ajout du site

This commit is contained in:
Camilla Schoeser
2026-05-29 21:38:59 +02:00
parent 4a07130d44
commit 6a71f91e2f
12475 changed files with 3055567 additions and 0 deletions
+1
View File
@@ -0,0 +1 @@
../drizzle-kit/bin.cjs
+1
View File
@@ -0,0 +1 @@
../@esbuild/linux-x64/bin/esbuild
Generated Vendored Symlink
+1
View File
@@ -0,0 +1 @@
../typescript/bin/tsc
+1
View File
@@ -0,0 +1 @@
../typescript/bin/tsserver
Generated Vendored Symlink
+1
View File
@@ -0,0 +1 @@
../tsx/dist/cli.mjs
+9
View File
@@ -0,0 +1,9 @@
The MIT License (MIT)
Copyright © 2025 Borewit
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.
+87
View File
@@ -0,0 +1,87 @@
[![CI](https://github.com/Borewit/text-codec/actions/workflows/ci.yml/badge.svg)](https://github.com/Borewit/text-codec/actions/workflows/ci.yml)
[![npm version](https://img.shields.io/npm/v/%40borewit%2Ftext-codec.svg)](https://www.npmjs.com/package/@borewit/text-codec)
[![npm downloads](http://img.shields.io/npm/dm/@borewit/text-codec.svg)](https://npmcharts.com/compare/@borewit/text-codec?interval=30)
![bundlejs](https://deno.bundlejs.com/?q=@borewit/text-codec&badge)
[![License: MIT](https://img.shields.io/badge/License-MIT-green.svg?logo=open-source-initiative&logoColor=white)](LICENSE.txt)
# `@borewit/text-codec`
A **lightweight polyfill for text encoders and decoders** covering a small set of commonly used encodings.
Some JavaScript runtimes provide limited or inconsistent encoding support through `TextEncoder` and `TextDecoder`.
Examples include environments like **Hermes (React Native)** or certain **Node.js builds with limited ICU support**.
This module provides **reliable encode/decode support for a small set of encodings that may be missing or unreliable in those environments**.
- If a native UTF-8 `TextEncoder` / `TextDecoder` is available, it is used.
- All other encodings are implemented by this library.
## Supported encodings
- `utf-8` / `utf8`
- `utf-16le`
- `ascii`
- `latin1` / `iso-8859-1`
- `windows-1252`
These encodings are commonly encountered in metadata formats and legacy text data.
## ✨ Features
- Encoding and decoding utilities
- Lightweight
- Typed API
## 📦 Installation
```sh
npm install @borewit/text-codec
```
# 📚 API Documentation
## `textDecode(bytes, encoding): string`
Decodes binary data into a JavaScript string.
**Parameters**
- `bytes` (`Uint8Array`) — The binary data to decode.
- `encoding` (`SupportedEncoding`, optional) — Encoding type. Defaults to `"utf-8"`.
**Returns**
- `string` — The decoded text.
**Example**
```js
import { textDecode } from "@borewit/text-codec";
const bytes = new Uint8Array([0x48, 0x65, 0x6c, 0x6c, 0x6f]);
const text = textDecode(bytes, "ascii");
console.log(text); // "Hello"
```
## `textEncode(input, encoding): Uint8Array`
Encodes a JavaScript string into binary form using the specified encoding.
**Parameters**
- `input` (`string`) — The string to encode.
- `encoding` (`SupportedEncoding`, optional) — Encoding type. Defaults to `"utf-8"`.
**Returns**
`Uint8Array` — The encoded binary data.
Example:
```js
import { textEncode } from "@borewit/text-codec";
const bytes = textEncode("Hello", "utf-16le");
console.log(bytes); // Uint8Array([...])
```
## 📜 Licence
This project is licensed under the [MIT License](LICENSE.txt). Feel free to use, modify, and distribute as needed.
+6
View File
@@ -0,0 +1,6 @@
export type SupportedEncoding = "utf-8" | "utf8" | "utf-16le" | "us-ascii" | "ascii" | "latin1" | "iso-8859-1" | "windows-1252";
/**
* Decode text from binary data
*/
export declare function textDecode(bytes: Uint8Array, encoding?: SupportedEncoding): string;
export declare function textEncode(input?: string, encoding?: SupportedEncoding): Uint8Array;
+380
View File
@@ -0,0 +1,380 @@
const WINDOWS_1252_EXTRA = {
0x80: "€", 0x82: "", 0x83: "ƒ", 0x84: "„", 0x85: "…", 0x86: "†",
0x87: "‡", 0x88: "ˆ", 0x89: "‰", 0x8a: "Š", 0x8b: "", 0x8c: "Œ",
0x8e: "Ž", 0x91: "", 0x92: "", 0x93: "“", 0x94: "”", 0x95: "•",
0x96: "", 0x97: "—", 0x98: "˜", 0x99: "™", 0x9a: "š", 0x9b: "",
0x9c: "œ", 0x9e: "ž", 0x9f: "Ÿ",
};
const WINDOWS_1252_REVERSE = {};
for (const [code, char] of Object.entries(WINDOWS_1252_EXTRA)) {
WINDOWS_1252_REVERSE[char] = Number.parseInt(code, 10);
}
let _utf8Decoder;
let _utf8Encoder;
function utf8Decoder() {
if (typeof globalThis.TextDecoder === "undefined")
return undefined;
return (_utf8Decoder !== null && _utf8Decoder !== void 0 ? _utf8Decoder : (_utf8Decoder = new globalThis.TextDecoder("utf-8")));
}
function utf8Encoder() {
if (typeof globalThis.TextEncoder === "undefined")
return undefined;
return (_utf8Encoder !== null && _utf8Encoder !== void 0 ? _utf8Encoder : (_utf8Encoder = new globalThis.TextEncoder()));
}
const CHUNK = 32 * 1024;
const REPLACEMENT = 0xfffd;
/**
* Decode text from binary data
*/
export function textDecode(bytes, encoding = "utf-8") {
switch (encoding.toLowerCase()) {
case "utf-8":
case "utf8": {
const dec = utf8Decoder();
return dec ? dec.decode(bytes) : decodeUTF8(bytes);
}
case "utf-16le":
return decodeUTF16LE(bytes);
case "us-ascii":
case "ascii":
return decodeASCII(bytes);
case "latin1":
case "iso-8859-1":
return decodeLatin1(bytes);
case "windows-1252":
return decodeWindows1252(bytes);
default:
throw new RangeError(`Encoding '${encoding}' not supported`);
}
}
export function textEncode(input = "", encoding = "utf-8") {
switch (encoding.toLowerCase()) {
case "utf-8":
case "utf8": {
const enc = utf8Encoder();
return enc ? enc.encode(input) : encodeUTF8(input);
}
case "utf-16le":
return encodeUTF16LE(input);
case "us-ascii":
case "ascii":
return encodeASCII(input);
case "latin1":
case "iso-8859-1":
return encodeLatin1(input);
case "windows-1252":
return encodeWindows1252(input);
default:
throw new RangeError(`Encoding '${encoding}' not supported`);
}
}
function appendCodePoint(out, cp) {
if (cp <= 0xffff) {
out.push(String.fromCharCode(cp));
return;
}
cp -= 0x10000;
out.push(String.fromCharCode(0xd800 + (cp >> 10), 0xdc00 + (cp & 0x3ff)));
}
function flushChunk(parts, chunk) {
if (chunk.length === 0)
return;
parts.push(String.fromCharCode.apply(null, chunk));
chunk.length = 0;
}
function pushCodeUnit(parts, chunk, codeUnit) {
chunk.push(codeUnit);
if (chunk.length >= CHUNK)
flushChunk(parts, chunk);
}
function pushCodePoint(parts, chunk, cp) {
if (cp <= 0xffff) {
pushCodeUnit(parts, chunk, cp);
return;
}
cp -= 0x10000;
pushCodeUnit(parts, chunk, 0xd800 + (cp >> 10));
pushCodeUnit(parts, chunk, 0xdc00 + (cp & 0x3ff));
}
function decodeUTF8(bytes) {
const parts = [];
const chunk = [];
let i = 0;
// Match TextDecoder("utf-8") default BOM handling
if (bytes.length >= 3 &&
bytes[0] === 0xef &&
bytes[1] === 0xbb &&
bytes[2] === 0xbf) {
i = 3;
}
while (i < bytes.length) {
const b1 = bytes[i];
if (b1 <= 0x7f) {
pushCodeUnit(parts, chunk, b1);
i++;
continue;
}
// Invalid leading bytes: continuation byte or impossible prefixes
if (b1 < 0xc2 || b1 > 0xf4) {
pushCodeUnit(parts, chunk, REPLACEMENT);
i++;
continue;
}
// 2-byte sequence
if (b1 <= 0xdf) {
if (i + 1 >= bytes.length) {
pushCodeUnit(parts, chunk, REPLACEMENT);
i++;
continue;
}
const b2 = bytes[i + 1];
if ((b2 & 0xc0) !== 0x80) {
pushCodeUnit(parts, chunk, REPLACEMENT);
i++;
continue;
}
const cp = ((b1 & 0x1f) << 6) | (b2 & 0x3f);
pushCodeUnit(parts, chunk, cp);
i += 2;
continue;
}
// 3-byte sequence
if (b1 <= 0xef) {
if (i + 2 >= bytes.length) {
pushCodeUnit(parts, chunk, REPLACEMENT);
i++;
continue;
}
const b2 = bytes[i + 1];
const b3 = bytes[i + 2];
const valid = (b2 & 0xc0) === 0x80 &&
(b3 & 0xc0) === 0x80 &&
!(b1 === 0xe0 && b2 < 0xa0) && // overlong
!(b1 === 0xed && b2 >= 0xa0); // surrogate range
if (!valid) {
pushCodeUnit(parts, chunk, REPLACEMENT);
i++;
continue;
}
const cp = ((b1 & 0x0f) << 12) |
((b2 & 0x3f) << 6) |
(b3 & 0x3f);
pushCodeUnit(parts, chunk, cp);
i += 3;
continue;
}
// 4-byte sequence
if (i + 3 >= bytes.length) {
pushCodeUnit(parts, chunk, REPLACEMENT);
i++;
continue;
}
const b2 = bytes[i + 1];
const b3 = bytes[i + 2];
const b4 = bytes[i + 3];
const valid = (b2 & 0xc0) === 0x80 &&
(b3 & 0xc0) === 0x80 &&
(b4 & 0xc0) === 0x80 &&
!(b1 === 0xf0 && b2 < 0x90) && // overlong
!(b1 === 0xf4 && b2 > 0x8f); // > U+10FFFF
if (!valid) {
pushCodeUnit(parts, chunk, REPLACEMENT);
i++;
continue;
}
const cp = ((b1 & 0x07) << 18) |
((b2 & 0x3f) << 12) |
((b3 & 0x3f) << 6) |
(b4 & 0x3f);
pushCodePoint(parts, chunk, cp);
i += 4;
}
flushChunk(parts, chunk);
return parts.join("");
}
function decodeUTF16LE(bytes) {
const parts = [];
const chunk = [];
const len = bytes.length;
let i = 0;
while (i + 1 < len) {
const u1 = bytes[i] | (bytes[i + 1] << 8);
i += 2;
// High surrogate
if (u1 >= 0xd800 && u1 <= 0xdbff) {
if (i + 1 < len) {
const u2 = bytes[i] | (bytes[i + 1] << 8);
if (u2 >= 0xdc00 && u2 <= 0xdfff) {
pushCodeUnit(parts, chunk, u1);
pushCodeUnit(parts, chunk, u2);
i += 2;
}
else {
pushCodeUnit(parts, chunk, REPLACEMENT);
}
}
else {
pushCodeUnit(parts, chunk, REPLACEMENT);
}
continue;
}
// Lone low surrogate
if (u1 >= 0xdc00 && u1 <= 0xdfff) {
pushCodeUnit(parts, chunk, REPLACEMENT);
continue;
}
pushCodeUnit(parts, chunk, u1);
}
// Odd trailing byte
if (i < len) {
pushCodeUnit(parts, chunk, REPLACEMENT);
}
flushChunk(parts, chunk);
return parts.join("");
}
function decodeASCII(bytes) {
const parts = [];
for (let i = 0; i < bytes.length; i += CHUNK) {
const end = Math.min(bytes.length, i + CHUNK);
const codes = new Array(end - i);
for (let j = i, k = 0; j < end; j++, k++) {
codes[k] = bytes[j] & 0x7f;
}
parts.push(String.fromCharCode.apply(null, codes));
}
return parts.join("");
}
function decodeLatin1(bytes) {
const parts = [];
for (let i = 0; i < bytes.length; i += CHUNK) {
const end = Math.min(bytes.length, i + CHUNK);
const codes = new Array(end - i);
for (let j = i, k = 0; j < end; j++, k++) {
codes[k] = bytes[j];
}
parts.push(String.fromCharCode.apply(null, codes));
}
return parts.join("");
}
function decodeWindows1252(bytes) {
const parts = [];
let out = "";
for (let i = 0; i < bytes.length; i++) {
const b = bytes[i];
const extra = b >= 0x80 && b <= 0x9f ? WINDOWS_1252_EXTRA[b] : undefined;
out += extra !== null && extra !== void 0 ? extra : String.fromCharCode(b);
if (out.length >= CHUNK) {
parts.push(out);
out = "";
}
}
if (out)
parts.push(out);
return parts.join("");
}
function encodeUTF8(str) {
const out = [];
for (let i = 0; i < str.length; i++) {
let cp = str.charCodeAt(i);
// Valid surrogate pair
if (cp >= 0xd800 && cp <= 0xdbff) {
if (i + 1 < str.length) {
const lo = str.charCodeAt(i + 1);
if (lo >= 0xdc00 && lo <= 0xdfff) {
cp = 0x10000 + ((cp - 0xd800) << 10) + (lo - 0xdc00);
i++;
}
else {
cp = REPLACEMENT;
}
}
else {
cp = REPLACEMENT;
}
}
else if (cp >= 0xdc00 && cp <= 0xdfff) {
// Lone low surrogate
cp = REPLACEMENT;
}
if (cp < 0x80) {
out.push(cp);
}
else if (cp < 0x800) {
out.push(0xc0 | (cp >> 6), 0x80 | (cp & 0x3f));
}
else if (cp < 0x10000) {
out.push(0xe0 | (cp >> 12), 0x80 | ((cp >> 6) & 0x3f), 0x80 | (cp & 0x3f));
}
else {
out.push(0xf0 | (cp >> 18), 0x80 | ((cp >> 12) & 0x3f), 0x80 | ((cp >> 6) & 0x3f), 0x80 | (cp & 0x3f));
}
}
return new Uint8Array(out);
}
function encodeUTF16LE(str) {
// Preserve JS string code units, but do not emit non-well-formed UTF-16.
// Replace lone surrogates with U+FFFD.
const units = [];
for (let i = 0; i < str.length; i++) {
const u = str.charCodeAt(i);
if (u >= 0xd800 && u <= 0xdbff) {
if (i + 1 < str.length) {
const lo = str.charCodeAt(i + 1);
if (lo >= 0xdc00 && lo <= 0xdfff) {
units.push(u, lo);
i++;
}
else {
units.push(REPLACEMENT);
}
}
else {
units.push(REPLACEMENT);
}
continue;
}
if (u >= 0xdc00 && u <= 0xdfff) {
units.push(REPLACEMENT);
continue;
}
units.push(u);
}
const out = new Uint8Array(units.length * 2);
for (let i = 0; i < units.length; i++) {
const code = units[i];
const o = i * 2;
out[o] = code & 0xff;
out[o + 1] = code >>> 8;
}
return out;
}
function encodeASCII(str) {
const out = new Uint8Array(str.length);
for (let i = 0; i < str.length; i++)
out[i] = str.charCodeAt(i) & 0x7f;
return out;
}
function encodeLatin1(str) {
const out = new Uint8Array(str.length);
for (let i = 0; i < str.length; i++)
out[i] = str.charCodeAt(i) & 0xff;
return out;
}
function encodeWindows1252(str) {
const out = new Uint8Array(str.length);
for (let i = 0; i < str.length; i++) {
const ch = str[i];
const code = ch.charCodeAt(0);
if (WINDOWS_1252_REVERSE[ch] !== undefined) {
out[i] = WINDOWS_1252_REVERSE[ch];
continue;
}
if ((code >= 0x00 && code <= 0x7f) ||
(code >= 0xa0 && code <= 0xff)) {
out[i] = code;
continue;
}
out[i] = 0x3f; // '?'
}
return out;
}
+70
View File
@@ -0,0 +1,70 @@
{
"name": "@borewit/text-codec",
"version": "0.2.2",
"description": "Text Decoder",
"type": "module",
"exports": "./lib/index.js",
"types": "lib/index.d.ts",
"files": [
"lib/index.js",
"lib/index.d.ts"
],
"scripts": {
"clean": "del-cli lib/**/*.js lib/***.js.map test/**/*.d.ts test/**/*.js test/**/*.js.map",
"build": "npm run compile",
"prepublishOnly": "npm run build",
"compile:src": "tsc --p lib --sourceMap false",
"compile:test": "tsc --p test",
"compile": "npm run compile:src && npm run compile:test",
"lint": "biome check",
"test": "mocha",
"update-biome": "npm install --save-dev --save-exact @biomejs/biome@latest && npx @biomejs/biome migrate --write"
},
"devDependencies": {
"@biomejs/biome": "2.4.6",
"@types/chai": "^5.2.2",
"@types/mocha": "^10.0.10",
"chai": "^6.2.2",
"mocha": "^11.7.5",
"ts-node": "^10.9.2",
"typescript": "^5.9.3"
},
"keywords": [
"TextDecoder",
"TextEncoder",
"decoder",
"decoding",
"encod",
"encoding",
"decode",
"text",
"ascii",
"utf-8",
"utf8",
"utf-16le",
"latin1",
"iso-8859-1",
"windows-1252",
"charset",
"encoding",
"decoding",
"polyfill",
"character-set",
"latin",
"hermes",
"react"
],
"repository": {
"type": "git",
"url": "git+https://github.com/Borewit/text-codec.git"
},
"author": {
"name": "Borewit",
"url": "https://github.com/Borewit"
},
"funding": {
"type": "github",
"url": "https://github.com/sponsors/Borewit"
},
"license": "MIT"
}
+464
View File
@@ -0,0 +1,464 @@
# Brocli 🥦
Modern type-safe way of building CLIs with TypeScript or JavaScript
by [Drizzle Team](https://drizzle.team)
```ts
import { command, string, boolean, run } from "@drizzle-team/brocli";
const push = command({
name: "push",
options: {
dialect: string().enum("postgresql", "mysql", "sqlite"),
databaseSchema: string().required(),
databaseUrl: string().required(),
strict: boolean().default(false),
},
handler: (opts) => {
...
},
});
run([push]); // parse shell arguments and run command
```
### Why?
Brocli is meant to solve a list of challenges we've faced while building
[Drizzle ORM](https://orm.drizzle.team) CLI companion for generating and running SQL schema migrations:
- [x] Explicit, straightforward and discoverable API
- [x] Typed options(arguments) with built in validation
- [x] Ability to reuse options(or option sets) across commands
- [x] Transformer hook to decouple runtime config consumption from command business logic
- [x] `--version`, `-v` as either string or callback
- [x] Command hooks to run common stuff before/after command
- [x] Explicit global params passthrough
- [x] Testability, the most important part for us to iterate without breaking
- [x] Themes, simple API to style global/command helps
- [x] Docs generation API to eliminate docs drifting
### Learn by examples
If you need API referece - [see here](#api-reference), this list of practical example
is meant to a be a zero to hero walk through for you to learn Brocli 🚀
Simple echo command with positional argument:
```ts
import { run, command, positional } from "@drizzle-team/brocli";
const echo = command({
name: "echo",
options: {
text: positional().desc("Text to echo").default("echo"),
},
handler: (opts) => {
console.log(opts.text);
},
});
run([echo])
```
```bash
~ bun run index.ts echo
echo
~ bun run index.ts echo text
text
```
Print version with `--version -v`:
```ts
...
run([echo], {
version: "1.0.0",
);
```
```bash
~ bun run index.ts --version
1.0.0
```
Version accepts async callback for you to do any kind of io if necessary before printing cli version:
```ts
import { run, command, positional } from "@drizzle-team/brocli";
const version = async () => {
// you can run async here, for example fetch version of runtime-dependend library
const envVersion = process.env.CLI_VERSION;
console.log(chalk.gray(envVersion), "\n");
};
const echo = command({ ... });
run([echo], {
version: version,
);
```
# API reference
[**`command`**](#command)
- [`command → name`](#command-name)
- [`command → desc`](#command-desc)
- [`command → shortDesc`](#command-shortDesc)
- [`command → aliases`](#command-aliases)
- [`command → options`](#command-options)
- [`command → transform`](#command-transform)
- [`command → handler`](#command-handler)
- [`command → help`](#command-help)
- [`command → hidden`](#command-hidden)
- [`command → metadata`](#command-metadata)
[**`options`**](#options)
- [`string`](#options-string)
- [`boolean`](#options-boolean)
- [`number`](#options-number)
- [`enum`](#options-enum)
- [`positional`](#options-positional)
- [`required`](#options-required)
- [`alias`](#options-alias)
- [`desc`](#options-desc)
- [`default`](#options-default)
- [`hidden`](#options-hidden)
[**`run`**](#run)
- [`string`](#options-string)
Brocli **`command`** declaration has:
`name` - command name, will be listed in `help`
`desc` - optional description, will be listed in the command `help`
`shortDesc` - optional short description, will be listed in the all commands/all subcommands `help`
`aliases` - command name aliases
`hidden` - flag to hide command from `help`
`help` - command help text or a callback to print help text with dynamically provided config
`options` - typed list of shell arguments to be parsed and provided to `transform` or `handler`
`transform` - optional hook, will be called before handler to modify CLI params
`handler` - called with either typed `options` or `transform` params, place to run your command business logic
`metadata` - optional meta information for docs generation flow
`name`, `desc`, `shortDesc` and `metadata` are provided to docs generation step
```ts
import { command, string, boolean } from "@drizzle-team/brocli";
const push = command({
name: "push",
options: {
dialect: string().enum("postgresql", "mysql", "sqlite"),
databaseSchema: string().required(),
databaseUrl: string().required(),
strict: boolean().default(false),
},
transform: (opts) => {
},
handler: (opts) => {
...
},
});
```
```ts
import { command } from "@drizzle-team/brocli";
const cmd = command({
name: "cmd",
options: {
dialect: string().enum("postgresql", "mysql", "sqlite"),
schema: string().required(),
url: string().required(),
},
handler: (opts) => {
...
},
});
```
### Option builder
Initial builder functions:
- `string(name?: string)` - defines option as a string-type option which requires data to be passed as `--option=value` or `--option value`
- `name` - name by which option is passed in cli args
If not specified, defaults to key of this option
:warning: - must not contain `=` character, not be in `--help`,`-h`,`--version`,`-v` and be unique per each command
:speech_balloon: - will be automatically prefixed with `-` if one character long, `--` if longer
If you wish to have only single hyphen as a prefix on multi character name - simply specify name with it: `string('-longname')`
- `number(name?: string)` - defines option as a number-type option which requires data to be passed as `--option=value` or `--option value`
- `name` - name by which option is passed in cli args
If not specified, defaults to key of this option
:warning: - must not contain `=` character, not be in `--help`,`-h`,`--version`,`-v` and be unique per each command
:speech_balloon: - will be automatically prefixed with `-` if one character long, `--` if longer
If you wish to have only single hyphen as a prefix on multi character name - simply specify name with it: `number('-longname')`
- `boolean(name?: string)` - defines option as a boolean-type option which requires data to be passed as `--option`
- `name` - name by which option is passed in cli args
If not specified, defaults to key of this option
:warning: - must not contain `=` character, not be in `--help`,`-h`,`--version`,`-v` and be unique per each command
:speech_balloon: - will be automatically prefixed with `-` if one character long, `--` if longer
If you wish to have only single hyphen as a prefix on multi character name - simply specify name with it: `boolean('-longname')`
- `positional(displayName?: string)` - defines option as a positional-type option which requires data to be passed after a command as `command value`
- `displayName` - name by which option is passed in cli args
If not specified, defaults to key of this option
:warning: - does not consume options and data that starts with
Extensions:
- `.alias(...aliases: string[])` - defines aliases for option
- `aliases` - aliases by which option is passed in cli args
:warning: - must not contain `=` character, not be in `--help`,`-h`,`--version`,`-v` and be unique per each command
:speech_balloon: - will be automatically prefixed with `-` if one character long, `--` if longer
If you wish to have only single hyphen as a prefix on multi character alias - simply specify alias with it: `.alias('-longname')`
- `.desc(description: string)` - defines description for option to be displayed in `help` command
- `.required()` - sets option as required, which means that application will print an error if it is not present in cli args
- `.default(value: string | boolean)` - sets default value for option which will be assigned to it in case it is not present in cli args
- `.hidden()` - sets option as hidden - option will be omitted from being displayed in `help` command
- `.enum(values: [string, ...string[]])` - limits values of string to one of specified here
- `values` - allowed enum values
- `.int()` - ensures that number is an integer
- `.min(value: number)` - specified minimal allowed value for numbers
- `value` - minimal allowed value
:warning: - does not limit defaults
- `.max(value: number)` - specified maximal allowed value for numbers
- `value` - maximal allowed value
:warning: - does not limit defaults
### Creating handlers
Normally, you can write handlers right in the `command()` function, however there might be cases where you'd want to define your handlers separately.
For such cases, you'd want to infer type of `options` that will be passes inside your handler.
You can do it using `TypeOf` type:
```Typescript
import { string, boolean, type TypeOf } from '@drizzle-team/brocli'
const commandOptions = {
opt1: string(),
opt2: boolean('flag').alias('f'),
// And so on...
}
export const commandHandler = (options: TypeOf<typeof commandOptions>) => {
// Your logic goes here...
}
```
Or by using `handler(options, myHandler () => {...})`
```Typescript
import { string, boolean, handler } from '@drizzle-team/brocli'
const commandOptions = {
opt1: string(),
opt2: boolean('flag').alias('f'),
// And so on...
}
export const commandHandler = handler(commandOptions, (options) => {
// Your logic goes here...
});
```
### Defining commands
To define commands, use `command()` function:
```Typescript
import { command, type Command, string, boolean, type TypeOf } from '@drizzle-team/brocli'
const commandOptions = {
opt1: string(),
opt2: boolean('flag').alias('f'),
// And so on...
}
const commands: Command[] = []
commands.push(command({
name: 'command',
aliases: ['c', 'cmd'],
desc: 'Description goes here',
shortDesc: 'Short description'
hidden: false,
options: commandOptions,
transform: (options) => {
// Preprocess options here...
return processedOptions
},
handler: (processedOptions) => {
// Your logic goes here...
},
help: () => 'This command works like this: ...',
subcommands: [
command(
// You can define subcommands like this
)
]
}));
```
Parameters:
- `name` - name by which command is searched in cli args
:warning: - must not start with `-` character, be equal to [`true`, `false`, `0`, `1`] (case-insensitive) and be unique per command collection
- `aliases` - aliases by which command is searched in cli args
:warning: - must not start with `-` character, be equal to [`true`, `false`, `0`, `1`] (case-insensitive) and be unique per command collection
- `desc` - description for command to be displayed in `help` command
- `shortDesc` - short description for command to be displayed in `help` command
- `hidden` - sets command as hidden - if `true`, command will be omitted from being displayed in `help` command
- `options` - object containing command options created using `string` and `boolean` functions
- `transform` - optional function to preprocess options before they are passed to handler
:warning: - type of return mutates type of handler's input
- `handler` - function, which will be executed in case of successful option parse
:warning: - must be present if your command doesn't have subcommands
If command has subcommands but no handler, help for this command is going to be called instead of handler
- `help` - function or string, which will be executed or printed when help is called for this command
:warning: - if passed, takes prevalence over theme's `commandHelp` event
- `subcommands` - subcommands for command
:warning: - command can't have subcommands and `positional` options at the same time
- `metadata` - any data that you want to attach to command to later use in docs generation step
### Running commands
After defining commands, you're going to need to execute `run` function to start command execution
```Typescript
import { command, type Command, run, string, boolean, type TypeOf } from '@drizzle-team/brocli'
const commandOptions = {
opt1: string(),
opt2: boolean('flag').alias('f'),
// And so on...
}
const commandHandler = (options: TypeOf<typeof commandOptions>) => {
// Your logic goes here...
}
const commands: Command[] = []
commands.push(command({
name: 'command',
aliases: ['c', 'cmd'],
desc: 'Description goes here',
hidden: false,
options: commandOptions,
handler: commandHandler,
}));
// And so on...
run(commands, {
name: 'mysoft',
description: 'MySoft CLI',
omitKeysOfUndefinedOptions: true,
argSource: customEnvironmentArgvStorage,
version: '1.0.0',
help: () => {
console.log('Command list:');
commands.forEach(c => console.log('This command does ... and has options ...'));
},
theme: async (event) => {
if (event.type === 'commandHelp') {
await myCustomUniversalCommandHelp(event.command);
return true;
}
if (event.type === 'unknownError') {
console.log('Something went wrong...');
return true;
}
return false;
},
hook: (event, command) => {
if(event === 'before') console.log(`Command '${command.name}' started`)
if(event === 'after') console.log(`Command '${command.name}' succesfully finished it's work`)
}
})
```
Parameters:
- `name` - name that's used to invoke your application from cli.
Used for themes that print usage examples, example:
`app do-task --help` results in `Usage: app do-task <positional> [flags] ...`
Default: `undefined`
- `description` - description of your app
Used for themes, example:
`myapp --help` results in
```
MyApp CLI
Usage: myapp [command]...
```
Default: `undefined`
- `omitKeysOfUndefinedOptions` - flag that determines whether undefined options will be passed to transform\handler or not
Default: `false`
- `argSource` - location of array of args in your environment
:warning: - first two items of this storage will be ignored as they typically contain executable and executed file paths
Default: `process.argv`
- `version` - string or handler used to print your app version
:warning: - if passed, takes prevalence over theme's version event
- `help` - string or handler used to print your app's global help
:warning: - if passed, takes prevalence over theme's `globalHelp` event
- `theme(event: BroCliEvent)` - function that's used to customize messages that are printed on various events
Return:
`true` | `Promise<true>` if you consider event processed
`false` | `Promise<false>` to redirect event to default theme
- `hook(event: EventType, command: Command)` - function that's used to execute code before and after every command's `transform` and `handler` execution
### Additional functions
- `commandsInfo(commands: Command[])` - get simplified representation of your command collection
Can be used to generate docs
- `test(command: Command, args: string)` - test behaviour for command with specified arguments
:warning: - if command has `transform`, it will get called, however `handler` won't
- `getCommandNameWithParents(command: Command)` - get subcommand's name with parent command names
## CLI
In `BroCLI`, command doesn't have to be the first argument, instead it may be passed in any order.
To make this possible, hovewer, option that's passed right before command should have an explicit value, even if it is a flag: `--verbose true <command-name>` (does not apply to reserved flags: [ `--help` | `-h` | `--version` | `-v`])
Options are parsed in strict mode, meaning that having any unrecognized options will result in an error.
File diff suppressed because it is too large Load Diff
File diff suppressed because one or more lines are too long
+298
View File
@@ -0,0 +1,298 @@
type OptionType = 'string' | 'boolean' | 'number' | 'positional';
type OutputType = string | boolean | number | undefined;
type BuilderConfig<TType extends OptionType = OptionType> = {
name?: string | undefined;
aliases: string[];
type: TType;
description?: string;
default?: OutputType;
isHidden?: boolean;
isRequired?: boolean;
isInt?: boolean;
minVal?: number;
maxVal?: number;
enumVals?: [string, ...string[]];
};
type ProcessedBuilderConfig = {
name: string;
aliases: string[];
type: OptionType;
description?: string;
default?: OutputType;
isHidden?: boolean;
isRequired?: boolean;
isInt?: boolean;
minVal?: number;
maxVal?: number;
enumVals?: [string, ...string[]];
};
type BuilderConfigLimited = BuilderConfig & {
type: Exclude<OptionType, 'positional'>;
};
declare class OptionBuilderBase<TBuilderConfig extends BuilderConfig = BuilderConfig, TOutput extends OutputType = string, TOmit extends string = '', TEnums extends string | undefined = undefined> {
_: {
config: TBuilderConfig;
/**
* Type-level only field
*
* Do not attempt to access at a runtime
*/
$output: TOutput;
};
private config;
constructor(config?: TBuilderConfig);
string<TName extends string>(name: TName): Omit<OptionBuilderBase<BuilderConfig<'string'>, string | undefined, TOmit | OptionType | 'min' | 'max' | 'int'>, TOmit | OptionType | 'min' | 'max' | 'int'>;
string(): Omit<OptionBuilderBase<BuilderConfig<'string'>, string | undefined, TOmit | OptionType | 'min' | 'max' | 'int'>, TOmit | OptionType | 'min' | 'max' | 'int'>;
number<TName extends string>(name: TName): Omit<OptionBuilderBase<BuilderConfig<'number'>, number | undefined, TOmit | OptionType | 'enum'>, TOmit | OptionType | 'enum'>;
number(): Omit<OptionBuilderBase<BuilderConfig<'number'>, string | undefined, TOmit | OptionType | 'enum'>, TOmit | OptionType | 'enum'>;
boolean<TName extends string>(name: TName): Omit<OptionBuilderBase<BuilderConfig<'boolean'>, boolean | undefined, TOmit | OptionType | 'min' | 'max' | 'enum' | 'int'>, TOmit | OptionType | 'min' | 'max' | 'enum' | 'int'>;
boolean(): Omit<OptionBuilderBase<BuilderConfig<'boolean'>, boolean | undefined, TOmit | OptionType | 'min' | 'max' | 'enum' | 'int'>, TOmit | OptionType | 'min' | 'max' | 'enum' | 'int'>;
positional<TName extends string>(displayName: TName): Omit<OptionBuilderBase<BuilderConfig<'positional'>, string | undefined, TOmit | OptionType | 'min' | 'max' | 'int' | 'alias'>, TOmit | OptionType | 'min' | 'max' | 'int' | 'alias'>;
positional(): Omit<OptionBuilderBase<BuilderConfig<'positional'>, string | undefined, TOmit | OptionType | 'min' | 'max' | 'int' | 'alias'>, TOmit | OptionType | 'min' | 'max' | 'int' | 'alias'>;
alias(...aliases: string[]): Omit<OptionBuilderBase<TBuilderConfig, TOutput, TOmit | 'alias'>, TOmit | 'alias'>;
desc<TDescription extends string>(description: TDescription): Omit<OptionBuilderBase<TBuilderConfig, TOutput, TOmit | 'desc'>, TOmit | 'desc'>;
hidden(): Omit<OptionBuilderBase<TBuilderConfig, TOutput, TOmit | 'hidden'>, TOmit | 'hidden'>;
required(): Omit<OptionBuilderBase<TBuilderConfig, Exclude<TOutput, undefined>, TOmit | 'required' | 'default'>, TOmit | 'required' | 'default'>;
default<TDefVal extends TEnums extends undefined ? Exclude<TOutput, undefined> : TEnums>(value: TDefVal): Omit<OptionBuilderBase<TBuilderConfig, Exclude<TOutput, undefined>, TOmit | 'enum' | 'required' | 'default', TEnums>, TOmit | 'enum' | 'required' | 'default'>;
enum<TValues extends [string, ...string[]], TUnion extends TValues[number] = TValues[number]>(...values: TValues): Omit<OptionBuilderBase<TBuilderConfig, TUnion | (TOutput extends undefined ? undefined : never), TOmit | 'enum', TUnion>, TOmit | 'enum'>;
min(value: number): Omit<OptionBuilderBase<TBuilderConfig, TOutput, TOmit | 'min'>, TOmit | 'min'>;
max(value: number): Omit<OptionBuilderBase<TBuilderConfig, TOutput, TOmit | 'max'>, TOmit | 'max'>;
int(): Omit<OptionBuilderBase<TBuilderConfig, TOutput, TOmit | 'int'>, TOmit | 'int'>;
}
type GenericBuilderInternalsFields = {
/**
* Type-level only field
*
* Do not attempt to access at a runtime
*/
$output: OutputType;
config: BuilderConfig;
};
type GenericBuilderInternals = {
_: GenericBuilderInternalsFields;
};
type GenericBuilderInternalsFieldsLimited = {
/**
* Type-level only field
*
* Do not attempt to access at a runtime
*/
$output: OutputType;
config: BuilderConfigLimited;
};
type GenericBuilderInternalsLimited = {
_: GenericBuilderInternalsFieldsLimited;
};
type ProcessedOptions<TOptionConfig extends Record<string, GenericBuilderInternals> = Record<string, GenericBuilderInternals>> = {
[K in keyof TOptionConfig]: K extends string ? {
config: ProcessedBuilderConfig;
/**
* Type-level only field
*
* Do not attempt to access at a runtime
*/
$output: TOptionConfig[K]['_']['$output'];
} : never;
};
type Simplify<T> = {
[K in keyof T]: T[K];
} & {};
type TypeOf<TOptions extends Record<string, GenericBuilderInternals>> = Simplify<{
[K in keyof TOptions]: TOptions[K]['_']['$output'];
}>;
declare function string<TName extends string>(name: TName): Omit<OptionBuilderBase<BuilderConfig<'string'>, string | undefined, OptionType | 'min' | 'max' | 'int'>, OptionType | 'min' | 'max' | 'int'>;
declare function string(): Omit<OptionBuilderBase<BuilderConfig<'string'>, string | undefined, OptionType | 'min' | 'max' | 'int'>, OptionType | 'min' | 'max' | 'int'>;
declare function number<TName extends string>(name: TName): Omit<OptionBuilderBase<BuilderConfig<'number'>, number | undefined, OptionType | 'enum'>, OptionType | 'enum'>;
declare function number(): Omit<OptionBuilderBase<BuilderConfig<'number'>, number | undefined, OptionType | 'enum'>, OptionType | 'enum'>;
declare function boolean<TName extends string>(name: TName): Omit<OptionBuilderBase<BuilderConfig<'boolean'>, boolean | undefined, OptionType | 'min' | 'max' | 'int' | 'enum'>, OptionType | 'min' | 'max' | 'int' | 'enum'>;
declare function boolean(): Omit<OptionBuilderBase<BuilderConfig<'boolean'>, boolean | undefined, OptionType | 'min' | 'max' | 'int' | 'enum'>, OptionType | 'min' | 'max' | 'int' | 'enum'>;
declare function positional<TName extends string>(displayName: TName): Omit<OptionBuilderBase<BuilderConfig<'positional'>, string | undefined, OptionType | 'min' | 'max' | 'int' | 'alias'>, OptionType | 'min' | 'max' | 'int' | 'alias'>;
declare function positional(): Omit<OptionBuilderBase<BuilderConfig<'positional'>, string | undefined, OptionType | 'min' | 'max' | 'int' | 'alias'>, OptionType | 'min' | 'max' | 'int' | 'alias'>;
type CommandHandler<TOpts extends Record<string, GenericBuilderInternals> | undefined = Record<string, GenericBuilderInternals> | undefined> = (options: TOpts extends Record<string, GenericBuilderInternals> ? TypeOf<TOpts> : undefined) => any;
type CommandInfo = {
name: string;
aliases?: [string, ...string[]];
desc?: string;
shortDesc?: string;
hidden?: boolean;
options?: Record<string, ProcessedBuilderConfig>;
metadata?: any;
subcommands?: CommandsInfo;
};
type CommandsInfo = Record<string, CommandInfo>;
type EventType = 'before' | 'after';
type BroCliConfig = {
name?: string;
description?: string;
argSource?: string[];
help?: string | Function;
version?: string | Function;
omitKeysOfUndefinedOptions?: boolean;
hook?: (event: EventType, command: Command) => any;
theme?: EventHandler;
};
type GenericCommandHandler = (options?: Record<string, OutputType> | undefined) => any;
type RawCommand<TOpts extends Record<string, GenericBuilderInternals> | undefined = Record<string, GenericBuilderInternals> | undefined, TOptsData = TOpts extends Record<string, GenericBuilderInternals> ? TypeOf<TOpts> : undefined, TTransformed = TOptsData extends undefined ? undefined : TOptsData> = {
name?: string;
aliases?: [string, ...string[]];
desc?: string;
shortDesc?: string;
hidden?: boolean;
options?: TOpts;
help?: string | Function;
transform?: (options: TOptsData) => TTransformed;
handler?: (options: Awaited<TTransformed>) => any;
subcommands?: [Command, ...Command[]];
metadata?: any;
};
type AnyRawCommand<TOpts extends Record<string, GenericBuilderInternals> | undefined = Record<string, GenericBuilderInternals> | undefined> = {
name?: string;
aliases?: [string, ...string[]];
desc?: string;
shortDesc?: string;
hidden?: boolean;
options?: TOpts;
help?: string | Function;
transform?: GenericCommandHandler;
handler?: GenericCommandHandler;
subcommands?: [Command, ...Command[]];
metadata?: any;
};
type Command<TOptsType = any, TTransformedType = any> = {
name: string;
aliases?: [string, ...string[]];
desc?: string;
shortDesc?: string;
hidden?: boolean;
options?: ProcessedOptions;
help?: string | Function;
transform?: GenericCommandHandler;
handler?: GenericCommandHandler;
subcommands?: [Command, ...Command[]];
parent?: Command;
metadata?: any;
};
type CommandCandidate = {
data: string;
originalIndex: number;
};
type InnerCommandParseRes = {
command: Command | undefined;
args: string[];
};
type TestResult<THandlerInput> = {
type: 'handler';
options: THandlerInput;
} | {
type: 'help' | 'version';
} | {
type: 'error';
error: unknown;
};
declare const command: <TOpts extends Record<string, GenericBuilderInternals> | undefined, TOptsData = TOpts extends Record<string, GenericBuilderInternals> ? { [K_1 in keyof { [K in keyof TOpts]: TOpts[K]["_"]["$output"]; }]: { [K in keyof TOpts]: TOpts[K]["_"]["$output"]; }[K_1]; } : undefined, TTransformed = TOptsData>(command: RawCommand<TOpts, TOptsData, TTransformed>) => Command<TOptsData, Awaited<TTransformed>>;
declare const getCommandNameWithParents: (command: Command) => string;
/**
* Runs CLI commands
*
* @param commands - command collection
*
* @param config - additional settings
*/
declare const run: (commands: Command[], config?: BroCliConfig) => Promise<void>;
declare const handler: <TOpts extends Record<string, GenericBuilderInternals>>(options: TOpts, handler: CommandHandler<TOpts>) => CommandHandler<TOpts>;
declare const test: <TOpts, THandlerInput>(command: Command<TOpts, THandlerInput>, args: string) => Promise<TestResult<THandlerInput>>;
declare const commandsInfo: (commands: Command[]) => CommandsInfo;
type CommandHelpEvent = {
type: 'command_help';
name: string | undefined;
description: string | undefined;
command: Command;
};
type GlobalHelpEvent = {
type: 'global_help';
description: string | undefined;
name: string | undefined;
commands: Command[];
};
type MissingArgsEvent = {
type: 'error';
violation: 'missing_args_error';
name: string | undefined;
description: string | undefined;
command: Command;
missing: [string[], ...string[][]];
};
type UnrecognizedArgsEvent = {
type: 'error';
violation: 'unrecognized_args_error';
name: string | undefined;
description: string | undefined;
command: Command;
unrecognized: [string, ...string[]];
};
type UnknownCommandEvent = {
type: 'error';
violation: 'unknown_command_error';
name: string | undefined;
description: string | undefined;
commands: Command[];
offender: string;
};
type UnknownSubcommandEvent = {
type: 'error';
violation: 'unknown_subcommand_error';
name: string | undefined;
description: string | undefined;
command: Command;
offender: string;
};
type UnknownErrorEvent = {
type: 'error';
violation: 'unknown_error';
name: string | undefined;
description: string | undefined;
error: unknown;
};
type VersionEvent = {
type: 'version';
name: string | undefined;
description: string | undefined;
};
type GenericValidationViolation = 'above_max' | 'below_min' | 'expected_int' | 'invalid_boolean_syntax' | 'invalid_string_syntax' | 'invalid_number_syntax' | 'invalid_number_value' | 'enum_violation';
type ValidationViolation = BroCliEvent extends infer Event ? Event extends {
violation: string;
} ? Event['violation'] : never : never;
type ValidationErrorEvent = {
type: 'error';
violation: GenericValidationViolation;
name: string | undefined;
description: string | undefined;
command: Command;
option: ProcessedBuilderConfig;
offender: {
namePart?: string;
dataPart?: string;
};
};
type BroCliEvent = CommandHelpEvent | GlobalHelpEvent | MissingArgsEvent | UnrecognizedArgsEvent | UnknownCommandEvent | UnknownSubcommandEvent | ValidationErrorEvent | VersionEvent | UnknownErrorEvent;
type BroCliEventType = BroCliEvent['type'];
/**
* Return `true` if your handler processes the event
*
* Return `false` to process event with a built-in handler
*/
type EventHandler = (event: BroCliEvent) => boolean | Promise<boolean>;
/**
* Internal error class used to bypass runCli's logging without stack trace
*
* Used only for malformed commands and options
*/
declare class BroCliError extends Error {
event?: BroCliEvent | undefined;
constructor(message: string | undefined, event?: BroCliEvent | undefined);
}
export { type AnyRawCommand, type BroCliConfig, BroCliError, type BroCliEvent, type BroCliEventType, type BuilderConfig, type BuilderConfigLimited, type Command, type CommandCandidate, type CommandHandler, type CommandHelpEvent, type CommandInfo, type CommandsInfo, type EventHandler, type EventType, type GenericBuilderInternals, type GenericBuilderInternalsFields, type GenericBuilderInternalsFieldsLimited, type GenericBuilderInternalsLimited, type GenericCommandHandler, type GenericValidationViolation, type GlobalHelpEvent, type InnerCommandParseRes, type MissingArgsEvent, OptionBuilderBase, type OptionType, type OutputType, type ProcessedBuilderConfig, type ProcessedOptions, type RawCommand, type Simplify, type TestResult, type TypeOf, type UnknownCommandEvent, type UnknownErrorEvent, type UnknownSubcommandEvent, type UnrecognizedArgsEvent, type ValidationErrorEvent, type ValidationViolation, type VersionEvent, boolean, command, commandsInfo, getCommandNameWithParents, handler, number, positional, run, string, test };
+298
View File
@@ -0,0 +1,298 @@
type OptionType = 'string' | 'boolean' | 'number' | 'positional';
type OutputType = string | boolean | number | undefined;
type BuilderConfig<TType extends OptionType = OptionType> = {
name?: string | undefined;
aliases: string[];
type: TType;
description?: string;
default?: OutputType;
isHidden?: boolean;
isRequired?: boolean;
isInt?: boolean;
minVal?: number;
maxVal?: number;
enumVals?: [string, ...string[]];
};
type ProcessedBuilderConfig = {
name: string;
aliases: string[];
type: OptionType;
description?: string;
default?: OutputType;
isHidden?: boolean;
isRequired?: boolean;
isInt?: boolean;
minVal?: number;
maxVal?: number;
enumVals?: [string, ...string[]];
};
type BuilderConfigLimited = BuilderConfig & {
type: Exclude<OptionType, 'positional'>;
};
declare class OptionBuilderBase<TBuilderConfig extends BuilderConfig = BuilderConfig, TOutput extends OutputType = string, TOmit extends string = '', TEnums extends string | undefined = undefined> {
_: {
config: TBuilderConfig;
/**
* Type-level only field
*
* Do not attempt to access at a runtime
*/
$output: TOutput;
};
private config;
constructor(config?: TBuilderConfig);
string<TName extends string>(name: TName): Omit<OptionBuilderBase<BuilderConfig<'string'>, string | undefined, TOmit | OptionType | 'min' | 'max' | 'int'>, TOmit | OptionType | 'min' | 'max' | 'int'>;
string(): Omit<OptionBuilderBase<BuilderConfig<'string'>, string | undefined, TOmit | OptionType | 'min' | 'max' | 'int'>, TOmit | OptionType | 'min' | 'max' | 'int'>;
number<TName extends string>(name: TName): Omit<OptionBuilderBase<BuilderConfig<'number'>, number | undefined, TOmit | OptionType | 'enum'>, TOmit | OptionType | 'enum'>;
number(): Omit<OptionBuilderBase<BuilderConfig<'number'>, string | undefined, TOmit | OptionType | 'enum'>, TOmit | OptionType | 'enum'>;
boolean<TName extends string>(name: TName): Omit<OptionBuilderBase<BuilderConfig<'boolean'>, boolean | undefined, TOmit | OptionType | 'min' | 'max' | 'enum' | 'int'>, TOmit | OptionType | 'min' | 'max' | 'enum' | 'int'>;
boolean(): Omit<OptionBuilderBase<BuilderConfig<'boolean'>, boolean | undefined, TOmit | OptionType | 'min' | 'max' | 'enum' | 'int'>, TOmit | OptionType | 'min' | 'max' | 'enum' | 'int'>;
positional<TName extends string>(displayName: TName): Omit<OptionBuilderBase<BuilderConfig<'positional'>, string | undefined, TOmit | OptionType | 'min' | 'max' | 'int' | 'alias'>, TOmit | OptionType | 'min' | 'max' | 'int' | 'alias'>;
positional(): Omit<OptionBuilderBase<BuilderConfig<'positional'>, string | undefined, TOmit | OptionType | 'min' | 'max' | 'int' | 'alias'>, TOmit | OptionType | 'min' | 'max' | 'int' | 'alias'>;
alias(...aliases: string[]): Omit<OptionBuilderBase<TBuilderConfig, TOutput, TOmit | 'alias'>, TOmit | 'alias'>;
desc<TDescription extends string>(description: TDescription): Omit<OptionBuilderBase<TBuilderConfig, TOutput, TOmit | 'desc'>, TOmit | 'desc'>;
hidden(): Omit<OptionBuilderBase<TBuilderConfig, TOutput, TOmit | 'hidden'>, TOmit | 'hidden'>;
required(): Omit<OptionBuilderBase<TBuilderConfig, Exclude<TOutput, undefined>, TOmit | 'required' | 'default'>, TOmit | 'required' | 'default'>;
default<TDefVal extends TEnums extends undefined ? Exclude<TOutput, undefined> : TEnums>(value: TDefVal): Omit<OptionBuilderBase<TBuilderConfig, Exclude<TOutput, undefined>, TOmit | 'enum' | 'required' | 'default', TEnums>, TOmit | 'enum' | 'required' | 'default'>;
enum<TValues extends [string, ...string[]], TUnion extends TValues[number] = TValues[number]>(...values: TValues): Omit<OptionBuilderBase<TBuilderConfig, TUnion | (TOutput extends undefined ? undefined : never), TOmit | 'enum', TUnion>, TOmit | 'enum'>;
min(value: number): Omit<OptionBuilderBase<TBuilderConfig, TOutput, TOmit | 'min'>, TOmit | 'min'>;
max(value: number): Omit<OptionBuilderBase<TBuilderConfig, TOutput, TOmit | 'max'>, TOmit | 'max'>;
int(): Omit<OptionBuilderBase<TBuilderConfig, TOutput, TOmit | 'int'>, TOmit | 'int'>;
}
type GenericBuilderInternalsFields = {
/**
* Type-level only field
*
* Do not attempt to access at a runtime
*/
$output: OutputType;
config: BuilderConfig;
};
type GenericBuilderInternals = {
_: GenericBuilderInternalsFields;
};
type GenericBuilderInternalsFieldsLimited = {
/**
* Type-level only field
*
* Do not attempt to access at a runtime
*/
$output: OutputType;
config: BuilderConfigLimited;
};
type GenericBuilderInternalsLimited = {
_: GenericBuilderInternalsFieldsLimited;
};
type ProcessedOptions<TOptionConfig extends Record<string, GenericBuilderInternals> = Record<string, GenericBuilderInternals>> = {
[K in keyof TOptionConfig]: K extends string ? {
config: ProcessedBuilderConfig;
/**
* Type-level only field
*
* Do not attempt to access at a runtime
*/
$output: TOptionConfig[K]['_']['$output'];
} : never;
};
type Simplify<T> = {
[K in keyof T]: T[K];
} & {};
type TypeOf<TOptions extends Record<string, GenericBuilderInternals>> = Simplify<{
[K in keyof TOptions]: TOptions[K]['_']['$output'];
}>;
declare function string<TName extends string>(name: TName): Omit<OptionBuilderBase<BuilderConfig<'string'>, string | undefined, OptionType | 'min' | 'max' | 'int'>, OptionType | 'min' | 'max' | 'int'>;
declare function string(): Omit<OptionBuilderBase<BuilderConfig<'string'>, string | undefined, OptionType | 'min' | 'max' | 'int'>, OptionType | 'min' | 'max' | 'int'>;
declare function number<TName extends string>(name: TName): Omit<OptionBuilderBase<BuilderConfig<'number'>, number | undefined, OptionType | 'enum'>, OptionType | 'enum'>;
declare function number(): Omit<OptionBuilderBase<BuilderConfig<'number'>, number | undefined, OptionType | 'enum'>, OptionType | 'enum'>;
declare function boolean<TName extends string>(name: TName): Omit<OptionBuilderBase<BuilderConfig<'boolean'>, boolean | undefined, OptionType | 'min' | 'max' | 'int' | 'enum'>, OptionType | 'min' | 'max' | 'int' | 'enum'>;
declare function boolean(): Omit<OptionBuilderBase<BuilderConfig<'boolean'>, boolean | undefined, OptionType | 'min' | 'max' | 'int' | 'enum'>, OptionType | 'min' | 'max' | 'int' | 'enum'>;
declare function positional<TName extends string>(displayName: TName): Omit<OptionBuilderBase<BuilderConfig<'positional'>, string | undefined, OptionType | 'min' | 'max' | 'int' | 'alias'>, OptionType | 'min' | 'max' | 'int' | 'alias'>;
declare function positional(): Omit<OptionBuilderBase<BuilderConfig<'positional'>, string | undefined, OptionType | 'min' | 'max' | 'int' | 'alias'>, OptionType | 'min' | 'max' | 'int' | 'alias'>;
type CommandHandler<TOpts extends Record<string, GenericBuilderInternals> | undefined = Record<string, GenericBuilderInternals> | undefined> = (options: TOpts extends Record<string, GenericBuilderInternals> ? TypeOf<TOpts> : undefined) => any;
type CommandInfo = {
name: string;
aliases?: [string, ...string[]];
desc?: string;
shortDesc?: string;
hidden?: boolean;
options?: Record<string, ProcessedBuilderConfig>;
metadata?: any;
subcommands?: CommandsInfo;
};
type CommandsInfo = Record<string, CommandInfo>;
type EventType = 'before' | 'after';
type BroCliConfig = {
name?: string;
description?: string;
argSource?: string[];
help?: string | Function;
version?: string | Function;
omitKeysOfUndefinedOptions?: boolean;
hook?: (event: EventType, command: Command) => any;
theme?: EventHandler;
};
type GenericCommandHandler = (options?: Record<string, OutputType> | undefined) => any;
type RawCommand<TOpts extends Record<string, GenericBuilderInternals> | undefined = Record<string, GenericBuilderInternals> | undefined, TOptsData = TOpts extends Record<string, GenericBuilderInternals> ? TypeOf<TOpts> : undefined, TTransformed = TOptsData extends undefined ? undefined : TOptsData> = {
name?: string;
aliases?: [string, ...string[]];
desc?: string;
shortDesc?: string;
hidden?: boolean;
options?: TOpts;
help?: string | Function;
transform?: (options: TOptsData) => TTransformed;
handler?: (options: Awaited<TTransformed>) => any;
subcommands?: [Command, ...Command[]];
metadata?: any;
};
type AnyRawCommand<TOpts extends Record<string, GenericBuilderInternals> | undefined = Record<string, GenericBuilderInternals> | undefined> = {
name?: string;
aliases?: [string, ...string[]];
desc?: string;
shortDesc?: string;
hidden?: boolean;
options?: TOpts;
help?: string | Function;
transform?: GenericCommandHandler;
handler?: GenericCommandHandler;
subcommands?: [Command, ...Command[]];
metadata?: any;
};
type Command<TOptsType = any, TTransformedType = any> = {
name: string;
aliases?: [string, ...string[]];
desc?: string;
shortDesc?: string;
hidden?: boolean;
options?: ProcessedOptions;
help?: string | Function;
transform?: GenericCommandHandler;
handler?: GenericCommandHandler;
subcommands?: [Command, ...Command[]];
parent?: Command;
metadata?: any;
};
type CommandCandidate = {
data: string;
originalIndex: number;
};
type InnerCommandParseRes = {
command: Command | undefined;
args: string[];
};
type TestResult<THandlerInput> = {
type: 'handler';
options: THandlerInput;
} | {
type: 'help' | 'version';
} | {
type: 'error';
error: unknown;
};
declare const command: <TOpts extends Record<string, GenericBuilderInternals> | undefined, TOptsData = TOpts extends Record<string, GenericBuilderInternals> ? { [K_1 in keyof { [K in keyof TOpts]: TOpts[K]["_"]["$output"]; }]: { [K in keyof TOpts]: TOpts[K]["_"]["$output"]; }[K_1]; } : undefined, TTransformed = TOptsData>(command: RawCommand<TOpts, TOptsData, TTransformed>) => Command<TOptsData, Awaited<TTransformed>>;
declare const getCommandNameWithParents: (command: Command) => string;
/**
* Runs CLI commands
*
* @param commands - command collection
*
* @param config - additional settings
*/
declare const run: (commands: Command[], config?: BroCliConfig) => Promise<void>;
declare const handler: <TOpts extends Record<string, GenericBuilderInternals>>(options: TOpts, handler: CommandHandler<TOpts>) => CommandHandler<TOpts>;
declare const test: <TOpts, THandlerInput>(command: Command<TOpts, THandlerInput>, args: string) => Promise<TestResult<THandlerInput>>;
declare const commandsInfo: (commands: Command[]) => CommandsInfo;
type CommandHelpEvent = {
type: 'command_help';
name: string | undefined;
description: string | undefined;
command: Command;
};
type GlobalHelpEvent = {
type: 'global_help';
description: string | undefined;
name: string | undefined;
commands: Command[];
};
type MissingArgsEvent = {
type: 'error';
violation: 'missing_args_error';
name: string | undefined;
description: string | undefined;
command: Command;
missing: [string[], ...string[][]];
};
type UnrecognizedArgsEvent = {
type: 'error';
violation: 'unrecognized_args_error';
name: string | undefined;
description: string | undefined;
command: Command;
unrecognized: [string, ...string[]];
};
type UnknownCommandEvent = {
type: 'error';
violation: 'unknown_command_error';
name: string | undefined;
description: string | undefined;
commands: Command[];
offender: string;
};
type UnknownSubcommandEvent = {
type: 'error';
violation: 'unknown_subcommand_error';
name: string | undefined;
description: string | undefined;
command: Command;
offender: string;
};
type UnknownErrorEvent = {
type: 'error';
violation: 'unknown_error';
name: string | undefined;
description: string | undefined;
error: unknown;
};
type VersionEvent = {
type: 'version';
name: string | undefined;
description: string | undefined;
};
type GenericValidationViolation = 'above_max' | 'below_min' | 'expected_int' | 'invalid_boolean_syntax' | 'invalid_string_syntax' | 'invalid_number_syntax' | 'invalid_number_value' | 'enum_violation';
type ValidationViolation = BroCliEvent extends infer Event ? Event extends {
violation: string;
} ? Event['violation'] : never : never;
type ValidationErrorEvent = {
type: 'error';
violation: GenericValidationViolation;
name: string | undefined;
description: string | undefined;
command: Command;
option: ProcessedBuilderConfig;
offender: {
namePart?: string;
dataPart?: string;
};
};
type BroCliEvent = CommandHelpEvent | GlobalHelpEvent | MissingArgsEvent | UnrecognizedArgsEvent | UnknownCommandEvent | UnknownSubcommandEvent | ValidationErrorEvent | VersionEvent | UnknownErrorEvent;
type BroCliEventType = BroCliEvent['type'];
/**
* Return `true` if your handler processes the event
*
* Return `false` to process event with a built-in handler
*/
type EventHandler = (event: BroCliEvent) => boolean | Promise<boolean>;
/**
* Internal error class used to bypass runCli's logging without stack trace
*
* Used only for malformed commands and options
*/
declare class BroCliError extends Error {
event?: BroCliEvent | undefined;
constructor(message: string | undefined, event?: BroCliEvent | undefined);
}
export { type AnyRawCommand, type BroCliConfig, BroCliError, type BroCliEvent, type BroCliEventType, type BuilderConfig, type BuilderConfigLimited, type Command, type CommandCandidate, type CommandHandler, type CommandHelpEvent, type CommandInfo, type CommandsInfo, type EventHandler, type EventType, type GenericBuilderInternals, type GenericBuilderInternalsFields, type GenericBuilderInternalsFieldsLimited, type GenericBuilderInternalsLimited, type GenericCommandHandler, type GenericValidationViolation, type GlobalHelpEvent, type InnerCommandParseRes, type MissingArgsEvent, OptionBuilderBase, type OptionType, type OutputType, type ProcessedBuilderConfig, type ProcessedOptions, type RawCommand, type Simplify, type TestResult, type TypeOf, type UnknownCommandEvent, type UnknownErrorEvent, type UnknownSubcommandEvent, type UnrecognizedArgsEvent, type ValidationErrorEvent, type ValidationViolation, type VersionEvent, boolean, command, commandsInfo, getCommandNameWithParents, handler, number, positional, run, string, test };
File diff suppressed because it is too large Load Diff
File diff suppressed because one or more lines are too long
+59
View File
@@ -0,0 +1,59 @@
{
"name": "@drizzle-team/brocli",
"type": "module",
"author": "Drizzle Team",
"version": "0.10.2",
"description": "Modern type-safe way of building CLIs",
"license": "Apache-2.0",
"sideEffects": false,
"publishConfig": {
"provenance": true
},
"repository": {
"type": "git",
"url": "git+https://github.com/drizzle-team/brocli.git"
},
"homepage": "https://github.com/drizzle-team/brocli",
"scripts": {
"build": "pnpm tsx scripts/build.ts",
"b": "pnpm build",
"pack": "(cd dist && npm pack --pack-destination ..) && rm -f package.tgz && mv *.tgz package.tgz",
"publish": "npm publish package.tgz",
"test": "vitest run && npx tsc --noEmit",
"mtest": "npx tsx tests/manual.ts",
"lint": "dprint check --list-different"
},
"devDependencies": {
"@arethetypeswrong/cli": "^0.15.3",
"@originjs/vite-plugin-commonjs": "^1.0.3",
"@types/clone": "^2.1.4",
"@types/node": "^20.12.13",
"@types/shell-quote": "^1.7.5",
"clone": "^2.1.2",
"dprint": "^0.46.2",
"shell-quote": "^1.8.1",
"tsup": "^8.1.0",
"tsx": "^4.7.0",
"typescript": "latest",
"vite-tsconfig-paths": "^4.3.2",
"vitest": "^1.6.0",
"zx": "^8.1.2"
},
"main": "./index.cjs",
"module": "./index.js",
"types": "./index.d.ts",
"exports": {
".": {
"import": {
"types": "./index.d.ts",
"default": "./index.js"
},
"require": {
"types": "./index.d.cjs",
"default": "./index.cjs"
},
"types": "./index.d.ts",
"default": "./index.js"
}
}
}
+7
View File
@@ -0,0 +1,7 @@
Copyright 2022 saltyAom
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.
+114
View File
@@ -0,0 +1,114 @@
# @elysiajs/cors
Plugin for [elysia](https://github.com/elysiajs/elysia) that for Cross Origin Requests (CORs)
## Installation
```bash
bun add @elysiajs/cors
```
## Example
```typescript
import { Elysia } from 'elysia'
import { cors } from '@elysiajs/cors'
const app = new Elysia()
.use(cors())
.listen(8080)
```
## Config
### origin
@default `true`
Assign the **Access-Control-Allow-Origin** header.
Value can be one of the following:
- `string` - String of origin which will directly assign to `Access-Control-Allow-Origin`
- `boolean` - If set to true, `Access-Control-Allow-Origin` will be set to `*` (accept all origin)
- `RegExp` - Pattern to use to test with request's url, will accept origin if matched.
- `Function` - Custom logic to validate origin acceptance or not. will accept origin if `true` is returned.
- Function will accepts `Context` just like `Handler`
```typescript
// Example usage
app.use(cors, {
origin: ({ request, headers }) => true
})
// Type Definition
type CORSOriginFn = (context: Context) => boolean | void
```
- `Array<string | RegExp | Function>` - Will try to find truthy value of all options above. Will accept Request if one is `true`.
### methods
@default `*`
Assign **Access-Control-Allow-Methods** header.
Value can be one of the following:
Accept:
- `undefined | null | ''` - Ignore all methods.
- `*` - Accept all methods.
- `HTTPMethod` - Will be directly set to **Access-Control-Allow-Methods**.
- Expects either a single method or a comma-delimited string (eg: 'GET, PUT, POST')
- `HTTPMethod[]` - Allow multiple HTTP methods.
- eg: ['GET', 'PUT', 'POST']
### allowedHeaders
@default `*`
Assign **Access-Control-Allow-Headers** header.
Allow incoming request with the specified headers.
Value can be one of the following:
- `string`
- Expects either a single method or a comma-delimited string (eg: 'Content-Type, Authorization').
- `string[]` - Allow multiple HTTP methods.
- eg: ['Content-Type', 'Authorization']
### exposedHeaders
@default `*`
Assign **Access-Control-Exposed-Headers** header.
Return the specified headers to request in CORS mode.
Value can be one of the following:
- `string`
- Expects either a single method or a comma-delimited string (eg: 'Content-Type, 'X-Powered-By').
- `string[]` - Allow multiple HTTP methods.
- eg: ['Content-Type', 'X-Powered-By']
### credentials
@default `true`
Assign **Access-Control-Allow-Credentials** header.
Allow incoming requests to send `credentials` header.
- `boolean` - Available if set to `true`.
### maxAge
@default `5`
Assign **Access-Control-Max-Age** header.
Allow incoming requests to send `credentials` header.
- `number` - Duration in seconds to indicates how long the results of a preflight request can be cached.
### preflight
@default `true`
Add `[OPTIONS] /*` handler to handle preflight request which response with `HTTP 204` and CORS hints.
- `boolean` - Available if set to `true`.
+493
View File
@@ -0,0 +1,493 @@
{
"lockfileVersion": 1,
"configVersion": 0,
"workspaces": {
"": {
"name": "@elysiajs/cors",
"devDependencies": {
"@types/bun": "1.1.14",
"@types/node": "^20.14.10",
"elysia": "1.4.0",
"eslint": "9.6.0",
"tsup": "^8.1.0",
"typescript": "^5.5.2",
},
"peerDependencies": {
"elysia": ">= 1.4.0",
},
},
},
"packages": {
"@borewit/text-codec": ["@borewit/text-codec@0.1.1", "", {}, "sha512-5L/uBxmjaCIX5h8Z+uu+kA9BQLkc/Wl06UGR5ajNRxu+/XjonB5i8JpgFMrPj3LXTCPA0pv8yxUvbUi+QthGGA=="],
"@esbuild/aix-ppc64": ["@esbuild/aix-ppc64@0.25.9", "", { "os": "aix", "cpu": "ppc64" }, "sha512-OaGtL73Jck6pBKjNIe24BnFE6agGl+6KxDtTfHhy1HmhthfKouEcOhqpSL64K4/0WCtbKFLOdzD/44cJ4k9opA=="],
"@esbuild/android-arm": ["@esbuild/android-arm@0.25.9", "", { "os": "android", "cpu": "arm" }, "sha512-5WNI1DaMtxQ7t7B6xa572XMXpHAaI/9Hnhk8lcxF4zVN4xstUgTlvuGDorBguKEnZO70qwEcLpfifMLoxiPqHQ=="],
"@esbuild/android-arm64": ["@esbuild/android-arm64@0.25.9", "", { "os": "android", "cpu": "arm64" }, "sha512-IDrddSmpSv51ftWslJMvl3Q2ZT98fUSL2/rlUXuVqRXHCs5EUF1/f+jbjF5+NG9UffUDMCiTyh8iec7u8RlTLg=="],
"@esbuild/android-x64": ["@esbuild/android-x64@0.25.9", "", { "os": "android", "cpu": "x64" }, "sha512-I853iMZ1hWZdNllhVZKm34f4wErd4lMyeV7BLzEExGEIZYsOzqDWDf+y082izYUE8gtJnYHdeDpN/6tUdwvfiw=="],
"@esbuild/darwin-arm64": ["@esbuild/darwin-arm64@0.25.9", "", { "os": "darwin", "cpu": "arm64" }, "sha512-XIpIDMAjOELi/9PB30vEbVMs3GV1v2zkkPnuyRRURbhqjyzIINwj+nbQATh4H9GxUgH1kFsEyQMxwiLFKUS6Rg=="],
"@esbuild/darwin-x64": ["@esbuild/darwin-x64@0.25.9", "", { "os": "darwin", "cpu": "x64" }, "sha512-jhHfBzjYTA1IQu8VyrjCX4ApJDnH+ez+IYVEoJHeqJm9VhG9Dh2BYaJritkYK3vMaXrf7Ogr/0MQ8/MeIefsPQ=="],
"@esbuild/freebsd-arm64": ["@esbuild/freebsd-arm64@0.25.9", "", { "os": "freebsd", "cpu": "arm64" }, "sha512-z93DmbnY6fX9+KdD4Ue/H6sYs+bhFQJNCPZsi4XWJoYblUqT06MQUdBCpcSfuiN72AbqeBFu5LVQTjfXDE2A6Q=="],
"@esbuild/freebsd-x64": ["@esbuild/freebsd-x64@0.25.9", "", { "os": "freebsd", "cpu": "x64" }, "sha512-mrKX6H/vOyo5v71YfXWJxLVxgy1kyt1MQaD8wZJgJfG4gq4DpQGpgTB74e5yBeQdyMTbgxp0YtNj7NuHN0PoZg=="],
"@esbuild/linux-arm": ["@esbuild/linux-arm@0.25.9", "", { "os": "linux", "cpu": "arm" }, "sha512-HBU2Xv78SMgaydBmdor38lg8YDnFKSARg1Q6AT0/y2ezUAKiZvc211RDFHlEZRFNRVhcMamiToo7bDx3VEOYQw=="],
"@esbuild/linux-arm64": ["@esbuild/linux-arm64@0.25.9", "", { "os": "linux", "cpu": "arm64" }, "sha512-BlB7bIcLT3G26urh5Dmse7fiLmLXnRlopw4s8DalgZ8ef79Jj4aUcYbk90g8iCa2467HX8SAIidbL7gsqXHdRw=="],
"@esbuild/linux-ia32": ["@esbuild/linux-ia32@0.25.9", "", { "os": "linux", "cpu": "ia32" }, "sha512-e7S3MOJPZGp2QW6AK6+Ly81rC7oOSerQ+P8L0ta4FhVi+/j/v2yZzx5CqqDaWjtPFfYz21Vi1S0auHrap3Ma3A=="],
"@esbuild/linux-loong64": ["@esbuild/linux-loong64@0.25.9", "", { "os": "linux", "cpu": "none" }, "sha512-Sbe10Bnn0oUAB2AalYztvGcK+o6YFFA/9829PhOCUS9vkJElXGdphz0A3DbMdP8gmKkqPmPcMJmJOrI3VYB1JQ=="],
"@esbuild/linux-mips64el": ["@esbuild/linux-mips64el@0.25.9", "", { "os": "linux", "cpu": "none" }, "sha512-YcM5br0mVyZw2jcQeLIkhWtKPeVfAerES5PvOzaDxVtIyZ2NUBZKNLjC5z3/fUlDgT6w89VsxP2qzNipOaaDyA=="],
"@esbuild/linux-ppc64": ["@esbuild/linux-ppc64@0.25.9", "", { "os": "linux", "cpu": "ppc64" }, "sha512-++0HQvasdo20JytyDpFvQtNrEsAgNG2CY1CLMwGXfFTKGBGQT3bOeLSYE2l1fYdvML5KUuwn9Z8L1EWe2tzs1w=="],
"@esbuild/linux-riscv64": ["@esbuild/linux-riscv64@0.25.9", "", { "os": "linux", "cpu": "none" }, "sha512-uNIBa279Y3fkjV+2cUjx36xkx7eSjb8IvnL01eXUKXez/CBHNRw5ekCGMPM0BcmqBxBcdgUWuUXmVWwm4CH9kg=="],
"@esbuild/linux-s390x": ["@esbuild/linux-s390x@0.25.9", "", { "os": "linux", "cpu": "s390x" }, "sha512-Mfiphvp3MjC/lctb+7D287Xw1DGzqJPb/J2aHHcHxflUo+8tmN/6d4k6I2yFR7BVo5/g7x2Monq4+Yew0EHRIA=="],
"@esbuild/linux-x64": ["@esbuild/linux-x64@0.25.9", "", { "os": "linux", "cpu": "x64" }, "sha512-iSwByxzRe48YVkmpbgoxVzn76BXjlYFXC7NvLYq+b+kDjyyk30J0JY47DIn8z1MO3K0oSl9fZoRmZPQI4Hklzg=="],
"@esbuild/netbsd-arm64": ["@esbuild/netbsd-arm64@0.25.9", "", { "os": "none", "cpu": "arm64" }, "sha512-9jNJl6FqaUG+COdQMjSCGW4QiMHH88xWbvZ+kRVblZsWrkXlABuGdFJ1E9L7HK+T0Yqd4akKNa/lO0+jDxQD4Q=="],
"@esbuild/netbsd-x64": ["@esbuild/netbsd-x64@0.25.9", "", { "os": "none", "cpu": "x64" }, "sha512-RLLdkflmqRG8KanPGOU7Rpg829ZHu8nFy5Pqdi9U01VYtG9Y0zOG6Vr2z4/S+/3zIyOxiK6cCeYNWOFR9QP87g=="],
"@esbuild/openbsd-arm64": ["@esbuild/openbsd-arm64@0.25.9", "", { "os": "openbsd", "cpu": "arm64" }, "sha512-YaFBlPGeDasft5IIM+CQAhJAqS3St3nJzDEgsgFixcfZeyGPCd6eJBWzke5piZuZ7CtL656eOSYKk4Ls2C0FRQ=="],
"@esbuild/openbsd-x64": ["@esbuild/openbsd-x64@0.25.9", "", { "os": "openbsd", "cpu": "x64" }, "sha512-1MkgTCuvMGWuqVtAvkpkXFmtL8XhWy+j4jaSO2wxfJtilVCi0ZE37b8uOdMItIHz4I6z1bWWtEX4CJwcKYLcuA=="],
"@esbuild/openharmony-arm64": ["@esbuild/openharmony-arm64@0.25.9", "", { "os": "none", "cpu": "arm64" }, "sha512-4Xd0xNiMVXKh6Fa7HEJQbrpP3m3DDn43jKxMjxLLRjWnRsfxjORYJlXPO4JNcXtOyfajXorRKY9NkOpTHptErg=="],
"@esbuild/sunos-x64": ["@esbuild/sunos-x64@0.25.9", "", { "os": "sunos", "cpu": "x64" }, "sha512-WjH4s6hzo00nNezhp3wFIAfmGZ8U7KtrJNlFMRKxiI9mxEK1scOMAaa9i4crUtu+tBr+0IN6JCuAcSBJZfnphw=="],
"@esbuild/win32-arm64": ["@esbuild/win32-arm64@0.25.9", "", { "os": "win32", "cpu": "arm64" }, "sha512-mGFrVJHmZiRqmP8xFOc6b84/7xa5y5YvR1x8djzXpJBSv/UsNK6aqec+6JDjConTgvvQefdGhFDAs2DLAds6gQ=="],
"@esbuild/win32-ia32": ["@esbuild/win32-ia32@0.25.9", "", { "os": "win32", "cpu": "ia32" }, "sha512-b33gLVU2k11nVx1OhX3C8QQP6UHQK4ZtN56oFWvVXvz2VkDoe6fbG8TOgHFxEvqeqohmRnIHe5A1+HADk4OQww=="],
"@esbuild/win32-x64": ["@esbuild/win32-x64@0.25.9", "", { "os": "win32", "cpu": "x64" }, "sha512-PPOl1mi6lpLNQxnGoyAfschAodRFYXJ+9fs6WHXz7CSWKbOqiMZsubC+BQsVKuul+3vKLuwTHsS2c2y9EoKwxQ=="],
"@eslint-community/eslint-utils": ["@eslint-community/eslint-utils@4.9.0", "", { "dependencies": { "eslint-visitor-keys": "^3.4.3" }, "peerDependencies": { "eslint": "^6.0.0 || ^7.0.0 || >=8.0.0" } }, "sha512-ayVFHdtZ+hsq1t2Dy24wCmGXGe4q9Gu3smhLYALJrr473ZH27MsnSL+LKUlimp4BWJqMDMLmPpx/Q9R3OAlL4g=="],
"@eslint-community/regexpp": ["@eslint-community/regexpp@4.12.1", "", {}, "sha512-CCZCDJuduB9OUkFkY2IgppNZMi2lBQgD2qzwXkEia16cge2pijY/aXi96CJMquDMn3nJdlPV1A5KrJEXwfLNzQ=="],
"@eslint/config-array": ["@eslint/config-array@0.17.1", "", { "dependencies": { "@eslint/object-schema": "^2.1.4", "debug": "^4.3.1", "minimatch": "^3.1.2" } }, "sha512-BlYOpej8AQ8Ev9xVqroV7a02JK3SkBAaN9GfMMH9W6Ch8FlQlkjGw4Ir7+FgYwfirivAf4t+GtzuAxqfukmISA=="],
"@eslint/eslintrc": ["@eslint/eslintrc@3.3.1", "", { "dependencies": { "ajv": "^6.12.4", "debug": "^4.3.2", "espree": "^10.0.1", "globals": "^14.0.0", "ignore": "^5.2.0", "import-fresh": "^3.2.1", "js-yaml": "^4.1.0", "minimatch": "^3.1.2", "strip-json-comments": "^3.1.1" } }, "sha512-gtF186CXhIl1p4pJNGZw8Yc6RlshoePRvE0X91oPGb3vZ8pM3qOS9W9NGPat9LziaBV7XrJWGylNQXkGcnM3IQ=="],
"@eslint/js": ["@eslint/js@9.6.0", "", {}, "sha512-D9B0/3vNg44ZeWbYMpBoXqNP4j6eQD5vNwIlGAuFRRzK/WtT/jvDQW3Bi9kkf3PMDMlM7Yi+73VLUsn5bJcl8A=="],
"@eslint/object-schema": ["@eslint/object-schema@2.1.6", "", {}, "sha512-RBMg5FRL0I0gs51M/guSAj5/e14VQ4tpZnQNWwuDT66P14I43ItmPfIZRhO9fUVIPOAQXU47atlywZ/czoqFPA=="],
"@humanwhocodes/module-importer": ["@humanwhocodes/module-importer@1.0.1", "", {}, "sha512-bxveV4V8v5Yb4ncFTT3rPSgZBOpCkjfK0y4oVVVJwIuDVBRMDXrPyXRL988i5ap9m9bnyEEjWfm5WkBmtffLfA=="],
"@humanwhocodes/retry": ["@humanwhocodes/retry@0.3.1", "", {}, "sha512-JBxkERygn7Bv/GbN5Rv8Ul6LVknS+5Bp6RgDC/O8gEBU/yeH5Ui5C/OlWrTb6qct7LjjfT6Re2NxB0ln0yYybA=="],
"@isaacs/cliui": ["@isaacs/cliui@8.0.2", "", { "dependencies": { "string-width": "^5.1.2", "string-width-cjs": "npm:string-width@^4.2.0", "strip-ansi": "^7.0.1", "strip-ansi-cjs": "npm:strip-ansi@^6.0.1", "wrap-ansi": "^8.1.0", "wrap-ansi-cjs": "npm:wrap-ansi@^7.0.0" } }, "sha512-O8jcjabXaleOG9DQ0+ARXWZBTfnP4WNAqzuiJK7ll44AmxGKv/J2M4TPjxjY3znBCfvBXFzucm1twdyFybFqEA=="],
"@jridgewell/gen-mapping": ["@jridgewell/gen-mapping@0.3.13", "", { "dependencies": { "@jridgewell/sourcemap-codec": "^1.5.0", "@jridgewell/trace-mapping": "^0.3.24" } }, "sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA=="],
"@jridgewell/resolve-uri": ["@jridgewell/resolve-uri@3.1.2", "", {}, "sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw=="],
"@jridgewell/sourcemap-codec": ["@jridgewell/sourcemap-codec@1.5.5", "", {}, "sha512-cYQ9310grqxueWbl+WuIUIaiUaDcj7WOq5fVhEljNVgRfOUhY9fy2zTvfoqWsnebh8Sl70VScFbICvJnLKB0Og=="],
"@jridgewell/trace-mapping": ["@jridgewell/trace-mapping@0.3.31", "", { "dependencies": { "@jridgewell/resolve-uri": "^3.1.0", "@jridgewell/sourcemap-codec": "^1.4.14" } }, "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw=="],
"@nodelib/fs.scandir": ["@nodelib/fs.scandir@2.1.5", "", { "dependencies": { "@nodelib/fs.stat": "2.0.5", "run-parallel": "^1.1.9" } }, "sha512-vq24Bq3ym5HEQm2NKCr3yXDwjc7vTsEThRDnkp2DK9p1uqLR+DHurm/NOTo0KG7HYHU7eppKZj3MyqYuMBf62g=="],
"@nodelib/fs.stat": ["@nodelib/fs.stat@2.0.5", "", {}, "sha512-RkhPPp2zrqDAQA/2jNhnztcPAlv64XdhIp7a7454A5ovI7Bukxgt7MX7udwAu3zg1DcpPU0rz3VV1SeaqvY4+A=="],
"@nodelib/fs.walk": ["@nodelib/fs.walk@1.2.8", "", { "dependencies": { "@nodelib/fs.scandir": "2.1.5", "fastq": "^1.6.0" } }, "sha512-oGB+UxlgWcgQkgwo8GcEGwemoTFt3FIO9ababBmaGwXIoBKZ+GTy0pP185beGg7Llih/NSHSV2XAs1lnznocSg=="],
"@pkgjs/parseargs": ["@pkgjs/parseargs@0.11.0", "", {}, "sha512-+1VkjdD0QBLPodGrJUeqarH8VAIvQODIbwh9XpP5Syisf7YoQgsJKPNFoqqLQlu+VQ/tVSshMR6loPMn8U+dPg=="],
"@rollup/rollup-android-arm-eabi": ["@rollup/rollup-android-arm-eabi@4.50.1", "", { "os": "android", "cpu": "arm" }, "sha512-HJXwzoZN4eYTdD8bVV22DN8gsPCAj3V20NHKOs8ezfXanGpmVPR7kalUHd+Y31IJp9stdB87VKPFbsGY3H/2ag=="],
"@rollup/rollup-android-arm64": ["@rollup/rollup-android-arm64@4.50.1", "", { "os": "android", "cpu": "arm64" }, "sha512-PZlsJVcjHfcH53mOImyt3bc97Ep3FJDXRpk9sMdGX0qgLmY0EIWxCag6EigerGhLVuL8lDVYNnSo8qnTElO4xw=="],
"@rollup/rollup-darwin-arm64": ["@rollup/rollup-darwin-arm64@4.50.1", "", { "os": "darwin", "cpu": "arm64" }, "sha512-xc6i2AuWh++oGi4ylOFPmzJOEeAa2lJeGUGb4MudOtgfyyjr4UPNK+eEWTPLvmPJIY/pgw6ssFIox23SyrkkJw=="],
"@rollup/rollup-darwin-x64": ["@rollup/rollup-darwin-x64@4.50.1", "", { "os": "darwin", "cpu": "x64" }, "sha512-2ofU89lEpDYhdLAbRdeyz/kX3Y2lpYc6ShRnDjY35bZhd2ipuDMDi6ZTQ9NIag94K28nFMofdnKeHR7BT0CATw=="],
"@rollup/rollup-freebsd-arm64": ["@rollup/rollup-freebsd-arm64@4.50.1", "", { "os": "freebsd", "cpu": "arm64" }, "sha512-wOsE6H2u6PxsHY/BeFHA4VGQN3KUJFZp7QJBmDYI983fgxq5Th8FDkVuERb2l9vDMs1D5XhOrhBrnqcEY6l8ZA=="],
"@rollup/rollup-freebsd-x64": ["@rollup/rollup-freebsd-x64@4.50.1", "", { "os": "freebsd", "cpu": "x64" }, "sha512-A/xeqaHTlKbQggxCqispFAcNjycpUEHP52mwMQZUNqDUJFFYtPHCXS1VAG29uMlDzIVr+i00tSFWFLivMcoIBQ=="],
"@rollup/rollup-linux-arm-gnueabihf": ["@rollup/rollup-linux-arm-gnueabihf@4.50.1", "", { "os": "linux", "cpu": "arm" }, "sha512-54v4okehwl5TaSIkpp97rAHGp7t3ghinRd/vyC1iXqXMfjYUTm7TfYmCzXDoHUPTTf36L8pr0E7YsD3CfB3ZDg=="],
"@rollup/rollup-linux-arm-musleabihf": ["@rollup/rollup-linux-arm-musleabihf@4.50.1", "", { "os": "linux", "cpu": "arm" }, "sha512-p/LaFyajPN/0PUHjv8TNyxLiA7RwmDoVY3flXHPSzqrGcIp/c2FjwPPP5++u87DGHtw+5kSH5bCJz0mvXngYxw=="],
"@rollup/rollup-linux-arm64-gnu": ["@rollup/rollup-linux-arm64-gnu@4.50.1", "", { "os": "linux", "cpu": "arm64" }, "sha512-2AbMhFFkTo6Ptna1zO7kAXXDLi7H9fGTbVaIq2AAYO7yzcAsuTNWPHhb2aTA6GPiP+JXh85Y8CiS54iZoj4opw=="],
"@rollup/rollup-linux-arm64-musl": ["@rollup/rollup-linux-arm64-musl@4.50.1", "", { "os": "linux", "cpu": "arm64" }, "sha512-Cgef+5aZwuvesQNw9eX7g19FfKX5/pQRIyhoXLCiBOrWopjo7ycfB292TX9MDcDijiuIJlx1IzJz3IoCPfqs9w=="],
"@rollup/rollup-linux-loongarch64-gnu": ["@rollup/rollup-linux-loongarch64-gnu@4.50.1", "", { "os": "linux", "cpu": "none" }, "sha512-RPhTwWMzpYYrHrJAS7CmpdtHNKtt2Ueo+BlLBjfZEhYBhK00OsEqM08/7f+eohiF6poe0YRDDd8nAvwtE/Y62Q=="],
"@rollup/rollup-linux-ppc64-gnu": ["@rollup/rollup-linux-ppc64-gnu@4.50.1", "", { "os": "linux", "cpu": "ppc64" }, "sha512-eSGMVQw9iekut62O7eBdbiccRguuDgiPMsw++BVUg+1K7WjZXHOg/YOT9SWMzPZA+w98G+Fa1VqJgHZOHHnY0Q=="],
"@rollup/rollup-linux-riscv64-gnu": ["@rollup/rollup-linux-riscv64-gnu@4.50.1", "", { "os": "linux", "cpu": "none" }, "sha512-S208ojx8a4ciIPrLgazF6AgdcNJzQE4+S9rsmOmDJkusvctii+ZvEuIC4v/xFqzbuP8yDjn73oBlNDgF6YGSXQ=="],
"@rollup/rollup-linux-riscv64-musl": ["@rollup/rollup-linux-riscv64-musl@4.50.1", "", { "os": "linux", "cpu": "none" }, "sha512-3Ag8Ls1ggqkGUvSZWYcdgFwriy2lWo+0QlYgEFra/5JGtAd6C5Hw59oojx1DeqcA2Wds2ayRgvJ4qxVTzCHgzg=="],
"@rollup/rollup-linux-s390x-gnu": ["@rollup/rollup-linux-s390x-gnu@4.50.1", "", { "os": "linux", "cpu": "s390x" }, "sha512-t9YrKfaxCYe7l7ldFERE1BRg/4TATxIg+YieHQ966jwvo7ddHJxPj9cNFWLAzhkVsbBvNA4qTbPVNsZKBO4NSg=="],
"@rollup/rollup-linux-x64-gnu": ["@rollup/rollup-linux-x64-gnu@4.50.1", "", { "os": "linux", "cpu": "x64" }, "sha512-MCgtFB2+SVNuQmmjHf+wfI4CMxy3Tk8XjA5Z//A0AKD7QXUYFMQcns91K6dEHBvZPCnhJSyDWLApk40Iq/H3tA=="],
"@rollup/rollup-linux-x64-musl": ["@rollup/rollup-linux-x64-musl@4.50.1", "", { "os": "linux", "cpu": "x64" }, "sha512-nEvqG+0jeRmqaUMuwzlfMKwcIVffy/9KGbAGyoa26iu6eSngAYQ512bMXuqqPrlTyfqdlB9FVINs93j534UJrg=="],
"@rollup/rollup-openharmony-arm64": ["@rollup/rollup-openharmony-arm64@4.50.1", "", { "os": "none", "cpu": "arm64" }, "sha512-RDsLm+phmT3MJd9SNxA9MNuEAO/J2fhW8GXk62G/B4G7sLVumNFbRwDL6v5NrESb48k+QMqdGbHgEtfU0LCpbA=="],
"@rollup/rollup-win32-arm64-msvc": ["@rollup/rollup-win32-arm64-msvc@4.50.1", "", { "os": "win32", "cpu": "arm64" }, "sha512-hpZB/TImk2FlAFAIsoElM3tLzq57uxnGYwplg6WDyAxbYczSi8O2eQ+H2Lx74504rwKtZ3N2g4bCUkiamzS6TQ=="],
"@rollup/rollup-win32-ia32-msvc": ["@rollup/rollup-win32-ia32-msvc@4.50.1", "", { "os": "win32", "cpu": "ia32" }, "sha512-SXjv8JlbzKM0fTJidX4eVsH+Wmnp0/WcD8gJxIZyR6Gay5Qcsmdbi9zVtnbkGPG8v2vMR1AD06lGWy5FLMcG7A=="],
"@rollup/rollup-win32-x64-msvc": ["@rollup/rollup-win32-x64-msvc@4.50.1", "", { "os": "win32", "cpu": "x64" }, "sha512-StxAO/8ts62KZVRAm4JZYq9+NqNsV7RvimNK+YM7ry//zebEH6meuugqW/P5OFUCjyQgui+9fUxT6d5NShvMvA=="],
"@sinclair/typebox": ["@sinclair/typebox@0.34.41", "", {}, "sha512-6gS8pZzSXdyRHTIqoqSVknxolr1kzfy4/CeDnrzsVz8TTIWUbOBr6gnzOmTYJ3eXQNh4IYHIGi5aIL7sOZ2G/g=="],
"@tokenizer/inflate": ["@tokenizer/inflate@0.2.7", "", { "dependencies": { "debug": "^4.4.0", "fflate": "^0.8.2", "token-types": "^6.0.0" } }, "sha512-MADQgmZT1eKjp06jpI2yozxaU9uVs4GzzgSL+uEq7bVcJ9V1ZXQkeGNql1fsSI0gMy1vhvNTNbUqrx+pZfJVmg=="],
"@tokenizer/token": ["@tokenizer/token@0.3.0", "", {}, "sha512-OvjF+z51L3ov0OyAU0duzsYuvO01PH7x4t6DJx+guahgTnBHkhJdG7soQeTSFLWN3efnHyibZ4Z8l2EuWwJN3A=="],
"@types/bun": ["@types/bun@1.1.14", "", { "dependencies": { "bun-types": "1.1.37" } }, "sha512-opVYiFGtO2af0dnWBdZWlioLBoxSdDO5qokaazLhq8XQtGZbY4pY3/JxY8Zdf/hEwGubbp7ErZXoN1+h2yesxA=="],
"@types/estree": ["@types/estree@1.0.8", "", {}, "sha512-dWHzHa2WqEXI/O1E9OjrocMTKJl2mSrEolh1Iomrv6U+JuNwaHXsXx9bLu5gG7BUWFIN0skIQJQ/L1rIex4X6w=="],
"@types/node": ["@types/node@20.19.13", "", { "dependencies": { "undici-types": "~6.21.0" } }, "sha512-yCAeZl7a0DxgNVteXFHt9+uyFbqXGy/ShC4BlcHkoE0AfGXYv/BUiplV72DjMYXHDBXFjhvr6DD1NiRVfB4j8g=="],
"@types/ws": ["@types/ws@8.5.14", "", { "dependencies": { "@types/node": "*" } }, "sha512-bd/YFLW+URhBzMXurx7lWByOu+xzU9+kb3RboOteXYDfW+tr+JZa99OyNmPINEGB/ahzKrEuc8rcv4gnpJmxTw=="],
"acorn": ["acorn@8.15.0", "", { "bin": { "acorn": "bin/acorn" } }, "sha512-NZyJarBfL7nWwIq+FDL6Zp/yHEhePMNnnJ0y3qfieCrmNvYct8uvtiV41UvlSe6apAfk0fY1FbWx+NwfmpvtTg=="],
"acorn-jsx": ["acorn-jsx@5.3.2", "", { "peerDependencies": { "acorn": "^6.0.0 || ^7.0.0 || ^8.0.0" } }, "sha512-rq9s+JNhf0IChjtDXxllJ7g41oZk5SlXtp0LHwyA5cejwn7vKmKp4pPri6YEePv2PU65sAsegbXtIinmDFDXgQ=="],
"ajv": ["ajv@6.12.6", "", { "dependencies": { "fast-deep-equal": "^3.1.1", "fast-json-stable-stringify": "^2.0.0", "json-schema-traverse": "^0.4.1", "uri-js": "^4.2.2" } }, "sha512-j3fVLgvTo527anyYyJOGTYJbG+vnnQYvE0m5mmkc1TK+nxAppkCLMIL0aZ4dblVCNoGShhm+kzE4ZUykBoMg4g=="],
"ansi-regex": ["ansi-regex@5.0.1", "", {}, "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ=="],
"ansi-styles": ["ansi-styles@4.3.0", "", { "dependencies": { "color-convert": "^2.0.1" } }, "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg=="],
"any-promise": ["any-promise@1.3.0", "", {}, "sha512-7UvmKalWRt1wgjL1RrGxoSJW/0QZFIegpeGvZG9kjp8vrRu55XTHbwnqq2GpXm9uLbcuhxm3IqX9OB4MZR1b2A=="],
"argparse": ["argparse@2.0.1", "", {}, "sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q=="],
"balanced-match": ["balanced-match@1.0.2", "", {}, "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw=="],
"brace-expansion": ["brace-expansion@1.1.12", "", { "dependencies": { "balanced-match": "^1.0.0", "concat-map": "0.0.1" } }, "sha512-9T9UjW3r0UW5c1Q7GTwllptXwhvYmEzFhzMfZ9H7FQWt+uZePjZPjBP/W1ZEyZ1twGWom5/56TF4lPcqjnDHcg=="],
"bun-types": ["bun-types@1.1.37", "", { "dependencies": { "@types/node": "~20.12.8", "@types/ws": "~8.5.10" } }, "sha512-C65lv6eBr3LPJWFZ2gswyrGZ82ljnH8flVE03xeXxKhi2ZGtFiO4isRKTKnitbSqtRAcaqYSR6djt1whI66AbA=="],
"bundle-require": ["bundle-require@5.1.0", "", { "dependencies": { "load-tsconfig": "^0.2.3" }, "peerDependencies": { "esbuild": ">=0.18" } }, "sha512-3WrrOuZiyaaZPWiEt4G3+IffISVC9HYlWueJEBWED4ZH4aIAC2PnkdnuRrR94M+w6yGWn4AglWtJtBI8YqvgoA=="],
"cac": ["cac@6.7.14", "", {}, "sha512-b6Ilus+c3RrdDk+JhLKUAQfzzgLEPy6wcXqS7f/xe1EETvsDP6GORG7SFuOs6cID5YkqchW/LXZbX5bc8j7ZcQ=="],
"callsites": ["callsites@3.1.0", "", {}, "sha512-P8BjAsXvZS+VIDUI11hHCQEv74YT67YUi5JJFNWIqL235sBmjX4+qx9Muvls5ivyNENctx46xQLQ3aTuE7ssaQ=="],
"chalk": ["chalk@4.1.2", "", { "dependencies": { "ansi-styles": "^4.1.0", "supports-color": "^7.1.0" } }, "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA=="],
"chokidar": ["chokidar@4.0.3", "", { "dependencies": { "readdirp": "^4.0.1" } }, "sha512-Qgzu8kfBvo+cA4962jnP1KkS6Dop5NS6g7R5LFYJr4b8Ub94PPQXUksCw9PvXoeXPRRddRNC5C1JQUR2SMGtnA=="],
"color-convert": ["color-convert@2.0.1", "", { "dependencies": { "color-name": "~1.1.4" } }, "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ=="],
"color-name": ["color-name@1.1.4", "", {}, "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA=="],
"commander": ["commander@4.1.1", "", {}, "sha512-NOKm8xhkzAjzFx8B2v5OAHT+u5pRQc2UCa2Vq9jYL/31o2wi9mxBA7LIFs3sV5VSC49z6pEhfbMULvShKj26WA=="],
"concat-map": ["concat-map@0.0.1", "", {}, "sha512-/Srv4dswyQNBfohGpz9o6Yb3Gz3SrUDqBH5rTuhGR7ahtlbYKnVxw2bCFMRljaA7EXHaXZ8wsHdodFvbkhKmqg=="],
"confbox": ["confbox@0.1.8", "", {}, "sha512-RMtmw0iFkeR4YV+fUOSucriAQNb9g8zFR52MWCtl+cCZOFRNL6zeB395vPzFhEjjn4fMxXudmELnl/KF/WrK6w=="],
"consola": ["consola@3.4.2", "", {}, "sha512-5IKcdX0nnYavi6G7TtOhwkYzyjfJlatbjMjuLSfE2kYT5pMDOilZ4OvMhi637CcDICTmz3wARPoyhqyX1Y+XvA=="],
"cookie": ["cookie@1.0.2", "", {}, "sha512-9Kr/j4O16ISv8zBBhJoi4bXOYNTkFLOqSL3UDB0njXxCXNezjeyVrJyGOWtgfs/q2km1gwBcfH8q1yEGoMYunA=="],
"cross-spawn": ["cross-spawn@7.0.6", "", { "dependencies": { "path-key": "^3.1.0", "shebang-command": "^2.0.0", "which": "^2.0.1" } }, "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA=="],
"debug": ["debug@4.4.1", "", { "dependencies": { "ms": "^2.1.3" } }, "sha512-KcKCqiftBJcZr++7ykoDIEwSa3XWowTfNPo92BYxjXiyYEVrUQh2aLyhxBCwww+heortUFxEJYcRzosstTEBYQ=="],
"deep-is": ["deep-is@0.1.4", "", {}, "sha512-oIPzksmTg4/MriiaYGO+okXDT7ztn/w3Eptv/+gSIdMdKsJo0u4CfYNFJPy+4SKMuCqGw2wxnA+URMg3t8a/bQ=="],
"eastasianwidth": ["eastasianwidth@0.2.0", "", {}, "sha512-I88TYZWc9XiYHRQ4/3c5rjjfgkjhLyW2luGIheGERbNQ6OY7yTybanSpDXZa8y7VUP9YmDcYa+eyq4ca7iLqWA=="],
"elysia": ["elysia@1.4.0", "", { "dependencies": { "cookie": "^1.0.2", "exact-mirror": "0.2.2", "fast-decode-uri-component": "^1.0.1" }, "optionalDependencies": { "@sinclair/typebox": ">= 0.34.0 < 1", "openapi-types": ">= 12.0.0" }, "peerDependencies": { "file-type": ">= 20.0.0", "typescript": ">= 5.0.0" } }, "sha512-AVEq8cWo7+fdkbUtqVXDZ7uhjjv8K6NE6bt9oSzdocaawsW5VhJP2ArPoRYkWdJPYmS4f2FI5xWF+Tvs98yXVw=="],
"emoji-regex": ["emoji-regex@9.2.2", "", {}, "sha512-L18DaJsXSUk2+42pv8mLs5jJT2hqFkFE4j21wOmgbUqsZ2hL72NsUU785g9RXgo3s0ZNgVl42TiHp3ZtOv/Vyg=="],
"esbuild": ["esbuild@0.25.9", "", { "optionalDependencies": { "@esbuild/aix-ppc64": "0.25.9", "@esbuild/android-arm": "0.25.9", "@esbuild/android-arm64": "0.25.9", "@esbuild/android-x64": "0.25.9", "@esbuild/darwin-arm64": "0.25.9", "@esbuild/darwin-x64": "0.25.9", "@esbuild/freebsd-arm64": "0.25.9", "@esbuild/freebsd-x64": "0.25.9", "@esbuild/linux-arm": "0.25.9", "@esbuild/linux-arm64": "0.25.9", "@esbuild/linux-ia32": "0.25.9", "@esbuild/linux-loong64": "0.25.9", "@esbuild/linux-mips64el": "0.25.9", "@esbuild/linux-ppc64": "0.25.9", "@esbuild/linux-riscv64": "0.25.9", "@esbuild/linux-s390x": "0.25.9", "@esbuild/linux-x64": "0.25.9", "@esbuild/netbsd-arm64": "0.25.9", "@esbuild/netbsd-x64": "0.25.9", "@esbuild/openbsd-arm64": "0.25.9", "@esbuild/openbsd-x64": "0.25.9", "@esbuild/openharmony-arm64": "0.25.9", "@esbuild/sunos-x64": "0.25.9", "@esbuild/win32-arm64": "0.25.9", "@esbuild/win32-ia32": "0.25.9", "@esbuild/win32-x64": "0.25.9" }, "bin": { "esbuild": "bin/esbuild" } }, "sha512-CRbODhYyQx3qp7ZEwzxOk4JBqmD/seJrzPa/cGjY1VtIn5E09Oi9/dB4JwctnfZ8Q8iT7rioVv5k/FNT/uf54g=="],
"escape-string-regexp": ["escape-string-regexp@4.0.0", "", {}, "sha512-TtpcNJ3XAzx3Gq8sWRzJaVajRs0uVxA2YAkdb1jm2YkPz4G6egUFAyA3n5vtEIZefPk5Wa4UXbKuS5fKkJWdgA=="],
"eslint": ["eslint@9.6.0", "", { "dependencies": { "@eslint-community/eslint-utils": "^4.2.0", "@eslint-community/regexpp": "^4.6.1", "@eslint/config-array": "^0.17.0", "@eslint/eslintrc": "^3.1.0", "@eslint/js": "9.6.0", "@humanwhocodes/module-importer": "^1.0.1", "@humanwhocodes/retry": "^0.3.0", "@nodelib/fs.walk": "^1.2.8", "ajv": "^6.12.4", "chalk": "^4.0.0", "cross-spawn": "^7.0.2", "debug": "^4.3.2", "escape-string-regexp": "^4.0.0", "eslint-scope": "^8.0.1", "eslint-visitor-keys": "^4.0.0", "espree": "^10.1.0", "esquery": "^1.5.0", "esutils": "^2.0.2", "fast-deep-equal": "^3.1.3", "file-entry-cache": "^8.0.0", "find-up": "^5.0.0", "glob-parent": "^6.0.2", "ignore": "^5.2.0", "imurmurhash": "^0.1.4", "is-glob": "^4.0.0", "is-path-inside": "^3.0.3", "json-stable-stringify-without-jsonify": "^1.0.1", "levn": "^0.4.1", "lodash.merge": "^4.6.2", "minimatch": "^3.1.2", "natural-compare": "^1.4.0", "optionator": "^0.9.3", "strip-ansi": "^6.0.1", "text-table": "^0.2.0" }, "bin": { "eslint": "bin/eslint.js" } }, "sha512-ElQkdLMEEqQNM9Njff+2Y4q2afHk7JpkPvrd7Xh7xefwgQynqPxwf55J7di9+MEibWUGdNjFF9ITG9Pck5M84w=="],
"eslint-scope": ["eslint-scope@8.4.0", "", { "dependencies": { "esrecurse": "^4.3.0", "estraverse": "^5.2.0" } }, "sha512-sNXOfKCn74rt8RICKMvJS7XKV/Xk9kA7DyJr8mJik3S7Cwgy3qlkkmyS2uQB3jiJg6VNdZd/pDBJu0nvG2NlTg=="],
"eslint-visitor-keys": ["eslint-visitor-keys@4.2.1", "", {}, "sha512-Uhdk5sfqcee/9H/rCOJikYz67o0a2Tw2hGRPOG2Y1R2dg7brRe1uG0yaNQDHu+TO/uQPF/5eCapvYSmHUjt7JQ=="],
"espree": ["espree@10.4.0", "", { "dependencies": { "acorn": "^8.15.0", "acorn-jsx": "^5.3.2", "eslint-visitor-keys": "^4.2.1" } }, "sha512-j6PAQ2uUr79PZhBjP5C5fhl8e39FmRnOjsD5lGnWrFU8i2G776tBK7+nP8KuQUTTyAZUwfQqXAgrVH5MbH9CYQ=="],
"esquery": ["esquery@1.6.0", "", { "dependencies": { "estraverse": "^5.1.0" } }, "sha512-ca9pw9fomFcKPvFLXhBKUK90ZvGibiGOvRJNbjljY7s7uq/5YO4BOzcYtJqExdx99rF6aAcnRxHmcUHcz6sQsg=="],
"esrecurse": ["esrecurse@4.3.0", "", { "dependencies": { "estraverse": "^5.2.0" } }, "sha512-KmfKL3b6G+RXvP8N1vr3Tq1kL/oCFgn2NYXEtqP8/L3pKapUA4G8cFVaoF3SU323CD4XypR/ffioHmkti6/Tag=="],
"estraverse": ["estraverse@5.3.0", "", {}, "sha512-MMdARuVEQziNTeJD8DgMqmhwR11BRQ/cBP+pLtYdSTnf3MIO8fFeiINEbX36ZdNlfU/7A9f3gUw49B3oQsvwBA=="],
"esutils": ["esutils@2.0.3", "", {}, "sha512-kVscqXk4OCp68SZ0dkgEKVi6/8ij300KBWTJq32P/dYeWTSwK41WyTxalN1eRmA5Z9UU/LX9D7FWSmV9SAYx6g=="],
"exact-mirror": ["exact-mirror@0.2.2", "", { "peerDependencies": { "@sinclair/typebox": "^0.34.15" }, "optionalPeers": ["@sinclair/typebox"] }, "sha512-CrGe+4QzHZlnrXZVlo/WbUZ4qQZq8C0uATQVGVgXIrNXgHDBBNFD1VRfssRA2C9t3RYvh3MadZSdg2Wy7HBoQA=="],
"fast-decode-uri-component": ["fast-decode-uri-component@1.0.1", "", {}, "sha512-WKgKWg5eUxvRZGwW8FvfbaH7AXSh2cL+3j5fMGzUMCxWBJ3dV3a7Wz8y2f/uQ0e3B6WmodD3oS54jTQ9HVTIIg=="],
"fast-deep-equal": ["fast-deep-equal@3.1.3", "", {}, "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q=="],
"fast-json-stable-stringify": ["fast-json-stable-stringify@2.1.0", "", {}, "sha512-lhd/wF+Lk98HZoTCtlVraHtfh5XYijIjalXck7saUtuanSDyLMxnHhSXEDJqHxD7msR8D0uCmqlkwjCV8xvwHw=="],
"fast-levenshtein": ["fast-levenshtein@2.0.6", "", {}, "sha512-DCXu6Ifhqcks7TZKY3Hxp3y6qphY5SJZmrWMDrKcERSOXWQdMhU9Ig/PYrzyw/ul9jOIyh0N4M0tbC5hodg8dw=="],
"fastq": ["fastq@1.19.1", "", { "dependencies": { "reusify": "^1.0.4" } }, "sha512-GwLTyxkCXjXbxqIhTsMI2Nui8huMPtnxg7krajPJAjnEG/iiOS7i+zCtWGZR9G0NBKbXKh6X9m9UIsYX/N6vvQ=="],
"fdir": ["fdir@6.5.0", "", { "peerDependencies": { "picomatch": "^3 || ^4" }, "optionalPeers": ["picomatch"] }, "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg=="],
"fflate": ["fflate@0.8.2", "", {}, "sha512-cPJU47OaAoCbg0pBvzsgpTPhmhqI5eJjh/JIu8tPj5q+T7iLvW/JAYUqmE7KOB4R1ZyEhzBaIQpQpardBF5z8A=="],
"file-entry-cache": ["file-entry-cache@8.0.0", "", { "dependencies": { "flat-cache": "^4.0.0" } }, "sha512-XXTUwCvisa5oacNGRP9SfNtYBNAMi+RPwBFmblZEF7N7swHYQS6/Zfk7SRwx4D5j3CH211YNRco1DEMNVfZCnQ=="],
"file-type": ["file-type@21.0.0", "", { "dependencies": { "@tokenizer/inflate": "^0.2.7", "strtok3": "^10.2.2", "token-types": "^6.0.0", "uint8array-extras": "^1.4.0" } }, "sha512-ek5xNX2YBYlXhiUXui3D/BXa3LdqPmoLJ7rqEx2bKJ7EAUEfmXgW0Das7Dc6Nr9MvqaOnIqiPV0mZk/r/UpNAg=="],
"find-up": ["find-up@5.0.0", "", { "dependencies": { "locate-path": "^6.0.0", "path-exists": "^4.0.0" } }, "sha512-78/PXT1wlLLDgTzDs7sjq9hzz0vXD+zn+7wypEe4fXQxCmdmqfGsEPQxmiCSQI3ajFV91bVSsvNtrJRiW6nGng=="],
"fix-dts-default-cjs-exports": ["fix-dts-default-cjs-exports@1.0.1", "", { "dependencies": { "magic-string": "^0.30.17", "mlly": "^1.7.4", "rollup": "^4.34.8" } }, "sha512-pVIECanWFC61Hzl2+oOCtoJ3F17kglZC/6N94eRWycFgBH35hHx0Li604ZIzhseh97mf2p0cv7vVrOZGoqhlEg=="],
"flat-cache": ["flat-cache@4.0.1", "", { "dependencies": { "flatted": "^3.2.9", "keyv": "^4.5.4" } }, "sha512-f7ccFPK3SXFHpx15UIGyRJ/FJQctuKZ0zVuN3frBo4HnK3cay9VEW0R6yPYFHC0AgqhukPzKjq22t5DmAyqGyw=="],
"flatted": ["flatted@3.3.3", "", {}, "sha512-GX+ysw4PBCz0PzosHDepZGANEuFCMLrnRTiEy9McGjmkCQYwRq4A/X786G/fjM/+OjsWSU1ZrY5qyARZmO/uwg=="],
"foreground-child": ["foreground-child@3.3.1", "", { "dependencies": { "cross-spawn": "^7.0.6", "signal-exit": "^4.0.1" } }, "sha512-gIXjKqtFuWEgzFRJA9WCQeSJLZDjgJUOMCMzxtvFq/37KojM1BFGufqsCy0r4qSQmYLsZYMeyRqzIWOMup03sw=="],
"fsevents": ["fsevents@2.3.3", "", { "os": "darwin" }, "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw=="],
"glob": ["glob@10.4.5", "", { "dependencies": { "foreground-child": "^3.1.0", "jackspeak": "^3.1.2", "minimatch": "^9.0.4", "minipass": "^7.1.2", "package-json-from-dist": "^1.0.0", "path-scurry": "^1.11.1" }, "bin": { "glob": "dist/esm/bin.mjs" } }, "sha512-7Bv8RF0k6xjo7d4A/PxYLbUCfb6c+Vpd2/mB2yRDlew7Jb5hEXiCD9ibfO7wpk8i4sevK6DFny9h7EYbM3/sHg=="],
"glob-parent": ["glob-parent@6.0.2", "", { "dependencies": { "is-glob": "^4.0.3" } }, "sha512-XxwI8EOhVQgWp6iDL+3b0r86f4d6AX6zSU55HfB4ydCEuXLXc5FcYeOu+nnGftS4TEju/11rt4KJPTMgbfmv4A=="],
"globals": ["globals@14.0.0", "", {}, "sha512-oahGvuMGQlPw/ivIYBjVSrWAfWLBeku5tpPE2fOPLi+WHffIWbuh2tCjhyQhTBPMf5E9jDEH4FOmTYgYwbKwtQ=="],
"has-flag": ["has-flag@4.0.0", "", {}, "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ=="],
"ieee754": ["ieee754@1.2.1", "", {}, "sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA=="],
"ignore": ["ignore@5.3.2", "", {}, "sha512-hsBTNUqQTDwkWtcdYI2i06Y/nUBEsNEDJKjWdigLvegy8kDuJAS8uRlpkkcQpyEXL0Z/pjDy5HBmMjRCJ2gq+g=="],
"import-fresh": ["import-fresh@3.3.1", "", { "dependencies": { "parent-module": "^1.0.0", "resolve-from": "^4.0.0" } }, "sha512-TR3KfrTZTYLPB6jUjfx6MF9WcWrHL9su5TObK4ZkYgBdWKPOFoSoQIdEuTuR82pmtxH2spWG9h6etwfr1pLBqQ=="],
"imurmurhash": ["imurmurhash@0.1.4", "", {}, "sha512-JmXMZ6wuvDmLiHEml9ykzqO6lwFbof0GG4IkcGaENdCRDDmMVnny7s5HsIgHCbaq0w2MyPhDqkhTUgS2LU2PHA=="],
"is-extglob": ["is-extglob@2.1.1", "", {}, "sha512-SbKbANkN603Vi4jEZv49LeVJMn4yGwsbzZworEoyEiutsN3nJYdbO36zfhGJ6QEDpOZIFkDtnq5JRxmvl3jsoQ=="],
"is-fullwidth-code-point": ["is-fullwidth-code-point@3.0.0", "", {}, "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg=="],
"is-glob": ["is-glob@4.0.3", "", { "dependencies": { "is-extglob": "^2.1.1" } }, "sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg=="],
"is-path-inside": ["is-path-inside@3.0.3", "", {}, "sha512-Fd4gABb+ycGAmKou8eMftCupSir5lRxqf4aD/vd0cD2qc4HL07OjCeuHMr8Ro4CoMaeCKDB0/ECBOVWjTwUvPQ=="],
"isexe": ["isexe@2.0.0", "", {}, "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw=="],
"jackspeak": ["jackspeak@3.4.3", "", { "dependencies": { "@isaacs/cliui": "^8.0.2" }, "optionalDependencies": { "@pkgjs/parseargs": "^0.11.0" } }, "sha512-OGlZQpz2yfahA/Rd1Y8Cd9SIEsqvXkLVoSw/cgwhnhFMDbsQFeZYoJJ7bIZBS9BcamUW96asq/npPWugM+RQBw=="],
"joycon": ["joycon@3.1.1", "", {}, "sha512-34wB/Y7MW7bzjKRjUKTa46I2Z7eV62Rkhva+KkopW7Qvv/OSWBqvkSY7vusOPrNuZcUG3tApvdVgNB8POj3SPw=="],
"js-yaml": ["js-yaml@4.1.0", "", { "dependencies": { "argparse": "^2.0.1" }, "bin": { "js-yaml": "bin/js-yaml.js" } }, "sha512-wpxZs9NoxZaJESJGIZTyDEaYpl0FKSA+FB9aJiyemKhMwkxQg63h4T1KJgUGHpTqPDNRcmmYLugrRjJlBtWvRA=="],
"json-buffer": ["json-buffer@3.0.1", "", {}, "sha512-4bV5BfR2mqfQTJm+V5tPPdf+ZpuhiIvTuAB5g8kcrXOZpTT/QwwVRWBywX1ozr6lEuPdbHxwaJlm9G6mI2sfSQ=="],
"json-schema-traverse": ["json-schema-traverse@0.4.1", "", {}, "sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg=="],
"json-stable-stringify-without-jsonify": ["json-stable-stringify-without-jsonify@1.0.1", "", {}, "sha512-Bdboy+l7tA3OGW6FjyFHWkP5LuByj1Tk33Ljyq0axyzdk9//JSi2u3fP1QSmd1KNwq6VOKYGlAu87CisVir6Pw=="],
"keyv": ["keyv@4.5.4", "", { "dependencies": { "json-buffer": "3.0.1" } }, "sha512-oxVHkHR/EJf2CNXnWxRLW6mg7JyCCUcG0DtEGmL2ctUo1PNTin1PUil+r/+4r5MpVgC/fn1kjsx7mjSujKqIpw=="],
"levn": ["levn@0.4.1", "", { "dependencies": { "prelude-ls": "^1.2.1", "type-check": "~0.4.0" } }, "sha512-+bT2uH4E5LGE7h/n3evcS/sQlJXCpIp6ym8OWJ5eV6+67Dsql/LaaT7qJBAt2rzfoa/5QBGBhxDix1dMt2kQKQ=="],
"lilconfig": ["lilconfig@3.1.3", "", {}, "sha512-/vlFKAoH5Cgt3Ie+JLhRbwOsCQePABiU3tJ1egGvyQ+33R/vcwM2Zl2QR/LzjsBeItPt3oSVXapn+m4nQDvpzw=="],
"lines-and-columns": ["lines-and-columns@1.2.4", "", {}, "sha512-7ylylesZQ/PV29jhEDl3Ufjo6ZX7gCqJr5F7PKrqc93v7fzSymt1BpwEU8nAUXs8qzzvqhbjhK5QZg6Mt/HkBg=="],
"load-tsconfig": ["load-tsconfig@0.2.5", "", {}, "sha512-IXO6OCs9yg8tMKzfPZ1YmheJbZCiEsnBdcB03l0OcfK9prKnJb96siuHCr5Fl37/yo9DnKU+TLpxzTUspw9shg=="],
"locate-path": ["locate-path@6.0.0", "", { "dependencies": { "p-locate": "^5.0.0" } }, "sha512-iPZK6eYjbxRu3uB4/WZ3EsEIMJFMqAoopl3R+zuq0UjcAm/MO6KCweDgPfP3elTztoKP3KtnVHxTn2NHBSDVUw=="],
"lodash.merge": ["lodash.merge@4.6.2", "", {}, "sha512-0KpjqXRVvrYyCsX1swR/XTK0va6VQkQM6MNo7PqW77ByjAhoARA8EfrP1N4+KlKj8YS0ZUCtRT/YUuhyYDujIQ=="],
"lodash.sortby": ["lodash.sortby@4.7.0", "", {}, "sha512-HDWXG8isMntAyRF5vZ7xKuEvOhT4AhlRt/3czTSjvGUxjYCBVRQY48ViDHyfYz9VIoBkW4TMGQNapx+l3RUwdA=="],
"lru-cache": ["lru-cache@10.4.3", "", {}, "sha512-JNAzZcXrCt42VGLuYz0zfAzDfAvJWW6AfYlDBQyDV5DClI2m5sAmK+OIO7s59XfsRsWHp02jAJrRadPRGTt6SQ=="],
"magic-string": ["magic-string@0.30.19", "", { "dependencies": { "@jridgewell/sourcemap-codec": "^1.5.5" } }, "sha512-2N21sPY9Ws53PZvsEpVtNuSW+ScYbQdp4b9qUaL+9QkHUrGFKo56Lg9Emg5s9V/qrtNBmiR01sYhUOwu3H+VOw=="],
"minimatch": ["minimatch@3.1.2", "", { "dependencies": { "brace-expansion": "^1.1.7" } }, "sha512-J7p63hRiAjw1NDEww1W7i37+ByIrOWO5XQQAzZ3VOcL0PNybwpfmV/N05zFAzwQ9USyEcX6t3UO+K5aqBQOIHw=="],
"minipass": ["minipass@7.1.2", "", {}, "sha512-qOOzS1cBTWYF4BH8fVePDBOO9iptMnGUEZwNc/cMWnTV2nVLZ7VoNWEPHkYczZA0pdoA7dl6e7FL659nX9S2aw=="],
"mlly": ["mlly@1.8.0", "", { "dependencies": { "acorn": "^8.15.0", "pathe": "^2.0.3", "pkg-types": "^1.3.1", "ufo": "^1.6.1" } }, "sha512-l8D9ODSRWLe2KHJSifWGwBqpTZXIXTeo8mlKjY+E2HAakaTeNpqAyBZ8GSqLzHgw4XmHmC8whvpjJNMbFZN7/g=="],
"ms": ["ms@2.1.3", "", {}, "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA=="],
"mz": ["mz@2.7.0", "", { "dependencies": { "any-promise": "^1.0.0", "object-assign": "^4.0.1", "thenify-all": "^1.0.0" } }, "sha512-z81GNO7nnYMEhrGh9LeymoE4+Yr0Wn5McHIZMK5cfQCl+NDX08sCZgUc9/6MHni9IWuFLm1Z3HTCXu2z9fN62Q=="],
"natural-compare": ["natural-compare@1.4.0", "", {}, "sha512-OWND8ei3VtNC9h7V60qff3SVobHr996CTwgxubgyQYEpg290h9J0buyECNNJexkFm5sOajh5G116RYA1c8ZMSw=="],
"object-assign": ["object-assign@4.1.1", "", {}, "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg=="],
"openapi-types": ["openapi-types@12.1.3", "", {}, "sha512-N4YtSYJqghVu4iek2ZUvcN/0aqH1kRDuNqzcycDxhOUpg7GdvLa2F3DgS6yBNhInhv2r/6I0Flkn7CqL8+nIcw=="],
"optionator": ["optionator@0.9.4", "", { "dependencies": { "deep-is": "^0.1.3", "fast-levenshtein": "^2.0.6", "levn": "^0.4.1", "prelude-ls": "^1.2.1", "type-check": "^0.4.0", "word-wrap": "^1.2.5" } }, "sha512-6IpQ7mKUxRcZNLIObR0hz7lxsapSSIYNZJwXPGeF0mTVqGKFIXj1DQcMoT22S3ROcLyY/rz0PWaWZ9ayWmad9g=="],
"p-limit": ["p-limit@3.1.0", "", { "dependencies": { "yocto-queue": "^0.1.0" } }, "sha512-TYOanM3wGwNGsZN2cVTYPArw454xnXj5qmWF1bEoAc4+cU/ol7GVh7odevjp1FNHduHc3KZMcFduxU5Xc6uJRQ=="],
"p-locate": ["p-locate@5.0.0", "", { "dependencies": { "p-limit": "^3.0.2" } }, "sha512-LaNjtRWUBY++zB5nE/NwcaoMylSPk+S+ZHNB1TzdbMJMny6dynpAGt7X/tl/QYq3TIeE6nxHppbo2LGymrG5Pw=="],
"package-json-from-dist": ["package-json-from-dist@1.0.1", "", {}, "sha512-UEZIS3/by4OC8vL3P2dTXRETpebLI2NiI5vIrjaD/5UtrkFX/tNbwjTSRAGC/+7CAo2pIcBaRgWmcBBHcsaCIw=="],
"parent-module": ["parent-module@1.0.1", "", { "dependencies": { "callsites": "^3.0.0" } }, "sha512-GQ2EWRpQV8/o+Aw8YqtfZZPfNRWZYkbidE9k5rpl/hC3vtHHBfGm2Ifi6qWV+coDGkrUKZAxE3Lot5kcsRlh+g=="],
"path-exists": ["path-exists@4.0.0", "", {}, "sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w=="],
"path-key": ["path-key@3.1.1", "", {}, "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q=="],
"path-scurry": ["path-scurry@1.11.1", "", { "dependencies": { "lru-cache": "^10.2.0", "minipass": "^5.0.0 || ^6.0.2 || ^7.0.0" } }, "sha512-Xa4Nw17FS9ApQFJ9umLiJS4orGjm7ZzwUrwamcGQuHSzDyth9boKDaycYdDcZDuqYATXw4HFXgaqWTctW/v1HA=="],
"pathe": ["pathe@2.0.3", "", {}, "sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w=="],
"picocolors": ["picocolors@1.1.1", "", {}, "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA=="],
"picomatch": ["picomatch@4.0.3", "", {}, "sha512-5gTmgEY/sqK6gFXLIsQNH19lWb4ebPDLA4SdLP7dsWkIXHWlG66oPuVvXSGFPppYZz8ZDZq0dYYrbHfBCVUb1Q=="],
"pirates": ["pirates@4.0.7", "", {}, "sha512-TfySrs/5nm8fQJDcBDuUng3VOUKsd7S+zqvbOTiGXHfxX4wK31ard+hoNuvkicM/2YFzlpDgABOevKSsB4G/FA=="],
"pkg-types": ["pkg-types@1.3.1", "", { "dependencies": { "confbox": "^0.1.8", "mlly": "^1.7.4", "pathe": "^2.0.1" } }, "sha512-/Jm5M4RvtBFVkKWRu2BLUTNP8/M2a+UwuAX+ae4770q1qVGtfjG+WTCupoZixokjmHiry8uI+dlY8KXYV5HVVQ=="],
"postcss-load-config": ["postcss-load-config@6.0.1", "", { "dependencies": { "lilconfig": "^3.1.1" }, "peerDependencies": { "jiti": ">=1.21.0", "postcss": ">=8.0.9", "tsx": "^4.8.1", "yaml": "^2.4.2" }, "optionalPeers": ["jiti", "postcss", "tsx", "yaml"] }, "sha512-oPtTM4oerL+UXmx+93ytZVN82RrlY/wPUV8IeDxFrzIjXOLF1pN+EmKPLbubvKHT2HC20xXsCAH2Z+CKV6Oz/g=="],
"prelude-ls": ["prelude-ls@1.2.1", "", {}, "sha512-vkcDPrRZo1QZLbn5RLGPpg/WmIQ65qoWWhcGKf/b5eplkkarX0m9z8ppCat4mlOqUsWpyNuYgO3VRyrYHSzX5g=="],
"punycode": ["punycode@2.3.1", "", {}, "sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg=="],
"queue-microtask": ["queue-microtask@1.2.3", "", {}, "sha512-NuaNSa6flKT5JaSYQzJok04JzTL1CA6aGhv5rfLW3PgqA+M2ChpZQnAC8h8i4ZFkBS8X5RqkDBHA7r4hej3K9A=="],
"readdirp": ["readdirp@4.1.2", "", {}, "sha512-GDhwkLfywWL2s6vEjyhri+eXmfH6j1L7JE27WhqLeYzoh/A3DBaYGEj2H/HFZCn/kMfim73FXxEJTw06WtxQwg=="],
"resolve-from": ["resolve-from@5.0.0", "", {}, "sha512-qYg9KP24dD5qka9J47d0aVky0N+b4fTU89LN9iDnjB5waksiC49rvMB0PrUJQGoTmH50XPiqOvAjDfaijGxYZw=="],
"reusify": ["reusify@1.1.0", "", {}, "sha512-g6QUff04oZpHs0eG5p83rFLhHeV00ug/Yf9nZM6fLeUrPguBTkTQOdpAWWspMh55TZfVQDPaN3NQJfbVRAxdIw=="],
"rollup": ["rollup@4.50.1", "", { "dependencies": { "@types/estree": "1.0.8" }, "optionalDependencies": { "@rollup/rollup-android-arm-eabi": "4.50.1", "@rollup/rollup-android-arm64": "4.50.1", "@rollup/rollup-darwin-arm64": "4.50.1", "@rollup/rollup-darwin-x64": "4.50.1", "@rollup/rollup-freebsd-arm64": "4.50.1", "@rollup/rollup-freebsd-x64": "4.50.1", "@rollup/rollup-linux-arm-gnueabihf": "4.50.1", "@rollup/rollup-linux-arm-musleabihf": "4.50.1", "@rollup/rollup-linux-arm64-gnu": "4.50.1", "@rollup/rollup-linux-arm64-musl": "4.50.1", "@rollup/rollup-linux-loongarch64-gnu": "4.50.1", "@rollup/rollup-linux-ppc64-gnu": "4.50.1", "@rollup/rollup-linux-riscv64-gnu": "4.50.1", "@rollup/rollup-linux-riscv64-musl": "4.50.1", "@rollup/rollup-linux-s390x-gnu": "4.50.1", "@rollup/rollup-linux-x64-gnu": "4.50.1", "@rollup/rollup-linux-x64-musl": "4.50.1", "@rollup/rollup-openharmony-arm64": "4.50.1", "@rollup/rollup-win32-arm64-msvc": "4.50.1", "@rollup/rollup-win32-ia32-msvc": "4.50.1", "@rollup/rollup-win32-x64-msvc": "4.50.1", "fsevents": "~2.3.2" }, "bin": { "rollup": "dist/bin/rollup" } }, "sha512-78E9voJHwnXQMiQdiqswVLZwJIzdBKJ1GdI5Zx6XwoFKUIk09/sSrr+05QFzvYb8q6Y9pPV45zzDuYa3907TZA=="],
"run-parallel": ["run-parallel@1.2.0", "", { "dependencies": { "queue-microtask": "^1.2.2" } }, "sha512-5l4VyZR86LZ/lDxZTR6jqL8AFE2S0IFLMP26AbjsLVADxHdhB/c0GUsH+y39UfCi3dzz8OlQuPmnaJOMoDHQBA=="],
"shebang-command": ["shebang-command@2.0.0", "", { "dependencies": { "shebang-regex": "^3.0.0" } }, "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA=="],
"shebang-regex": ["shebang-regex@3.0.0", "", {}, "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A=="],
"signal-exit": ["signal-exit@4.1.0", "", {}, "sha512-bzyZ1e88w9O1iNJbKnOlvYTrWPDl46O1bG0D3XInv+9tkPrxrN8jUUTiFlDkkmKWgn1M6CfIA13SuGqOa9Korw=="],
"source-map": ["source-map@0.8.0-beta.0", "", { "dependencies": { "whatwg-url": "^7.0.0" } }, "sha512-2ymg6oRBpebeZi9UUNsgQ89bhx01TcTkmNTGnNO88imTmbSgy4nfujrgVEFKWpMTEGA11EDkTt7mqObTPdigIA=="],
"string-width": ["string-width@5.1.2", "", { "dependencies": { "eastasianwidth": "^0.2.0", "emoji-regex": "^9.2.2", "strip-ansi": "^7.0.1" } }, "sha512-HnLOCR3vjcY8beoNLtcjZ5/nxn2afmME6lhrDrebokqMap+XbeW8n9TXpPDOqdGK5qcI3oT0GKTW6wC7EMiVqA=="],
"string-width-cjs": ["string-width@4.2.3", "", { "dependencies": { "emoji-regex": "^8.0.0", "is-fullwidth-code-point": "^3.0.0", "strip-ansi": "^6.0.1" } }, "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g=="],
"strip-ansi": ["strip-ansi@6.0.1", "", { "dependencies": { "ansi-regex": "^5.0.1" } }, "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A=="],
"strip-ansi-cjs": ["strip-ansi@6.0.1", "", { "dependencies": { "ansi-regex": "^5.0.1" } }, "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A=="],
"strip-json-comments": ["strip-json-comments@3.1.1", "", {}, "sha512-6fPc+R4ihwqP6N/aIv2f1gMH8lOVtWQHoqC4yK6oSDVVocumAsfCqjkXnqiYMhmMwS/mEHLp7Vehlt3ql6lEig=="],
"strtok3": ["strtok3@10.3.4", "", { "dependencies": { "@tokenizer/token": "^0.3.0" } }, "sha512-KIy5nylvC5le1OdaaoCJ07L+8iQzJHGH6pWDuzS+d07Cu7n1MZ2x26P8ZKIWfbK02+XIL8Mp4RkWeqdUCrDMfg=="],
"sucrase": ["sucrase@3.35.0", "", { "dependencies": { "@jridgewell/gen-mapping": "^0.3.2", "commander": "^4.0.0", "glob": "^10.3.10", "lines-and-columns": "^1.1.6", "mz": "^2.7.0", "pirates": "^4.0.1", "ts-interface-checker": "^0.1.9" }, "bin": { "sucrase": "bin/sucrase", "sucrase-node": "bin/sucrase-node" } }, "sha512-8EbVDiu9iN/nESwxeSxDKe0dunta1GOlHufmSSXxMD2z2/tMZpDMpvXQGsc+ajGo8y2uYUmixaSRUc/QPoQ0GA=="],
"supports-color": ["supports-color@7.2.0", "", { "dependencies": { "has-flag": "^4.0.0" } }, "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw=="],
"text-table": ["text-table@0.2.0", "", {}, "sha512-N+8UisAXDGk8PFXP4HAzVR9nbfmVJ3zYLAWiTIoqC5v5isinhr+r5uaO8+7r3BMfuNIufIsA7RdpVgacC2cSpw=="],
"thenify": ["thenify@3.3.1", "", { "dependencies": { "any-promise": "^1.0.0" } }, "sha512-RVZSIV5IG10Hk3enotrhvz0T9em6cyHBLkH/YAZuKqd8hRkKhSfCGIcP2KUY0EPxndzANBmNllzWPwak+bheSw=="],
"thenify-all": ["thenify-all@1.6.0", "", { "dependencies": { "thenify": ">= 3.1.0 < 4" } }, "sha512-RNxQH/qI8/t3thXJDwcstUO4zeqo64+Uy/+sNVRBx4Xn2OX+OZ9oP+iJnNFqplFra2ZUVeKCSa2oVWi3T4uVmA=="],
"tinyexec": ["tinyexec@0.3.2", "", {}, "sha512-KQQR9yN7R5+OSwaK0XQoj22pwHoTlgYqmUscPYoknOoWCWfj/5/ABTMRi69FrKU5ffPVh5QcFikpWJI/P1ocHA=="],
"tinyglobby": ["tinyglobby@0.2.15", "", { "dependencies": { "fdir": "^6.5.0", "picomatch": "^4.0.3" } }, "sha512-j2Zq4NyQYG5XMST4cbs02Ak8iJUdxRM0XI5QyxXuZOzKOINmWurp3smXu3y5wDcJrptwpSjgXHzIQxR0omXljQ=="],
"token-types": ["token-types@6.1.1", "", { "dependencies": { "@borewit/text-codec": "^0.1.0", "@tokenizer/token": "^0.3.0", "ieee754": "^1.2.1" } }, "sha512-kh9LVIWH5CnL63Ipf0jhlBIy0UsrMj/NJDfpsy1SqOXlLKEVyXXYrnFxFT1yOOYVGBSApeVnjPw/sBz5BfEjAQ=="],
"tr46": ["tr46@1.0.1", "", { "dependencies": { "punycode": "^2.1.0" } }, "sha512-dTpowEjclQ7Kgx5SdBkqRzVhERQXov8/l9Ft9dVM9fmg0W0KQSVaXX9T4i6twCPNtYiZM53lpSSUAwJbFPOHxA=="],
"tree-kill": ["tree-kill@1.2.2", "", { "bin": { "tree-kill": "cli.js" } }, "sha512-L0Orpi8qGpRG//Nd+H90vFB+3iHnue1zSSGmNOOCh1GLJ7rUKVwV2HvijphGQS2UmhUZewS9VgvxYIdgr+fG1A=="],
"ts-interface-checker": ["ts-interface-checker@0.1.13", "", {}, "sha512-Y/arvbn+rrz3JCKl9C4kVNfTfSm2/mEp5FSz5EsZSANGPSlQrpRI5M4PKF+mJnE52jOO90PnPSc3Ur3bTQw0gA=="],
"tsup": ["tsup@8.5.0", "", { "dependencies": { "bundle-require": "^5.1.0", "cac": "^6.7.14", "chokidar": "^4.0.3", "consola": "^3.4.0", "debug": "^4.4.0", "esbuild": "^0.25.0", "fix-dts-default-cjs-exports": "^1.0.0", "joycon": "^3.1.1", "picocolors": "^1.1.1", "postcss-load-config": "^6.0.1", "resolve-from": "^5.0.0", "rollup": "^4.34.8", "source-map": "0.8.0-beta.0", "sucrase": "^3.35.0", "tinyexec": "^0.3.2", "tinyglobby": "^0.2.11", "tree-kill": "^1.2.2" }, "peerDependencies": { "@microsoft/api-extractor": "^7.36.0", "@swc/core": "^1", "postcss": "^8.4.12", "typescript": ">=4.5.0" }, "optionalPeers": ["@microsoft/api-extractor", "@swc/core", "postcss", "typescript"], "bin": { "tsup": "dist/cli-default.js", "tsup-node": "dist/cli-node.js" } }, "sha512-VmBp77lWNQq6PfuMqCHD3xWl22vEoWsKajkF8t+yMBawlUS8JzEI+vOVMeuNZIuMML8qXRizFKi9oD5glKQVcQ=="],
"type-check": ["type-check@0.4.0", "", { "dependencies": { "prelude-ls": "^1.2.1" } }, "sha512-XleUoc9uwGXqjWwXaUTZAmzMcFZ5858QA2vvx1Ur5xIcixXIP+8LnFDgRplU30us6teqdlskFfu+ae4K79Ooew=="],
"typescript": ["typescript@5.9.2", "", { "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" } }, "sha512-CWBzXQrc/qOkhidw1OzBTQuYRbfyxDXJMVJ1XNwUHGROVmuaeiEm3OslpZ1RV96d7SKKjZKrSJu3+t/xlw3R9A=="],
"ufo": ["ufo@1.6.1", "", {}, "sha512-9a4/uxlTWJ4+a5i0ooc1rU7C7YOw3wT+UGqdeNNHWnOF9qcMBgLRS+4IYUqbczewFx4mLEig6gawh7X6mFlEkA=="],
"uint8array-extras": ["uint8array-extras@1.5.0", "", {}, "sha512-rvKSBiC5zqCCiDZ9kAOszZcDvdAHwwIKJG33Ykj43OKcWsnmcBRL09YTU4nOeHZ8Y2a7l1MgTd08SBe9A8Qj6A=="],
"undici-types": ["undici-types@6.21.0", "", {}, "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ=="],
"uri-js": ["uri-js@4.4.1", "", { "dependencies": { "punycode": "^2.1.0" } }, "sha512-7rKUyy33Q1yc98pQ1DAmLtwX109F7TIfWlW1Ydo8Wl1ii1SeHieeh0HHfPeL2fMXK6z0s8ecKs9frCuLJvndBg=="],
"webidl-conversions": ["webidl-conversions@4.0.2", "", {}, "sha512-YQ+BmxuTgd6UXZW3+ICGfyqRyHXVlD5GtQr5+qjiNW7bF0cqrzX500HVXPBOvgXb5YnzDd+h0zqyv61KUD7+Sg=="],
"whatwg-url": ["whatwg-url@7.1.0", "", { "dependencies": { "lodash.sortby": "^4.7.0", "tr46": "^1.0.1", "webidl-conversions": "^4.0.2" } }, "sha512-WUu7Rg1DroM7oQvGWfOiAK21n74Gg+T4elXEQYkOhtyLeWiJFoOGLXPKI/9gzIie9CtwVLm8wtw6YJdKyxSjeg=="],
"which": ["which@2.0.2", "", { "dependencies": { "isexe": "^2.0.0" }, "bin": { "node-which": "./bin/node-which" } }, "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA=="],
"word-wrap": ["word-wrap@1.2.5", "", {}, "sha512-BN22B5eaMMI9UMtjrGd5g5eCYPpCPDUy0FJXbYsaT5zYxjFOckS53SQDE3pWkVoWpHXVb3BrYcEN4Twa55B5cA=="],
"wrap-ansi": ["wrap-ansi@8.1.0", "", { "dependencies": { "ansi-styles": "^6.1.0", "string-width": "^5.0.1", "strip-ansi": "^7.0.1" } }, "sha512-si7QWI6zUMq56bESFvagtmzMdGOtoxfR+Sez11Mobfc7tm+VkUckk9bW2UeffTGVUbOksxmSw0AA2gs8g71NCQ=="],
"wrap-ansi-cjs": ["wrap-ansi@7.0.0", "", { "dependencies": { "ansi-styles": "^4.0.0", "string-width": "^4.1.0", "strip-ansi": "^6.0.0" } }, "sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q=="],
"yocto-queue": ["yocto-queue@0.1.0", "", {}, "sha512-rVksvsnNCdJ/ohGc6xgPwyN8eheCxsiLM8mxuE/t/mOVqJewPuO1miLpTHQiRgTKCLexL4MeAFVagts7HmNZ2Q=="],
"@eslint-community/eslint-utils/eslint-visitor-keys": ["eslint-visitor-keys@3.4.3", "", {}, "sha512-wpc+LXeiyiisxPlEkUzU6svyS1frIO3Mgxj1fdy7Pm8Ygzguax2N3Fa/D/ag1WqbOprdI+uY6wMUl8/a2G+iag=="],
"@isaacs/cliui/strip-ansi": ["strip-ansi@7.1.2", "", { "dependencies": { "ansi-regex": "^6.0.1" } }, "sha512-gmBGslpoQJtgnMAvOVqGZpEz9dyoKTCzy2nfz/n8aIFhN/jCE/rCmcxabB6jOOHV+0WNnylOxaxBQPSvcWklhA=="],
"bun-types/@types/node": ["@types/node@20.12.14", "", { "dependencies": { "undici-types": "~5.26.4" } }, "sha512-scnD59RpYD91xngrQQLGkE+6UrHUPzeKZWhhjBSa3HSkwjbQc38+q3RoIVEwxQGRw3M+j5hpNAM+lgV3cVormg=="],
"glob/minimatch": ["minimatch@9.0.5", "", { "dependencies": { "brace-expansion": "^2.0.1" } }, "sha512-G6T0ZX48xgozx7587koeX9Ys2NYy6Gmv//P89sEte9V9whIapMNF4idKxnW2QtCcLiTWlb/wfCabAtAFWhhBow=="],
"import-fresh/resolve-from": ["resolve-from@4.0.0", "", {}, "sha512-pb/MYmXstAkysRFx8piNI1tGFNQIFA3vkE3Gq4EuA1dF6gHp/+vgZqsCGJapvy8N3Q+4o7FwvquPJcnZ7RYy4g=="],
"string-width/strip-ansi": ["strip-ansi@7.1.2", "", { "dependencies": { "ansi-regex": "^6.0.1" } }, "sha512-gmBGslpoQJtgnMAvOVqGZpEz9dyoKTCzy2nfz/n8aIFhN/jCE/rCmcxabB6jOOHV+0WNnylOxaxBQPSvcWklhA=="],
"string-width-cjs/emoji-regex": ["emoji-regex@8.0.0", "", {}, "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A=="],
"wrap-ansi/ansi-styles": ["ansi-styles@6.2.3", "", {}, "sha512-4Dj6M28JB+oAH8kFkTLUo+a2jwOFkuqb3yucU0CANcRRUbxS0cP0nZYCGjcc3BNXwRIsUVmDGgzawme7zvJHvg=="],
"wrap-ansi/strip-ansi": ["strip-ansi@7.1.2", "", { "dependencies": { "ansi-regex": "^6.0.1" } }, "sha512-gmBGslpoQJtgnMAvOVqGZpEz9dyoKTCzy2nfz/n8aIFhN/jCE/rCmcxabB6jOOHV+0WNnylOxaxBQPSvcWklhA=="],
"wrap-ansi-cjs/string-width": ["string-width@4.2.3", "", { "dependencies": { "emoji-regex": "^8.0.0", "is-fullwidth-code-point": "^3.0.0", "strip-ansi": "^6.0.1" } }, "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g=="],
"@isaacs/cliui/strip-ansi/ansi-regex": ["ansi-regex@6.2.2", "", {}, "sha512-Bq3SmSpyFHaWjPk8If9yc6svM8c56dB5BAtW4Qbw5jHTwwXXcTLoRMkpDJp6VL0XzlWaCHTXrkFURMYmD0sLqg=="],
"bun-types/@types/node/undici-types": ["undici-types@5.26.5", "", {}, "sha512-JlCMO+ehdEIKqlFxk6IfVoAUVmgz7cU7zD/h9XZ0qzeosSHmUJVOzSQvvYSYWXkFXC+IfLKSIffhv0sVZup6pA=="],
"glob/minimatch/brace-expansion": ["brace-expansion@2.0.2", "", { "dependencies": { "balanced-match": "^1.0.0" } }, "sha512-Jt0vHyM+jmUBqojB7E1NIYadt0vI0Qxjxd2TErW94wDz+E2LAm5vKMXXwg6ZZBTHPuUlDgQHKXvjGBdfcF1ZDQ=="],
"string-width/strip-ansi/ansi-regex": ["ansi-regex@6.2.2", "", {}, "sha512-Bq3SmSpyFHaWjPk8If9yc6svM8c56dB5BAtW4Qbw5jHTwwXXcTLoRMkpDJp6VL0XzlWaCHTXrkFURMYmD0sLqg=="],
"wrap-ansi-cjs/string-width/emoji-regex": ["emoji-regex@8.0.0", "", {}, "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A=="],
"wrap-ansi/strip-ansi/ansi-regex": ["ansi-regex@6.2.2", "", {}, "sha512-Bq3SmSpyFHaWjPk8If9yc6svM8c56dB5BAtW4Qbw5jHTwwXXcTLoRMkpDJp6VL0XzlWaCHTXrkFURMYmD0sLqg=="],
}
}
+2
View File
@@ -0,0 +1,2 @@
[install]
registry = "https://registry.npmjs.org/"
+147
View File
@@ -0,0 +1,147 @@
import { Elysia } from 'elysia';
type Origin = string | RegExp | ((request: Request) => boolean | void);
export type HTTPMethod = 'ACL' | 'BIND' | 'CHECKOUT' | 'CONNECT' | 'COPY' | 'DELETE' | 'GET' | 'HEAD' | 'LINK' | 'LOCK' | 'M-SEARCH' | 'MERGE' | 'MKACTIVITY' | 'MKCALENDAR' | 'MKCOL' | 'MOVE' | 'NOTIFY' | 'OPTIONS' | 'PATCH' | 'POST' | 'PROPFIND' | 'PROPPATCH' | 'PURGE' | 'PUT' | 'REBIND' | 'REPORT' | 'SEARCH' | 'SOURCE' | 'SUBSCRIBE' | 'TRACE' | 'UNBIND' | 'UNLINK' | 'UNLOCK' | 'UNSUBSCRIBE';
type MaybeArray<T> = T | T[];
export interface CORSConfig {
/**
* Disable AOT (Ahead of Time) compilation for plugin instance
*
* @default true
*/
aot?: boolean;
/**
* @default `true`
*
* Assign the **Access-Control-Allow-Origin** header.
*
* Value can be one of the following:
* - `string` - String of origin which will be directly assign to `Access-Control-Allow-Origin`
*
* - `boolean` - If set to true, `Access-Control-Allow-Origin` will be set to `*` (accept all origin)
*
* - `RegExp` - Pattern to use to test with request's url, will accept origin if matched.
*
* - `Function` - Custom logic to validate origin acceptance or not. will accept origin if `true` is returned.
* - Function will accepts `Context` just like `Handler`
*
* ```typescript
* // ? Example usage
* app.use(cors, {
* origin: ({ request, headers }) => true
* })
*
* // Type Definition
* type CORSOriginFn = (context: Context) => boolean | void
* ```
*
* - `Array<string | RegExp | Function>` - Will try to find truthy value of all options above. Will accept request if one is `true`.
*/
origin?: Origin | boolean | Origin[];
/**
* @default `*`
*
* Assign **Access-Control-Allow-Methods** header.
*
* Value can be one of the following:
* Accept:
* - `undefined | null | ''` - Ignore all methods.
*
* - `*` - Accept all methods.
*
* - `HTTPMethod` - Will be directly set to **Access-Control-Allow-Methods**.
* - Expects either a single method or a comma-delimited string (eg: 'GET, PUT, POST')
*
* - `HTTPMethod[]` - Allow multiple HTTP methods.
* - eg: ['GET', 'PUT', 'POST']
*/
methods?: boolean | undefined | null | '' | '*' | MaybeArray<HTTPMethod | (string & {})>;
/**
* @default `*`
*
* Assign **Access-Control-Allow-Headers** header.
*
* Allow incoming request with the specified headers.
*
* Value can be one of the following:
* - `string`
* - Expects either a single method or a comma-delimited string (eg: 'Content-Type, Authorization').
*
* - `string[]` - Allow multiple HTTP methods.
* - eg: ['Content-Type', 'Authorization']
*/
allowedHeaders?: true | string | string[];
/**
* @default `*`
*
* Assign **Access-Control-Expose-Headers** header.
*
* Return the specified headers to request in CORS mode.
*
* Value can be one of the following:
* - `string`
* - Expects either a single method or a comma-delimited string (eg: 'Content-Type, 'X-Powered-By').
*
* - `string[]` - Allow multiple HTTP methods.
* - eg: ['Content-Type', 'X-Powered-By']
*/
exposeHeaders?: true | string | string[];
/**
* @default `true`
*
* Assign **Access-Control-Allow-Credentials** header.
*
* Allow incoming requests to send `credentials` header.
*
* - `boolean` - Available if set to `true`.
*/
credentials?: boolean;
/**
* @default `5`
*
* Assign **Access-Control-Max-Age** header.
*
* Allow incoming requests to send `credentials` header.
*
* - `number` - Duration in seconds to indicates how long the results of a preflight request can be cached.
*/
maxAge?: number;
/**
* @default `true`
*
* Add `[OPTIONS] /*` handler to handle preflight request which response with `HTTP 204` and CORS hints.
*
* - `boolean` - Available if set to `true`.
*/
preflight?: boolean;
}
export declare const cors: (config?: CORSConfig) => Elysia<"", {
decorator: {};
store: {};
derive: {};
resolve: {};
}, {
typebox: {};
error: {};
}, {
schema: {};
standaloneSchema: {};
macro: {};
macroFn: {};
parser: {};
response: {};
}, {}, {
derive: {};
resolve: {};
schema: {};
standaloneSchema: {};
response: {};
}, {
derive: {};
resolve: {};
schema: {};
standaloneSchema: {};
response: {
200: import("undici-types").Response;
};
}>;
export default cors;
+167
View File
@@ -0,0 +1,167 @@
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
// src/index.ts
var index_exports = {};
__export(index_exports, {
cors: () => cors,
default: () => index_default
});
module.exports = __toCommonJS(index_exports);
var import_elysia = require("elysia");
var isBun = typeof new Headers()?.toJSON === "function";
var processHeaders = (headers) => {
if (isBun) return Object.keys(headers.toJSON()).join(", ");
let keys = "";
let i = 0;
headers.forEach((_, key) => {
if (i) keys = keys + ", " + key;
else keys = key;
i++;
});
return keys;
};
var cors = (config) => {
let {
aot = true,
origin = true,
methods = true,
allowedHeaders = true,
exposeHeaders = true,
credentials = true,
maxAge = 5,
preflight = true
} = config ?? {};
if (Array.isArray(allowedHeaders))
allowedHeaders = allowedHeaders.join(", ");
if (Array.isArray(exposeHeaders)) exposeHeaders = exposeHeaders.join(", ");
const origins = typeof origin === "boolean" ? void 0 : Array.isArray(origin) ? origin : [origin];
const app = new import_elysia.Elysia({
name: "@elysiajs/cors",
seed: config,
aot
});
const anyOrigin = origins?.some((o) => o === "*");
const originMap = {};
if (origins) {
for (const origin2 of origins)
if (typeof origin2 === "string") originMap[origin2] = true;
}
const processOrigin = (origin2, request, from) => {
if (Array.isArray(origin2))
return origin2.some((o) => processOrigin(o, request, from));
switch (typeof origin2) {
case "string":
if (from in originMap) return true;
const fromProtocol = from.indexOf("://");
if (fromProtocol !== -1) from = from.slice(fromProtocol + 3);
return origin2 === from;
case "function":
return origin2(request) === true;
case "object":
if (origin2 instanceof RegExp) return origin2.test(from);
}
return false;
};
const handleOrigin = (set, request) => {
if (origin === true) {
set.headers.vary = "*";
set.headers["access-control-allow-origin"] = request.headers.get("Origin") || "*";
return;
}
if (anyOrigin) {
set.headers.vary = "*";
set.headers["access-control-allow-origin"] = "*";
return;
}
if (!origins?.length) return;
if (origins.length) {
const from = request.headers.get("Origin") ?? "";
for (let i = 0; i < origins.length; i++) {
const value = processOrigin(origins[i], request, from);
if (value === true) {
set.headers.vary = origin ? "Origin" : "*";
set.headers["access-control-allow-origin"] = from || "*";
return;
}
}
}
set.headers.vary = "Origin";
};
const handleMethod = (set, method) => {
if (!method) return;
if (methods === true)
return set.headers["access-control-allow-methods"] = method ?? "*";
if (methods === false || !methods?.length) return;
if (methods === "*")
return set.headers["access-control-allow-methods"] = "*";
if (!Array.isArray(methods))
return set.headers["access-control-allow-methods"] = methods;
set.headers["access-control-allow-methods"] = methods.join(", ");
};
const defaultHeaders = {};
if (typeof exposeHeaders === "string")
defaultHeaders["access-control-expose-headers"] = exposeHeaders;
if (typeof allowedHeaders === "string")
defaultHeaders["access-control-allow-headers"] = allowedHeaders;
if (credentials === true)
defaultHeaders["access-control-allow-credentials"] = "true";
app.headers(defaultHeaders);
function handleOption({ set, request, headers }) {
handleOrigin(set, request);
handleMethod(set, request.headers.get("access-control-request-method"));
if (allowedHeaders === true || exposeHeaders === true) {
if (allowedHeaders === true)
set.headers["access-control-allow-headers"] = headers["access-control-request-headers"];
if (exposeHeaders === true)
set.headers["access-control-expose-headers"] = Object.keys(headers).join(",");
}
if (maxAge) set.headers["access-control-max-age"] = maxAge.toString();
return new Response(null, {
status: 204
});
}
if (preflight) app.options("/", handleOption).options("/*", handleOption);
return app.onRequest(function processCors({ set, request }) {
handleOrigin(set, request);
if (preflight && request.method === "OPTIONS") {
return handleOption({
set,
request,
headers: isBun ? request.headers.toJSON() : (
// for non-Bun environments
Object.fromEntries(request.headers.entries())
)
});
}
handleMethod(set, request.method);
if (allowedHeaders === true || exposeHeaders === true) {
const headers = processHeaders(request.headers);
if (allowedHeaders === true)
set.headers["access-control-allow-headers"] = headers;
if (exposeHeaders === true)
set.headers["access-control-expose-headers"] = headers;
}
});
};
var index_default = cors;
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
cors
});
+147
View File
@@ -0,0 +1,147 @@
import { Elysia } from 'elysia';
type Origin = string | RegExp | ((request: Request) => boolean | void);
export type HTTPMethod = 'ACL' | 'BIND' | 'CHECKOUT' | 'CONNECT' | 'COPY' | 'DELETE' | 'GET' | 'HEAD' | 'LINK' | 'LOCK' | 'M-SEARCH' | 'MERGE' | 'MKACTIVITY' | 'MKCALENDAR' | 'MKCOL' | 'MOVE' | 'NOTIFY' | 'OPTIONS' | 'PATCH' | 'POST' | 'PROPFIND' | 'PROPPATCH' | 'PURGE' | 'PUT' | 'REBIND' | 'REPORT' | 'SEARCH' | 'SOURCE' | 'SUBSCRIBE' | 'TRACE' | 'UNBIND' | 'UNLINK' | 'UNLOCK' | 'UNSUBSCRIBE';
type MaybeArray<T> = T | T[];
export interface CORSConfig {
/**
* Disable AOT (Ahead of Time) compilation for plugin instance
*
* @default true
*/
aot?: boolean;
/**
* @default `true`
*
* Assign the **Access-Control-Allow-Origin** header.
*
* Value can be one of the following:
* - `string` - String of origin which will be directly assign to `Access-Control-Allow-Origin`
*
* - `boolean` - If set to true, `Access-Control-Allow-Origin` will be set to `*` (accept all origin)
*
* - `RegExp` - Pattern to use to test with request's url, will accept origin if matched.
*
* - `Function` - Custom logic to validate origin acceptance or not. will accept origin if `true` is returned.
* - Function will accepts `Context` just like `Handler`
*
* ```typescript
* // ? Example usage
* app.use(cors, {
* origin: ({ request, headers }) => true
* })
*
* // Type Definition
* type CORSOriginFn = (context: Context) => boolean | void
* ```
*
* - `Array<string | RegExp | Function>` - Will try to find truthy value of all options above. Will accept request if one is `true`.
*/
origin?: Origin | boolean | Origin[];
/**
* @default `*`
*
* Assign **Access-Control-Allow-Methods** header.
*
* Value can be one of the following:
* Accept:
* - `undefined | null | ''` - Ignore all methods.
*
* - `*` - Accept all methods.
*
* - `HTTPMethod` - Will be directly set to **Access-Control-Allow-Methods**.
* - Expects either a single method or a comma-delimited string (eg: 'GET, PUT, POST')
*
* - `HTTPMethod[]` - Allow multiple HTTP methods.
* - eg: ['GET', 'PUT', 'POST']
*/
methods?: boolean | undefined | null | '' | '*' | MaybeArray<HTTPMethod | (string & {})>;
/**
* @default `*`
*
* Assign **Access-Control-Allow-Headers** header.
*
* Allow incoming request with the specified headers.
*
* Value can be one of the following:
* - `string`
* - Expects either a single method or a comma-delimited string (eg: 'Content-Type, Authorization').
*
* - `string[]` - Allow multiple HTTP methods.
* - eg: ['Content-Type', 'Authorization']
*/
allowedHeaders?: true | string | string[];
/**
* @default `*`
*
* Assign **Access-Control-Expose-Headers** header.
*
* Return the specified headers to request in CORS mode.
*
* Value can be one of the following:
* - `string`
* - Expects either a single method or a comma-delimited string (eg: 'Content-Type, 'X-Powered-By').
*
* - `string[]` - Allow multiple HTTP methods.
* - eg: ['Content-Type', 'X-Powered-By']
*/
exposeHeaders?: true | string | string[];
/**
* @default `true`
*
* Assign **Access-Control-Allow-Credentials** header.
*
* Allow incoming requests to send `credentials` header.
*
* - `boolean` - Available if set to `true`.
*/
credentials?: boolean;
/**
* @default `5`
*
* Assign **Access-Control-Max-Age** header.
*
* Allow incoming requests to send `credentials` header.
*
* - `number` - Duration in seconds to indicates how long the results of a preflight request can be cached.
*/
maxAge?: number;
/**
* @default `true`
*
* Add `[OPTIONS] /*` handler to handle preflight request which response with `HTTP 204` and CORS hints.
*
* - `boolean` - Available if set to `true`.
*/
preflight?: boolean;
}
export declare const cors: (config?: CORSConfig) => Elysia<"", {
decorator: {};
store: {};
derive: {};
resolve: {};
}, {
typebox: {};
error: {};
}, {
schema: {};
standaloneSchema: {};
macro: {};
macroFn: {};
parser: {};
response: {};
}, {}, {
derive: {};
resolve: {};
schema: {};
standaloneSchema: {};
response: {};
}, {
derive: {};
resolve: {};
schema: {};
standaloneSchema: {};
response: {
200: import("undici-types").Response;
};
}>;
export default cors;
+142
View File
@@ -0,0 +1,142 @@
// src/index.ts
import { Elysia } from "elysia";
var isBun = typeof new Headers()?.toJSON === "function";
var processHeaders = (headers) => {
if (isBun) return Object.keys(headers.toJSON()).join(", ");
let keys = "";
let i = 0;
headers.forEach((_, key) => {
if (i) keys = keys + ", " + key;
else keys = key;
i++;
});
return keys;
};
var cors = (config) => {
let {
aot = true,
origin = true,
methods = true,
allowedHeaders = true,
exposeHeaders = true,
credentials = true,
maxAge = 5,
preflight = true
} = config ?? {};
if (Array.isArray(allowedHeaders))
allowedHeaders = allowedHeaders.join(", ");
if (Array.isArray(exposeHeaders)) exposeHeaders = exposeHeaders.join(", ");
const origins = typeof origin === "boolean" ? void 0 : Array.isArray(origin) ? origin : [origin];
const app = new Elysia({
name: "@elysiajs/cors",
seed: config,
aot
});
const anyOrigin = origins?.some((o) => o === "*");
const originMap = {};
if (origins) {
for (const origin2 of origins)
if (typeof origin2 === "string") originMap[origin2] = true;
}
const processOrigin = (origin2, request, from) => {
if (Array.isArray(origin2))
return origin2.some((o) => processOrigin(o, request, from));
switch (typeof origin2) {
case "string":
if (from in originMap) return true;
const fromProtocol = from.indexOf("://");
if (fromProtocol !== -1) from = from.slice(fromProtocol + 3);
return origin2 === from;
case "function":
return origin2(request) === true;
case "object":
if (origin2 instanceof RegExp) return origin2.test(from);
}
return false;
};
const handleOrigin = (set, request) => {
if (origin === true) {
set.headers.vary = "*";
set.headers["access-control-allow-origin"] = request.headers.get("Origin") || "*";
return;
}
if (anyOrigin) {
set.headers.vary = "*";
set.headers["access-control-allow-origin"] = "*";
return;
}
if (!origins?.length) return;
if (origins.length) {
const from = request.headers.get("Origin") ?? "";
for (let i = 0; i < origins.length; i++) {
const value = processOrigin(origins[i], request, from);
if (value === true) {
set.headers.vary = origin ? "Origin" : "*";
set.headers["access-control-allow-origin"] = from || "*";
return;
}
}
}
set.headers.vary = "Origin";
};
const handleMethod = (set, method) => {
if (!method) return;
if (methods === true)
return set.headers["access-control-allow-methods"] = method ?? "*";
if (methods === false || !methods?.length) return;
if (methods === "*")
return set.headers["access-control-allow-methods"] = "*";
if (!Array.isArray(methods))
return set.headers["access-control-allow-methods"] = methods;
set.headers["access-control-allow-methods"] = methods.join(", ");
};
const defaultHeaders = {};
if (typeof exposeHeaders === "string")
defaultHeaders["access-control-expose-headers"] = exposeHeaders;
if (typeof allowedHeaders === "string")
defaultHeaders["access-control-allow-headers"] = allowedHeaders;
if (credentials === true)
defaultHeaders["access-control-allow-credentials"] = "true";
app.headers(defaultHeaders);
function handleOption({ set, request, headers }) {
handleOrigin(set, request);
handleMethod(set, request.headers.get("access-control-request-method"));
if (allowedHeaders === true || exposeHeaders === true) {
if (allowedHeaders === true)
set.headers["access-control-allow-headers"] = headers["access-control-request-headers"];
if (exposeHeaders === true)
set.headers["access-control-expose-headers"] = Object.keys(headers).join(",");
}
if (maxAge) set.headers["access-control-max-age"] = maxAge.toString();
return new Response(null, {
status: 204
});
}
if (preflight) app.options("/", handleOption).options("/*", handleOption);
return app.onRequest(function processCors({ set, request }) {
handleOrigin(set, request);
if (preflight && request.method === "OPTIONS") {
return handleOption({
set,
request,
headers: isBun ? request.headers.toJSON() : (
// for non-Bun environments
Object.fromEntries(request.headers.entries())
)
});
}
handleMethod(set, request.method);
if (allowedHeaders === true || exposeHeaders === true) {
const headers = processHeaders(request.headers);
if (allowedHeaders === true)
set.headers["access-control-allow-headers"] = headers;
if (exposeHeaders === true)
set.headers["access-control-expose-headers"] = headers;
}
});
};
var index_default = cors;
export {
cors,
index_default as default
};
+49
View File
@@ -0,0 +1,49 @@
{
"name": "@elysiajs/cors",
"version": "1.4.1",
"description": "Plugin for Elysia that for Cross Origin Requests (CORs)",
"author": {
"name": "saltyAom",
"url": "https://github.com/SaltyAom",
"email": "saltyaom@gmail.com"
},
"repository": {
"type": "git",
"url": "https://github.com/elysiajs/elysia-cors"
},
"main": "./dist/cjs/index.js",
"module": "./dist/index.mjs",
"types": "./dist/index.d.ts",
"exports": {
"./package.json": "./package.json",
".": {
"types": "./dist/index.d.ts",
"import": "./dist/index.mjs",
"require": "./dist/cjs/index.js"
}
},
"homepage": "https://github.com/elysiajs/elysia-cors",
"keywords": [
"elysia",
"cors"
],
"license": "MIT",
"scripts": {
"dev": "bun run --watch example/index.ts",
"test": "bun test && npm run test:node",
"test:node": "npm install --prefix ./test/node/cjs/ && npm install --prefix ./test/node/esm/ && node ./test/node/cjs/index.js && node ./test/node/esm/index.js",
"build": "bun build.ts",
"release": "npm run build && npm run test && npm publish --access public"
},
"devDependencies": {
"@types/bun": "1.1.14",
"@types/node": "^20.14.10",
"elysia": "1.4.0",
"eslint": "9.6.0",
"tsup": "^8.1.0",
"typescript": "^5.5.2"
},
"peerDependencies": {
"elysia": ">= 1.4.0"
}
}
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) Hiroki Osame <hiroki.osame@gmail.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.
+11
View File
@@ -0,0 +1,11 @@
# @esbuild-kit/core-utils
Core utility functions used by [@esbuild-kit/cjs-loader](https://github.com/esbuild-kit/cjs-loader) and [@esbuild-kit/esm-loader](https://github.com/esbuild-kit/esm-loader).
## Library
### esbuild
Transform defaults, caching, and source-map handling.
### Source map support
Uses [native source-map](https://nodejs.org/api/process.html#processsetsourcemapsenabledval) if available, fallsback to [source-map-support](https://www.npmjs.com/package/source-map-support).
+32
View File
@@ -0,0 +1,32 @@
import { MessagePort } from 'node:worker_threads';
import { UrlAndMap } from 'source-map-support';
import { TransformOptions } from 'esbuild';
type Transformed = {
code: string;
map: RawSourceMap;
warnings?: unknown[];
};
type RawSourceMap = UrlAndMap['map'];
declare function installSourceMapSupport(
/**
* To support Node v20 where loaders are executed in its own thread
* https://nodejs.org/docs/latest-v20.x/api/esm.html#globalpreload
*/
loaderPort?: MessagePort): ({ code, map }: Transformed, filePath: string, mainThreadPort?: MessagePort) => string;
declare function transformDynamicImport(filePath: string, code: string): {
code: string;
map: any;
} | undefined;
declare function transformSync(code: string, filePath: string, extendOptions?: TransformOptions): Transformed;
declare function transform(code: string, filePath: string, extendOptions?: TransformOptions): Promise<Transformed>;
declare const resolveTsPath: (filePath: string) => string | undefined;
type Version = [number, number, number];
declare const compareNodeVersion: (version: Version) => number;
export { RawSourceMap, compareNodeVersion, installSourceMapSupport, resolveTsPath, transform, transformDynamicImport, transformSync };
File diff suppressed because one or more lines are too long
+1
View File
@@ -0,0 +1 @@
../esbuild/bin/esbuild
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2020 Evan Wallace
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
@@ -0,0 +1,3 @@
# esbuild
This is a JavaScript bundler and minifier. See https://github.com/evanw/esbuild and the [JavaScript API documentation](https://esbuild.github.io/api/) for details.
Binary file not shown.
@@ -0,0 +1,287 @@
"use strict";
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
// If the importer is in node compatibility mode or this is not an ESM
// file that has been converted to a CommonJS file using a Babel-
// compatible transform (i.e. "__esModule" has not been set), then set
// "default" to the CommonJS "module.exports" for node compatibility.
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
mod
));
// lib/npm/node-platform.ts
var fs = require("fs");
var os = require("os");
var path = require("path");
var ESBUILD_BINARY_PATH = process.env.ESBUILD_BINARY_PATH || ESBUILD_BINARY_PATH;
var isValidBinaryPath = (x) => !!x && x !== "/usr/bin/esbuild";
var knownWindowsPackages = {
"win32 arm64 LE": "@esbuild/win32-arm64",
"win32 ia32 LE": "@esbuild/win32-ia32",
"win32 x64 LE": "@esbuild/win32-x64"
};
var knownUnixlikePackages = {
"android arm64 LE": "@esbuild/android-arm64",
"darwin arm64 LE": "@esbuild/darwin-arm64",
"darwin x64 LE": "@esbuild/darwin-x64",
"freebsd arm64 LE": "@esbuild/freebsd-arm64",
"freebsd x64 LE": "@esbuild/freebsd-x64",
"linux arm LE": "@esbuild/linux-arm",
"linux arm64 LE": "@esbuild/linux-arm64",
"linux ia32 LE": "@esbuild/linux-ia32",
"linux mips64el LE": "@esbuild/linux-mips64el",
"linux ppc64 LE": "@esbuild/linux-ppc64",
"linux riscv64 LE": "@esbuild/linux-riscv64",
"linux s390x BE": "@esbuild/linux-s390x",
"linux x64 LE": "@esbuild/linux-x64",
"linux loong64 LE": "@esbuild/linux-loong64",
"netbsd x64 LE": "@esbuild/netbsd-x64",
"openbsd x64 LE": "@esbuild/openbsd-x64",
"sunos x64 LE": "@esbuild/sunos-x64"
};
var knownWebAssemblyFallbackPackages = {
"android arm LE": "@esbuild/android-arm",
"android x64 LE": "@esbuild/android-x64"
};
function pkgAndSubpathForCurrentPlatform() {
let pkg;
let subpath;
let isWASM = false;
let platformKey = `${process.platform} ${os.arch()} ${os.endianness()}`;
if (platformKey in knownWindowsPackages) {
pkg = knownWindowsPackages[platformKey];
subpath = "esbuild.exe";
} else if (platformKey in knownUnixlikePackages) {
pkg = knownUnixlikePackages[platformKey];
subpath = "bin/esbuild";
} else if (platformKey in knownWebAssemblyFallbackPackages) {
pkg = knownWebAssemblyFallbackPackages[platformKey];
subpath = "bin/esbuild";
isWASM = true;
} else {
throw new Error(`Unsupported platform: ${platformKey}`);
}
return { pkg, subpath, isWASM };
}
function downloadedBinPath(pkg, subpath) {
const esbuildLibDir = path.dirname(require.resolve("esbuild"));
return path.join(esbuildLibDir, `downloaded-${pkg.replace("/", "-")}-${path.basename(subpath)}`);
}
// lib/npm/node-install.ts
var fs2 = require("fs");
var os2 = require("os");
var path2 = require("path");
var zlib = require("zlib");
var https = require("https");
var child_process = require("child_process");
var versionFromPackageJSON = require(path2.join(__dirname, "package.json")).version;
var toPath = path2.join(__dirname, "bin", "esbuild");
var isToPathJS = true;
function validateBinaryVersion(...command) {
command.push("--version");
let stdout;
try {
stdout = child_process.execFileSync(command.shift(), command, {
// Without this, this install script strangely crashes with the error
// "EACCES: permission denied, write" but only on Ubuntu Linux when node is
// installed from the Snap Store. This is not a problem when you download
// the official version of node. The problem appears to be that stderr
// (i.e. file descriptor 2) isn't writable?
//
// More info:
// - https://snapcraft.io/ (what the Snap Store is)
// - https://nodejs.org/dist/ (download the official version of node)
// - https://github.com/evanw/esbuild/issues/1711#issuecomment-1027554035
//
stdio: "pipe"
}).toString().trim();
} catch (err) {
if (os2.platform() === "darwin" && /_SecTrustEvaluateWithError/.test(err + "")) {
let os3 = "this version of macOS";
try {
os3 = "macOS " + child_process.execFileSync("sw_vers", ["-productVersion"]).toString().trim();
} catch {
}
throw new Error(`The "esbuild" package cannot be installed because ${os3} is too outdated.
The Go compiler (which esbuild relies on) no longer supports ${os3},
which means the "esbuild" binary executable can't be run. You can either:
* Update your version of macOS to one that the Go compiler supports
* Use the "esbuild-wasm" package instead of the "esbuild" package
* Build esbuild yourself using an older version of the Go compiler
`);
}
throw err;
}
if (stdout !== versionFromPackageJSON) {
throw new Error(`Expected ${JSON.stringify(versionFromPackageJSON)} but got ${JSON.stringify(stdout)}`);
}
}
function isYarn() {
const { npm_config_user_agent } = process.env;
if (npm_config_user_agent) {
return /\byarn\//.test(npm_config_user_agent);
}
return false;
}
function fetch(url) {
return new Promise((resolve, reject) => {
https.get(url, (res) => {
if ((res.statusCode === 301 || res.statusCode === 302) && res.headers.location)
return fetch(res.headers.location).then(resolve, reject);
if (res.statusCode !== 200)
return reject(new Error(`Server responded with ${res.statusCode}`));
let chunks = [];
res.on("data", (chunk) => chunks.push(chunk));
res.on("end", () => resolve(Buffer.concat(chunks)));
}).on("error", reject);
});
}
function extractFileFromTarGzip(buffer, subpath) {
try {
buffer = zlib.unzipSync(buffer);
} catch (err) {
throw new Error(`Invalid gzip data in archive: ${err && err.message || err}`);
}
let str = (i, n) => String.fromCharCode(...buffer.subarray(i, i + n)).replace(/\0.*$/, "");
let offset = 0;
subpath = `package/${subpath}`;
while (offset < buffer.length) {
let name = str(offset, 100);
let size = parseInt(str(offset + 124, 12), 8);
offset += 512;
if (!isNaN(size)) {
if (name === subpath)
return buffer.subarray(offset, offset + size);
offset += size + 511 & ~511;
}
}
throw new Error(`Could not find ${JSON.stringify(subpath)} in archive`);
}
function installUsingNPM(pkg, subpath, binPath) {
const env = { ...process.env, npm_config_global: void 0 };
const esbuildLibDir = path2.dirname(require.resolve("esbuild"));
const installDir = path2.join(esbuildLibDir, "npm-install");
fs2.mkdirSync(installDir);
try {
fs2.writeFileSync(path2.join(installDir, "package.json"), "{}");
child_process.execSync(
`npm install --loglevel=error --prefer-offline --no-audit --progress=false ${pkg}@${versionFromPackageJSON}`,
{ cwd: installDir, stdio: "pipe", env }
);
const installedBinPath = path2.join(installDir, "node_modules", pkg, subpath);
fs2.renameSync(installedBinPath, binPath);
} finally {
try {
removeRecursive(installDir);
} catch {
}
}
}
function removeRecursive(dir) {
for (const entry of fs2.readdirSync(dir)) {
const entryPath = path2.join(dir, entry);
let stats;
try {
stats = fs2.lstatSync(entryPath);
} catch {
continue;
}
if (stats.isDirectory())
removeRecursive(entryPath);
else
fs2.unlinkSync(entryPath);
}
fs2.rmdirSync(dir);
}
function applyManualBinaryPathOverride(overridePath) {
const pathString = JSON.stringify(overridePath);
fs2.writeFileSync(toPath, `#!/usr/bin/env node
require('child_process').execFileSync(${pathString}, process.argv.slice(2), { stdio: 'inherit' });
`);
const libMain = path2.join(__dirname, "lib", "main.js");
const code = fs2.readFileSync(libMain, "utf8");
fs2.writeFileSync(libMain, `var ESBUILD_BINARY_PATH = ${pathString};
${code}`);
}
function maybeOptimizePackage(binPath) {
if (os2.platform() !== "win32" && !isYarn()) {
const tempPath = path2.join(__dirname, "bin-esbuild");
try {
fs2.linkSync(binPath, tempPath);
fs2.renameSync(tempPath, toPath);
isToPathJS = false;
fs2.unlinkSync(tempPath);
} catch {
}
}
}
async function downloadDirectlyFromNPM(pkg, subpath, binPath) {
const url = `https://registry.npmjs.org/${pkg}/-/${pkg.replace("@esbuild/", "")}-${versionFromPackageJSON}.tgz`;
console.error(`[esbuild] Trying to download ${JSON.stringify(url)}`);
try {
fs2.writeFileSync(binPath, extractFileFromTarGzip(await fetch(url), subpath));
fs2.chmodSync(binPath, 493);
} catch (e) {
console.error(`[esbuild] Failed to download ${JSON.stringify(url)}: ${e && e.message || e}`);
throw e;
}
}
async function checkAndPreparePackage() {
if (isValidBinaryPath(ESBUILD_BINARY_PATH)) {
if (!fs2.existsSync(ESBUILD_BINARY_PATH)) {
console.warn(`[esbuild] Ignoring bad configuration: ESBUILD_BINARY_PATH=${ESBUILD_BINARY_PATH}`);
} else {
applyManualBinaryPathOverride(ESBUILD_BINARY_PATH);
return;
}
}
const { pkg, subpath } = pkgAndSubpathForCurrentPlatform();
let binPath;
try {
binPath = require.resolve(`${pkg}/${subpath}`);
} catch (e) {
console.error(`[esbuild] Failed to find package "${pkg}" on the file system
This can happen if you use the "--no-optional" flag. The "optionalDependencies"
package.json feature is used by esbuild to install the correct binary executable
for your current platform. This install script will now attempt to work around
this. If that fails, you need to remove the "--no-optional" flag to use esbuild.
`);
binPath = downloadedBinPath(pkg, subpath);
try {
console.error(`[esbuild] Trying to install package "${pkg}" using npm`);
installUsingNPM(pkg, subpath, binPath);
} catch (e2) {
console.error(`[esbuild] Failed to install package "${pkg}" using npm: ${e2 && e2.message || e2}`);
try {
await downloadDirectlyFromNPM(pkg, subpath, binPath);
} catch (e3) {
throw new Error(`Failed to install package "${pkg}"`);
}
}
}
maybeOptimizePackage(binPath);
}
checkAndPreparePackage().then(() => {
if (isToPathJS) {
validateBinaryVersion(process.execPath, toPath);
} else {
validateBinaryVersion(toPath);
}
});
@@ -0,0 +1,660 @@
export type Platform = 'browser' | 'node' | 'neutral'
export type Format = 'iife' | 'cjs' | 'esm'
export type Loader = 'base64' | 'binary' | 'copy' | 'css' | 'dataurl' | 'default' | 'empty' | 'file' | 'js' | 'json' | 'jsx' | 'local-css' | 'text' | 'ts' | 'tsx'
export type LogLevel = 'verbose' | 'debug' | 'info' | 'warning' | 'error' | 'silent'
export type Charset = 'ascii' | 'utf8'
export type Drop = 'console' | 'debugger'
interface CommonOptions {
/** Documentation: https://esbuild.github.io/api/#sourcemap */
sourcemap?: boolean | 'linked' | 'inline' | 'external' | 'both'
/** Documentation: https://esbuild.github.io/api/#legal-comments */
legalComments?: 'none' | 'inline' | 'eof' | 'linked' | 'external'
/** Documentation: https://esbuild.github.io/api/#source-root */
sourceRoot?: string
/** Documentation: https://esbuild.github.io/api/#sources-content */
sourcesContent?: boolean
/** Documentation: https://esbuild.github.io/api/#format */
format?: Format
/** Documentation: https://esbuild.github.io/api/#global-name */
globalName?: string
/** Documentation: https://esbuild.github.io/api/#target */
target?: string | string[]
/** Documentation: https://esbuild.github.io/api/#supported */
supported?: Record<string, boolean>
/** Documentation: https://esbuild.github.io/api/#platform */
platform?: Platform
/** Documentation: https://esbuild.github.io/api/#mangle-props */
mangleProps?: RegExp
/** Documentation: https://esbuild.github.io/api/#mangle-props */
reserveProps?: RegExp
/** Documentation: https://esbuild.github.io/api/#mangle-props */
mangleQuoted?: boolean
/** Documentation: https://esbuild.github.io/api/#mangle-props */
mangleCache?: Record<string, string | false>
/** Documentation: https://esbuild.github.io/api/#drop */
drop?: Drop[]
/** Documentation: https://esbuild.github.io/api/#drop-labels */
dropLabels?: string[]
/** Documentation: https://esbuild.github.io/api/#minify */
minify?: boolean
/** Documentation: https://esbuild.github.io/api/#minify */
minifyWhitespace?: boolean
/** Documentation: https://esbuild.github.io/api/#minify */
minifyIdentifiers?: boolean
/** Documentation: https://esbuild.github.io/api/#minify */
minifySyntax?: boolean
/** Documentation: https://esbuild.github.io/api/#line-limit */
lineLimit?: number
/** Documentation: https://esbuild.github.io/api/#charset */
charset?: Charset
/** Documentation: https://esbuild.github.io/api/#tree-shaking */
treeShaking?: boolean
/** Documentation: https://esbuild.github.io/api/#ignore-annotations */
ignoreAnnotations?: boolean
/** Documentation: https://esbuild.github.io/api/#jsx */
jsx?: 'transform' | 'preserve' | 'automatic'
/** Documentation: https://esbuild.github.io/api/#jsx-factory */
jsxFactory?: string
/** Documentation: https://esbuild.github.io/api/#jsx-fragment */
jsxFragment?: string
/** Documentation: https://esbuild.github.io/api/#jsx-import-source */
jsxImportSource?: string
/** Documentation: https://esbuild.github.io/api/#jsx-development */
jsxDev?: boolean
/** Documentation: https://esbuild.github.io/api/#jsx-side-effects */
jsxSideEffects?: boolean
/** Documentation: https://esbuild.github.io/api/#define */
define?: { [key: string]: string }
/** Documentation: https://esbuild.github.io/api/#pure */
pure?: string[]
/** Documentation: https://esbuild.github.io/api/#keep-names */
keepNames?: boolean
/** Documentation: https://esbuild.github.io/api/#color */
color?: boolean
/** Documentation: https://esbuild.github.io/api/#log-level */
logLevel?: LogLevel
/** Documentation: https://esbuild.github.io/api/#log-limit */
logLimit?: number
/** Documentation: https://esbuild.github.io/api/#log-override */
logOverride?: Record<string, LogLevel>
/** Documentation: https://esbuild.github.io/api/#tsconfig-raw */
tsconfigRaw?: string | TsconfigRaw
}
export interface TsconfigRaw {
compilerOptions?: {
alwaysStrict?: boolean
baseUrl?: boolean
experimentalDecorators?: boolean
importsNotUsedAsValues?: 'remove' | 'preserve' | 'error'
jsx?: 'preserve' | 'react-native' | 'react' | 'react-jsx' | 'react-jsxdev'
jsxFactory?: string
jsxFragmentFactory?: string
jsxImportSource?: string
paths?: Record<string, string[]>
preserveValueImports?: boolean
strict?: boolean
target?: string
useDefineForClassFields?: boolean
verbatimModuleSyntax?: boolean
}
}
export interface BuildOptions extends CommonOptions {
/** Documentation: https://esbuild.github.io/api/#bundle */
bundle?: boolean
/** Documentation: https://esbuild.github.io/api/#splitting */
splitting?: boolean
/** Documentation: https://esbuild.github.io/api/#preserve-symlinks */
preserveSymlinks?: boolean
/** Documentation: https://esbuild.github.io/api/#outfile */
outfile?: string
/** Documentation: https://esbuild.github.io/api/#metafile */
metafile?: boolean
/** Documentation: https://esbuild.github.io/api/#outdir */
outdir?: string
/** Documentation: https://esbuild.github.io/api/#outbase */
outbase?: string
/** Documentation: https://esbuild.github.io/api/#external */
external?: string[]
/** Documentation: https://esbuild.github.io/api/#packages */
packages?: 'external'
/** Documentation: https://esbuild.github.io/api/#alias */
alias?: Record<string, string>
/** Documentation: https://esbuild.github.io/api/#loader */
loader?: { [ext: string]: Loader }
/** Documentation: https://esbuild.github.io/api/#resolve-extensions */
resolveExtensions?: string[]
/** Documentation: https://esbuild.github.io/api/#main-fields */
mainFields?: string[]
/** Documentation: https://esbuild.github.io/api/#conditions */
conditions?: string[]
/** Documentation: https://esbuild.github.io/api/#write */
write?: boolean
/** Documentation: https://esbuild.github.io/api/#allow-overwrite */
allowOverwrite?: boolean
/** Documentation: https://esbuild.github.io/api/#tsconfig */
tsconfig?: string
/** Documentation: https://esbuild.github.io/api/#out-extension */
outExtension?: { [ext: string]: string }
/** Documentation: https://esbuild.github.io/api/#public-path */
publicPath?: string
/** Documentation: https://esbuild.github.io/api/#entry-names */
entryNames?: string
/** Documentation: https://esbuild.github.io/api/#chunk-names */
chunkNames?: string
/** Documentation: https://esbuild.github.io/api/#asset-names */
assetNames?: string
/** Documentation: https://esbuild.github.io/api/#inject */
inject?: string[]
/** Documentation: https://esbuild.github.io/api/#banner */
banner?: { [type: string]: string }
/** Documentation: https://esbuild.github.io/api/#footer */
footer?: { [type: string]: string }
/** Documentation: https://esbuild.github.io/api/#entry-points */
entryPoints?: string[] | Record<string, string> | { in: string, out: string }[]
/** Documentation: https://esbuild.github.io/api/#stdin */
stdin?: StdinOptions
/** Documentation: https://esbuild.github.io/plugins/ */
plugins?: Plugin[]
/** Documentation: https://esbuild.github.io/api/#working-directory */
absWorkingDir?: string
/** Documentation: https://esbuild.github.io/api/#node-paths */
nodePaths?: string[]; // The "NODE_PATH" variable from Node.js
}
export interface StdinOptions {
contents: string | Uint8Array
resolveDir?: string
sourcefile?: string
loader?: Loader
}
export interface Message {
id: string
pluginName: string
text: string
location: Location | null
notes: Note[]
/**
* Optional user-specified data that is passed through unmodified. You can
* use this to stash the original error, for example.
*/
detail: any
}
export interface Note {
text: string
location: Location | null
}
export interface Location {
file: string
namespace: string
/** 1-based */
line: number
/** 0-based, in bytes */
column: number
/** in bytes */
length: number
lineText: string
suggestion: string
}
export interface OutputFile {
path: string
contents: Uint8Array
hash: string
/** "contents" as text (changes automatically with "contents") */
readonly text: string
}
export interface BuildResult<ProvidedOptions extends BuildOptions = BuildOptions> {
errors: Message[]
warnings: Message[]
/** Only when "write: false" */
outputFiles: OutputFile[] | (ProvidedOptions['write'] extends false ? never : undefined)
/** Only when "metafile: true" */
metafile: Metafile | (ProvidedOptions['metafile'] extends true ? never : undefined)
/** Only when "mangleCache" is present */
mangleCache: Record<string, string | false> | (ProvidedOptions['mangleCache'] extends Object ? never : undefined)
}
export interface BuildFailure extends Error {
errors: Message[]
warnings: Message[]
}
/** Documentation: https://esbuild.github.io/api/#serve-arguments */
export interface ServeOptions {
port?: number
host?: string
servedir?: string
keyfile?: string
certfile?: string
fallback?: string
onRequest?: (args: ServeOnRequestArgs) => void
}
export interface ServeOnRequestArgs {
remoteAddress: string
method: string
path: string
status: number
/** The time to generate the response, not to send it */
timeInMS: number
}
/** Documentation: https://esbuild.github.io/api/#serve-return-values */
export interface ServeResult {
port: number
host: string
}
export interface TransformOptions extends CommonOptions {
/** Documentation: https://esbuild.github.io/api/#sourcefile */
sourcefile?: string
/** Documentation: https://esbuild.github.io/api/#loader */
loader?: Loader
/** Documentation: https://esbuild.github.io/api/#banner */
banner?: string
/** Documentation: https://esbuild.github.io/api/#footer */
footer?: string
}
export interface TransformResult<ProvidedOptions extends TransformOptions = TransformOptions> {
code: string
map: string
warnings: Message[]
/** Only when "mangleCache" is present */
mangleCache: Record<string, string | false> | (ProvidedOptions['mangleCache'] extends Object ? never : undefined)
/** Only when "legalComments" is "external" */
legalComments: string | (ProvidedOptions['legalComments'] extends 'external' ? never : undefined)
}
export interface TransformFailure extends Error {
errors: Message[]
warnings: Message[]
}
export interface Plugin {
name: string
setup: (build: PluginBuild) => (void | Promise<void>)
}
export interface PluginBuild {
/** Documentation: https://esbuild.github.io/plugins/#build-options */
initialOptions: BuildOptions
/** Documentation: https://esbuild.github.io/plugins/#resolve */
resolve(path: string, options?: ResolveOptions): Promise<ResolveResult>
/** Documentation: https://esbuild.github.io/plugins/#on-start */
onStart(callback: () =>
(OnStartResult | null | void | Promise<OnStartResult | null | void>)): void
/** Documentation: https://esbuild.github.io/plugins/#on-end */
onEnd(callback: (result: BuildResult) =>
(OnEndResult | null | void | Promise<OnEndResult | null | void>)): void
/** Documentation: https://esbuild.github.io/plugins/#on-resolve */
onResolve(options: OnResolveOptions, callback: (args: OnResolveArgs) =>
(OnResolveResult | null | undefined | Promise<OnResolveResult | null | undefined>)): void
/** Documentation: https://esbuild.github.io/plugins/#on-load */
onLoad(options: OnLoadOptions, callback: (args: OnLoadArgs) =>
(OnLoadResult | null | undefined | Promise<OnLoadResult | null | undefined>)): void
/** Documentation: https://esbuild.github.io/plugins/#on-dispose */
onDispose(callback: () => void): void
// This is a full copy of the esbuild library in case you need it
esbuild: {
context: typeof context,
build: typeof build,
buildSync: typeof buildSync,
transform: typeof transform,
transformSync: typeof transformSync,
formatMessages: typeof formatMessages,
formatMessagesSync: typeof formatMessagesSync,
analyzeMetafile: typeof analyzeMetafile,
analyzeMetafileSync: typeof analyzeMetafileSync,
initialize: typeof initialize,
version: typeof version,
}
}
/** Documentation: https://esbuild.github.io/plugins/#resolve-options */
export interface ResolveOptions {
pluginName?: string
importer?: string
namespace?: string
resolveDir?: string
kind?: ImportKind
pluginData?: any
}
/** Documentation: https://esbuild.github.io/plugins/#resolve-results */
export interface ResolveResult {
errors: Message[]
warnings: Message[]
path: string
external: boolean
sideEffects: boolean
namespace: string
suffix: string
pluginData: any
}
export interface OnStartResult {
errors?: PartialMessage[]
warnings?: PartialMessage[]
}
export interface OnEndResult {
errors?: PartialMessage[]
warnings?: PartialMessage[]
}
/** Documentation: https://esbuild.github.io/plugins/#on-resolve-options */
export interface OnResolveOptions {
filter: RegExp
namespace?: string
}
/** Documentation: https://esbuild.github.io/plugins/#on-resolve-arguments */
export interface OnResolveArgs {
path: string
importer: string
namespace: string
resolveDir: string
kind: ImportKind
pluginData: any
}
export type ImportKind =
| 'entry-point'
// JS
| 'import-statement'
| 'require-call'
| 'dynamic-import'
| 'require-resolve'
// CSS
| 'import-rule'
| 'composes-from'
| 'url-token'
/** Documentation: https://esbuild.github.io/plugins/#on-resolve-results */
export interface OnResolveResult {
pluginName?: string
errors?: PartialMessage[]
warnings?: PartialMessage[]
path?: string
external?: boolean
sideEffects?: boolean
namespace?: string
suffix?: string
pluginData?: any
watchFiles?: string[]
watchDirs?: string[]
}
/** Documentation: https://esbuild.github.io/plugins/#on-load-options */
export interface OnLoadOptions {
filter: RegExp
namespace?: string
}
/** Documentation: https://esbuild.github.io/plugins/#on-load-arguments */
export interface OnLoadArgs {
path: string
namespace: string
suffix: string
pluginData: any
}
/** Documentation: https://esbuild.github.io/plugins/#on-load-results */
export interface OnLoadResult {
pluginName?: string
errors?: PartialMessage[]
warnings?: PartialMessage[]
contents?: string | Uint8Array
resolveDir?: string
loader?: Loader
pluginData?: any
watchFiles?: string[]
watchDirs?: string[]
}
export interface PartialMessage {
id?: string
pluginName?: string
text?: string
location?: Partial<Location> | null
notes?: PartialNote[]
detail?: any
}
export interface PartialNote {
text?: string
location?: Partial<Location> | null
}
/** Documentation: https://esbuild.github.io/api/#metafile */
export interface Metafile {
inputs: {
[path: string]: {
bytes: number
imports: {
path: string
kind: ImportKind
external?: boolean
original?: string
}[]
format?: 'cjs' | 'esm'
}
}
outputs: {
[path: string]: {
bytes: number
inputs: {
[path: string]: {
bytesInOutput: number
}
}
imports: {
path: string
kind: ImportKind | 'file-loader'
external?: boolean
}[]
exports: string[]
entryPoint?: string
cssBundle?: string
}
}
}
export interface FormatMessagesOptions {
kind: 'error' | 'warning'
color?: boolean
terminalWidth?: number
}
export interface AnalyzeMetafileOptions {
color?: boolean
verbose?: boolean
}
export interface WatchOptions {
}
export interface BuildContext<ProvidedOptions extends BuildOptions = BuildOptions> {
/** Documentation: https://esbuild.github.io/api/#rebuild */
rebuild(): Promise<BuildResult<ProvidedOptions>>
/** Documentation: https://esbuild.github.io/api/#watch */
watch(options?: WatchOptions): Promise<void>
/** Documentation: https://esbuild.github.io/api/#serve */
serve(options?: ServeOptions): Promise<ServeResult>
cancel(): Promise<void>
dispose(): Promise<void>
}
// This is a TypeScript type-level function which replaces any keys in "In"
// that aren't in "Out" with "never". We use this to reject properties with
// typos in object literals. See: https://stackoverflow.com/questions/49580725
type SameShape<Out, In extends Out> = In & { [Key in Exclude<keyof In, keyof Out>]: never }
/**
* This function invokes the "esbuild" command-line tool for you. It returns a
* promise that either resolves with a "BuildResult" object or rejects with a
* "BuildFailure" object.
*
* - Works in node: yes
* - Works in browser: yes
*
* Documentation: https://esbuild.github.io/api/#build
*/
export declare function build<T extends BuildOptions>(options: SameShape<BuildOptions, T>): Promise<BuildResult<T>>
/**
* This is the advanced long-running form of "build" that supports additional
* features such as watch mode and a local development server.
*
* - Works in node: yes
* - Works in browser: no
*
* Documentation: https://esbuild.github.io/api/#build
*/
export declare function context<T extends BuildOptions>(options: SameShape<BuildOptions, T>): Promise<BuildContext<T>>
/**
* This function transforms a single JavaScript file. It can be used to minify
* JavaScript, convert TypeScript/JSX to JavaScript, or convert newer JavaScript
* to older JavaScript. It returns a promise that is either resolved with a
* "TransformResult" object or rejected with a "TransformFailure" object.
*
* - Works in node: yes
* - Works in browser: yes
*
* Documentation: https://esbuild.github.io/api/#transform
*/
export declare function transform<T extends TransformOptions>(input: string | Uint8Array, options?: SameShape<TransformOptions, T>): Promise<TransformResult<T>>
/**
* Converts log messages to formatted message strings suitable for printing in
* the terminal. This allows you to reuse the built-in behavior of esbuild's
* log message formatter. This is a batch-oriented API for efficiency.
*
* - Works in node: yes
* - Works in browser: yes
*/
export declare function formatMessages(messages: PartialMessage[], options: FormatMessagesOptions): Promise<string[]>
/**
* Pretty-prints an analysis of the metafile JSON to a string. This is just for
* convenience to be able to match esbuild's pretty-printing exactly. If you want
* to customize it, you can just inspect the data in the metafile yourself.
*
* - Works in node: yes
* - Works in browser: yes
*
* Documentation: https://esbuild.github.io/api/#analyze
*/
export declare function analyzeMetafile(metafile: Metafile | string, options?: AnalyzeMetafileOptions): Promise<string>
/**
* A synchronous version of "build".
*
* - Works in node: yes
* - Works in browser: no
*
* Documentation: https://esbuild.github.io/api/#build
*/
export declare function buildSync<T extends BuildOptions>(options: SameShape<BuildOptions, T>): BuildResult<T>
/**
* A synchronous version of "transform".
*
* - Works in node: yes
* - Works in browser: no
*
* Documentation: https://esbuild.github.io/api/#transform
*/
export declare function transformSync<T extends TransformOptions>(input: string | Uint8Array, options?: SameShape<TransformOptions, T>): TransformResult<T>
/**
* A synchronous version of "formatMessages".
*
* - Works in node: yes
* - Works in browser: no
*/
export declare function formatMessagesSync(messages: PartialMessage[], options: FormatMessagesOptions): string[]
/**
* A synchronous version of "analyzeMetafile".
*
* - Works in node: yes
* - Works in browser: no
*
* Documentation: https://esbuild.github.io/api/#analyze
*/
export declare function analyzeMetafileSync(metafile: Metafile | string, options?: AnalyzeMetafileOptions): string
/**
* This configures the browser-based version of esbuild. It is necessary to
* call this first and wait for the returned promise to be resolved before
* making other API calls when using esbuild in the browser.
*
* - Works in node: yes
* - Works in browser: yes ("options" is required)
*
* Documentation: https://esbuild.github.io/api/#browser
*/
export declare function initialize(options: InitializeOptions): Promise<void>
export interface InitializeOptions {
/**
* The URL of the "esbuild.wasm" file. This must be provided when running
* esbuild in the browser.
*/
wasmURL?: string | URL
/**
* The result of calling "new WebAssembly.Module(buffer)" where "buffer"
* is a typed array or ArrayBuffer containing the binary code of the
* "esbuild.wasm" file.
*
* You can use this as an alternative to "wasmURL" for environments where it's
* not possible to download the WebAssembly module.
*/
wasmModule?: WebAssembly.Module
/**
* By default esbuild runs the WebAssembly-based browser API in a web worker
* to avoid blocking the UI thread. This can be disabled by setting "worker"
* to false.
*/
worker?: boolean
}
export let version: string
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,3 @@
# esbuild
This is the Linux 64-bit binary for esbuild, a JavaScript bundler and minifier. See https://github.com/evanw/esbuild for details.
@@ -0,0 +1,17 @@
{
"name": "@esbuild/linux-x64",
"version": "0.18.20",
"description": "The Linux 64-bit binary for esbuild, a JavaScript bundler.",
"repository": "https://github.com/evanw/esbuild",
"license": "MIT",
"preferUnplugged": true,
"engines": {
"node": ">=12"
},
"os": [
"linux"
],
"cpu": [
"x64"
]
}
@@ -0,0 +1,42 @@
{
"name": "esbuild",
"version": "0.18.20",
"description": "An extremely fast JavaScript and CSS bundler and minifier.",
"repository": "https://github.com/evanw/esbuild",
"scripts": {
"postinstall": "node install.js"
},
"main": "lib/main.js",
"types": "lib/main.d.ts",
"engines": {
"node": ">=12"
},
"bin": {
"esbuild": "bin/esbuild"
},
"optionalDependencies": {
"@esbuild/android-arm": "0.18.20",
"@esbuild/android-arm64": "0.18.20",
"@esbuild/android-x64": "0.18.20",
"@esbuild/darwin-arm64": "0.18.20",
"@esbuild/darwin-x64": "0.18.20",
"@esbuild/freebsd-arm64": "0.18.20",
"@esbuild/freebsd-x64": "0.18.20",
"@esbuild/linux-arm": "0.18.20",
"@esbuild/linux-arm64": "0.18.20",
"@esbuild/linux-ia32": "0.18.20",
"@esbuild/linux-loong64": "0.18.20",
"@esbuild/linux-mips64el": "0.18.20",
"@esbuild/linux-ppc64": "0.18.20",
"@esbuild/linux-riscv64": "0.18.20",
"@esbuild/linux-s390x": "0.18.20",
"@esbuild/linux-x64": "0.18.20",
"@esbuild/netbsd-x64": "0.18.20",
"@esbuild/openbsd-x64": "0.18.20",
"@esbuild/sunos-x64": "0.18.20",
"@esbuild/win32-arm64": "0.18.20",
"@esbuild/win32-ia32": "0.18.20",
"@esbuild/win32-x64": "0.18.20"
},
"license": "MIT"
}
+33
View File
@@ -0,0 +1,33 @@
{
"name": "@esbuild-kit/core-utils",
"version": "3.3.2",
"publishConfig": {
"access": "public"
},
"license": "MIT",
"repository": "esbuild-kit/core-utils",
"author": {
"name": "Hiroki Osame",
"email": "hiroki.osame@gmail.com"
},
"files": [
"dist"
],
"main": "./dist/index.js",
"types": "./dist/index.d.ts",
"exports": {
"types": "./dist/index.d.ts",
"default": "./dist/index.js"
},
"imports": {
"#esbuild-kit/core-utils": {
"types": "./src/index.ts",
"development": "./src/index.ts",
"default": "./dist/index.js"
}
},
"dependencies": {
"esbuild": "~0.18.20",
"source-map-support": "^0.5.21"
}
}
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) Hiroki Osame <hiroki.osame@gmail.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.
+155
View File
@@ -0,0 +1,155 @@
# esm-loader
[Node.js loader](https://nodejs.org/api/esm.html#loaders) for loading TypeScript files.
### Features
- Transforms TypeScript to ESM on demand
- Classic Node.js resolution (extensionless & directory imports)
- Cached for performance boost
- Supports Node.js v12.20.0+
- Handles `node:` import prefixes
- Resolves `tsconfig.json` [`paths`](https://www.typescriptlang.org/tsconfig#paths)
- Named imports from JSON modules
> **Protip: use with _cjs-loader_ or _tsx_**
>
> _esm-loader_ only transforms ES modules (`.mjs`/`.mts` extensions or `.js` files in `module` type packages).
>
> To transform CommonJS files (`.cjs`/`.cts` extensions or `.js` files in `commonjs` type packages), use this with [_cjs-loader_](https://github.com/esbuild-kit/cjs-loader).
>
> Alternatively, use [tsx](https://github.com/esbuild-kit/tsx) to handle them both automatically.
<br>
<p align="center">
<a href="https://privatenumber-sponsors.vercel.app/api/sponsor?tier=platinum">
<picture>
<source width="830" media="(prefers-color-scheme: dark)" srcset="https://privatenumber-sponsors.vercel.app/api/sponsor?tier=platinum&image=dark">
<source width="830" media="(prefers-color-scheme: light)" srcset="https://privatenumber-sponsors.vercel.app/api/sponsor?tier=platinum&image">
<img width="830" src="https://privatenumber-sponsors.vercel.app/api/sponsor?tier=platinum&image" alt="Premium sponsor banner">
</picture>
</a>
</p>
## Install
```sh
npm install --save-dev @esbuild-kit/esm-loader
```
## Usage
Pass `@esbuild-kit/esm-loader` into the [`--loader`](https://nodejs.org/api/cli.html#--experimental-loadermodule) flag.
```sh
node --loader @esbuild-kit/esm-loader ./file.ts
```
### TypeScript configuration
The following properties are used from `tsconfig.json` in the working directory:
- [`strict`](https://www.typescriptlang.org/tsconfig#strict): Whether to transform to strict mode
- [`jsx`](https://esbuild.github.io/api/#jsx): Whether to transform JSX
> **Warning:** When set to `preserve`, the JSX syntax will remain untransformed. To prevent Node.js from throwing a syntax error, chain another Node.js loader that can transform JSX to JS.
- [`jsxFactory`](https://esbuild.github.io/api/#jsx-factory): How to transform JSX
- [`jsxFragmentFactory`](https://esbuild.github.io/api/#jsx-fragment): How to transform JSX Fragments
- [`jsxImportSource`](https://www.typescriptlang.org/tsconfig#jsxImportSource): Where to import JSX functions from
- [`allowJs`](https://www.typescriptlang.org/tsconfig#allowJs): Whether to apply the tsconfig to JS files
- [`paths`](https://www.typescriptlang.org/tsconfig#paths): For resolving aliases
#### Custom `tsconfig.json` path
By default, `tsconfig.json` will be detected from the current working directory.
To set a custom path, use the `ESBK_TSCONFIG_PATH` environment variable:
```sh
ESBK_TSCONFIG_PATH=./path/to/tsconfig.custom.json node --loader @esbuild-kit/esm-loader ./file.ts
```
### Cache
Modules transformations are cached in the system cache directory ([`TMPDIR`](https://en.wikipedia.org/wiki/TMPDIR)). Transforms are cached by content hash so duplicate dependencies are not re-transformed.
Set environment variable `ESBK_DISABLE_CACHE` to a truthy value to disable the cache:
```sh
ESBK_DISABLE_CACHE=1 node --loader @esbuild-kit/esm-loader ./file.ts
```
<br>
<p align="center">
<a href="https://privatenumber-sponsors.vercel.app/api/sponsor?tier=gold">
<picture>
<source width="830" media="(prefers-color-scheme: dark)" srcset="https://privatenumber-sponsors.vercel.app/api/sponsor?tier=gold&image=dark">
<source width="830" media="(prefers-color-scheme: light)" srcset="https://privatenumber-sponsors.vercel.app/api/sponsor?tier=gold&image">
<img width="830" src="https://privatenumber-sponsors.vercel.app/api/sponsor?tier=gold&image" alt="Premium sponsor banner">
</picture>
</a>
</p>
## FAQ
### Can it import JSON modules?
Yes. This loader transpiles JSON modules so it's also compatible with named imports.
### Can it import ESM modules over network?
Node.js has built-in support for network imports [behind the `--experimental-network-imports` flag](https://nodejs.org/api/esm.html#network-based-loading-is-not-enabled-by-default).
You can pass it in with `esm-loader`:
```sh
node --loader @esbuild-kit/esm-loader --experimental-network-imports ./file.ts
```
### Can it resolve files without an extension?
In ESM, import paths must be explicit (must include file name and extension).
For backwards compatibility, this loader adds support for classic Node resolution for extensions: `.js`, `.json`, `.ts`, `.tsx`, `.jsx`. Resolving a `index` file by the directory name works too.
```js
import file from './file' // -> ./file.js
import directory from './directory' // -> ./directory/index.js
```
### Can it use Node.js's CommonJS resolution algorithm?
ESM import resolution expects explicit import paths, whereas CommonJS resolution expects implicit imports (eg. extensionless & directory imports).
As a result of this change, Node.js changes how it imports a path that matches both a file and directory. In ESM, the directory would be imported, but in CJS, the file would be imported.
To use to the CommonJS resolution algorithm, use the [`--experimental-specifier-resolution=node`](https://nodejs.org/api/cli.html#--experimental-specifier-resolutionmode) flag.
```sh
node --loader @esbuild-kit/esm-loader --experimental-specifier-resolution=node ./file.ts
```
## Related
- [tsx](https://github.com/esbuild-kit/tsx) - Node.js runtime powered by esbuild using [`@esbuild-kit/cjs-loader`](https://github.com/esbuild-kit/cjs-loader) and [`@esbuild-kit/esm-loader`](https://github.com/esbuild-kit/esm-loader).
- [@esbuild-kit/cjs-loader](https://github.com/esbuild-kit/cjs-loader) - TypeScript & ESM to CJS transpiler using the Node.js loader API.
## Sponsors
<p align="center">
<a href="https://privatenumber-sponsors.vercel.app/api/sponsor?tier=silver1">
<picture>
<source width="410" media="(prefers-color-scheme: dark)" srcset="https://privatenumber-sponsors.vercel.app/api/sponsor?tier=silver1&image=dark">
<source width="410" media="(prefers-color-scheme: light)" srcset="https://privatenumber-sponsors.vercel.app/api/sponsor?tier=silver1&image">
<img width="410" src="https://privatenumber-sponsors.vercel.app/api/sponsor?tier=silver1&image" alt="Premium sponsor banner">
</picture>
</a>
<a href="https://privatenumber-sponsors.vercel.app/api/sponsor?tier=silver2">
<picture>
<source width="410" media="(prefers-color-scheme: dark)" srcset="https://privatenumber-sponsors.vercel.app/api/sponsor?tier=silver2&image=dark">
<source width="410" media="(prefers-color-scheme: light)" srcset="https://privatenumber-sponsors.vercel.app/api/sponsor?tier=silver2&image">
<img width="410" src="https://privatenumber-sponsors.vercel.app/api/sponsor?tier=silver2&image" alt="Premium sponsor banner">
</picture>
</a>
</p>
<p align="center">
<a href="https://github.com/sponsors/privatenumber">
<img src="https://cdn.jsdelivr.net/gh/privatenumber/sponsors/sponsorkit/sponsors.svg">
</a>
</p>
+12
View File
@@ -0,0 +1,12 @@
import l from"path";import{fileURLToPath as y,pathToFileURL as U}from"url";import{installSourceMapSupport as I,compareNodeVersion as m,resolveTsPath as M,transform as S,transformDynamicImport as k}from"@esbuild-kit/core-utils";import{parseTsconfig as A,getTsconfig as J,createFilesMatcher as L,createPathsMatcher as W}from"get-tsconfig";import R from"fs";const f=new Map;async function b(t){if(f.has(t))return f.get(t);if(!await R.promises.access(t).then(()=>!0,()=>!1)){f.set(t,void 0);return}const e=await R.promises.readFile(t,"utf8");try{const n=JSON.parse(e);return f.set(t,n),n}catch{throw new Error(`Error parsing: ${t}`)}}async function $(t){let s=new URL("package.json",t);for(;!s.pathname.endsWith("/node_modules/package.json");){const e=y(s),n=await b(e);if(n)return n;const r=s;if(s=new URL("../package.json",s),s.pathname===r.pathname)break}}async function x(t){var s;const e=await $(t);return(s=e==null?void 0:e.type)!=null?s:"commonjs"}const u=I(),d=process.env.ESBK_TSCONFIG_PATH?{path:l.resolve(process.env.ESBK_TSCONFIG_PATH),config:A(process.env.ESBK_TSCONFIG_PATH)}:J(),N=d&&L(d),O=d&&W(d),w="file://",g=/\.([cm]?ts|[tj]sx)($|\?)/,_=/\.json(?:$|\?)/,C=t=>{const s=l.extname(t);if(s===".json")return"json";if(s===".mjs"||s===".mts")return"module";if(s===".cjs"||s===".cts")return"commonjs"},j=t=>{const s=C(t);if(s)return s;if(g.test(t))return x(t)},v=/\/(?:$|\?)/,K=m([20,0,0])>=0;let P=process.send?process.send.bind(process):void 0,E;const q=({port:t})=>(E=t,P=t.postMessage.bind(t),`
const require = getBuiltin('module').createRequire("${import.meta.url}");
require('@esbuild-kit/core-utils').installSourceMapSupport(port);
if (process.send) {
port.addListener('message', (message) => {
if (message.type === 'dependency') {
process.send(message);
}
});
}
port.unref(); // Allows process to exit without waiting for port to close
`),B=K?q:void 0,G=[".js",".json",".ts",".tsx",".jsx"];async function T(t,s,e){const[n,r]=t.split("?");let i;for(const a of G)try{return await h(n+a+(r?`?${r}`:""),s,e,!0)}catch(o){if(i===void 0&&o instanceof Error){const{message:c}=o;o.message=o.message.replace(`${a}'`,"'"),o.stack=o.stack.replace(c,o.message),i=o}}throw i}async function F(t,s,e){const n=v.test(t),r=n?"index":"/index",[i,a]=t.split("?");try{return await T(i+r+(a?`?${a}`:""),s,e)}catch(o){if(!n)try{return await T(t,s,e)}catch{}const c=o,{message:p}=c;throw c.message=c.message.replace(`${r.replace("/",l.sep)}'`,"'"),c.stack=c.stack.replace(p,c.message),c}}const H=/^\.{1,2}\//,Q=m([14,13,1])>=0||m([12,20,0])>=0,h=async function(t,s,e,n){var r;if(!Q&&t.startsWith("node:")&&(t=t.slice(5)),v.test(t))return await F(t,s,e);const i=t.startsWith(w)||H.test(t);if(O&&!i&&!((r=s.parentURL)!=null&&r.includes("/node_modules/"))){const o=O(t);for(const c of o)try{return await h(U(c).toString(),s,e)}catch{}}if(g.test(s.parentURL)){const o=M(t);if(o)try{return await h(o,s,e,!0)}catch(c){const{code:p}=c;if(p!=="ERR_MODULE_NOT_FOUND"&&p!=="ERR_PACKAGE_PATH_NOT_EXPORTED")throw c}}let a;try{a=await e(t,s)}catch(o){if(o instanceof Error&&!n){const{code:c}=o;if(c==="ERR_UNSUPPORTED_DIR_IMPORT")try{return await F(t,s,e)}catch(p){if(p.code!=="ERR_PACKAGE_IMPORT_NOT_DEFINED")throw p}if(c==="ERR_MODULE_NOT_FOUND")try{return await T(t,s,e)}catch{}}throw o}return!a.format&&a.url.startsWith(w)&&(a.format=await j(a.url)),a},X=async function(t,s,e){var n;P&&P({type:"dependency",path:t}),_.test(t)&&(s.importAssertions||(s.importAssertions={}),s.importAssertions.type="json");const r=await e(t,s);if(!r.source)return r;const i=t.startsWith("file://")?y(t):t,a=r.source.toString();if(r.format==="json"||g.test(t)){const o=await S(a,i,{tsconfigRaw:(n=N)==null?void 0:n(i)});return{format:"module",source:u(o,t,E)}}if(r.format==="module"){const o=k(i,a);o&&(r.source=u(o,t,E))}return r},V=async function(t,s,e){if(_.test(t))return{format:"module"};try{return await e(t,s,e)}catch(n){if(n.code==="ERR_UNKNOWN_FILE_EXTENSION"&&t.startsWith(w)){const r=await j(t);if(r)return{format:r}}throw n}},z=async function(t,s,e){var n;const{url:r}=s,i=r.startsWith("file://")?y(r):r;if(process.send&&process.send({type:"dependency",path:r}),_.test(r)||g.test(r)){const o=await S(t.toString(),i,{tsconfigRaw:(n=N)==null?void 0:n(i)});return{source:u(o,r)}}const a=await e(t,s,e);if(s.format==="module"){const o=k(i,a.source.toString());o&&(a.source=u(o,r))}return a},D=m([16,12,0])<0,Y=D?V:void 0,Z=D?z:void 0;export{Y as getFormat,B as globalPreload,X as load,h as resolve,Z as transformSource};
+31
View File
@@ -0,0 +1,31 @@
{
"name": "@esbuild-kit/esm-loader",
"version": "2.6.5",
"publishConfig": {
"access": "public"
},
"description": "Node.js loader for compiling TypeScript modules to ESM",
"keywords": [
"esbuild",
"loader",
"node",
"esm",
"typescript"
],
"license": "MIT",
"repository": "esbuild-kit/esm-loader",
"author": {
"name": "Hiroki Osame",
"email": "hiroki.osame@gmail.com"
},
"type": "module",
"files": [
"dist"
],
"main": "./dist/index.js",
"exports": "./dist/index.js",
"dependencies": {
"@esbuild-kit/core-utils": "^3.3.2",
"get-tsconfig": "^4.7.0"
}
}
+3
View File
@@ -0,0 +1,3 @@
# esbuild
This is the Linux 64-bit binary for esbuild, a JavaScript bundler and minifier. See https://github.com/evanw/esbuild for details.
BIN
View File
Binary file not shown.
+20
View File
@@ -0,0 +1,20 @@
{
"name": "@esbuild/linux-x64",
"version": "0.25.12",
"description": "The Linux 64-bit binary for esbuild, a JavaScript bundler.",
"repository": {
"type": "git",
"url": "git+https://github.com/evanw/esbuild.git"
},
"license": "MIT",
"preferUnplugged": true,
"engines": {
"node": ">=18"
},
"os": [
"linux"
],
"cpu": [
"x64"
]
}
@@ -0,0 +1,55 @@
import { ValueErrorIterator } from '../errors/index';
import { TypeBoxError } from '../type/error/index';
import type { TSchema } from '../type/schema/index';
import type { Static, StaticDecode, StaticEncode } from '../type/static/index';
export type CheckFunction = (value: unknown) => boolean;
export declare class TypeCheck<T extends TSchema> {
private readonly schema;
private readonly references;
private readonly checkFunc;
private readonly code;
private readonly hasTransform;
constructor(schema: T, references: TSchema[], checkFunc: CheckFunction, code: string);
/** Returns the generated assertion code used to validate this type. */
Code(): string;
/** Returns the schema type used to validate */
Schema(): T;
/** Returns reference types used to validate */
References(): TSchema[];
/** Returns an iterator for each error in this value. */
Errors(value: unknown): ValueErrorIterator;
/** Returns true if the value matches the compiled type. */
Check(value: unknown): value is Static<T>;
/** Decodes a value or throws if error */
Decode<Static = StaticDecode<T>, Result extends Static = Static>(value: unknown): Result;
/** Encodes a value or throws if error */
Encode<Static = StaticEncode<T>, Result extends Static = Static>(value: unknown): Result;
}
export declare class TypeCompilerUnknownTypeError extends TypeBoxError {
readonly schema: TSchema;
constructor(schema: TSchema);
}
export declare class TypeCompilerTypeGuardError extends TypeBoxError {
readonly schema: TSchema;
constructor(schema: TSchema);
}
export declare namespace Policy {
function IsExactOptionalProperty(value: string, key: string, expression: string): string;
function IsObjectLike(value: string): string;
function IsRecordLike(value: string): string;
function IsNumberLike(value: string): string;
function IsVoidLike(value: string): string;
}
export type TypeCompilerLanguageOption = 'typescript' | 'javascript';
export interface TypeCompilerCodegenOptions {
language?: TypeCompilerLanguageOption;
}
/** Compiles Types for Runtime Type Checking */
export declare namespace TypeCompiler {
/** Generates the code used to assert this type and returns it as a string */
function Code<T extends TSchema>(schema: T, references: TSchema[], options?: TypeCompilerCodegenOptions): string;
/** Generates the code used to assert this type and returns it as a string */
function Code<T extends TSchema>(schema: T, options?: TypeCompilerCodegenOptions): string;
/** Compiles a TypeBox type for optimal runtime type checking. Types must be valid TypeBox types of TSchema */
function Compile<T extends TSchema>(schema: T, references?: TSchema[]): TypeCheck<T>;
}
@@ -0,0 +1,670 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.TypeCompiler = exports.Policy = exports.TypeCompilerTypeGuardError = exports.TypeCompilerUnknownTypeError = exports.TypeCheck = void 0;
const index_1 = require("../value/transform/index");
const index_2 = require("../errors/index");
const index_3 = require("../system/index");
const index_4 = require("../type/error/index");
const index_5 = require("../value/deref/index");
const index_6 = require("../value/hash/index");
const index_7 = require("../type/symbols/index");
const index_8 = require("../type/registry/index");
const index_9 = require("../type/keyof/index");
const extends_undefined_1 = require("../type/extends/extends-undefined");
const index_10 = require("../type/never/index");
const index_11 = require("../type/ref/index");
// ------------------------------------------------------------------
// ValueGuard
// ------------------------------------------------------------------
const index_12 = require("../value/guard/index");
// ------------------------------------------------------------------
// TypeGuard
// ------------------------------------------------------------------
const type_1 = require("../type/guard/type");
// ------------------------------------------------------------------
// TypeCheck
// ------------------------------------------------------------------
class TypeCheck {
constructor(schema, references, checkFunc, code) {
this.schema = schema;
this.references = references;
this.checkFunc = checkFunc;
this.code = code;
this.hasTransform = (0, index_1.HasTransform)(schema, references);
}
/** Returns the generated assertion code used to validate this type. */
Code() {
return this.code;
}
/** Returns the schema type used to validate */
Schema() {
return this.schema;
}
/** Returns reference types used to validate */
References() {
return this.references;
}
/** Returns an iterator for each error in this value. */
Errors(value) {
return (0, index_2.Errors)(this.schema, this.references, value);
}
/** Returns true if the value matches the compiled type. */
Check(value) {
return this.checkFunc(value);
}
/** Decodes a value or throws if error */
Decode(value) {
if (!this.checkFunc(value))
throw new index_1.TransformDecodeCheckError(this.schema, value, this.Errors(value).First());
return (this.hasTransform ? (0, index_1.TransformDecode)(this.schema, this.references, value) : value);
}
/** Encodes a value or throws if error */
Encode(value) {
const encoded = this.hasTransform ? (0, index_1.TransformEncode)(this.schema, this.references, value) : value;
if (!this.checkFunc(encoded))
throw new index_1.TransformEncodeCheckError(this.schema, value, this.Errors(value).First());
return encoded;
}
}
exports.TypeCheck = TypeCheck;
// ------------------------------------------------------------------
// Character
// ------------------------------------------------------------------
var Character;
(function (Character) {
function DollarSign(code) {
return code === 36;
}
Character.DollarSign = DollarSign;
function IsUnderscore(code) {
return code === 95;
}
Character.IsUnderscore = IsUnderscore;
function IsAlpha(code) {
return (code >= 65 && code <= 90) || (code >= 97 && code <= 122);
}
Character.IsAlpha = IsAlpha;
function IsNumeric(code) {
return code >= 48 && code <= 57;
}
Character.IsNumeric = IsNumeric;
})(Character || (Character = {}));
// ------------------------------------------------------------------
// MemberExpression
// ------------------------------------------------------------------
var MemberExpression;
(function (MemberExpression) {
function IsFirstCharacterNumeric(value) {
if (value.length === 0)
return false;
return Character.IsNumeric(value.charCodeAt(0));
}
function IsAccessor(value) {
if (IsFirstCharacterNumeric(value))
return false;
for (let i = 0; i < value.length; i++) {
const code = value.charCodeAt(i);
const check = Character.IsAlpha(code) || Character.IsNumeric(code) || Character.DollarSign(code) || Character.IsUnderscore(code);
if (!check)
return false;
}
return true;
}
function EscapeHyphen(key) {
return key.replace(/'/g, "\\'");
}
function Encode(object, key) {
return IsAccessor(key) ? `${object}.${key}` : `${object}['${EscapeHyphen(key)}']`;
}
MemberExpression.Encode = Encode;
})(MemberExpression || (MemberExpression = {}));
// ------------------------------------------------------------------
// Identifier
// ------------------------------------------------------------------
var Identifier;
(function (Identifier) {
function Encode($id) {
const buffer = [];
for (let i = 0; i < $id.length; i++) {
const code = $id.charCodeAt(i);
if (Character.IsNumeric(code) || Character.IsAlpha(code)) {
buffer.push($id.charAt(i));
}
else {
buffer.push(`_${code}_`);
}
}
return buffer.join('').replace(/__/g, '_');
}
Identifier.Encode = Encode;
})(Identifier || (Identifier = {}));
// ------------------------------------------------------------------
// LiteralString
// ------------------------------------------------------------------
var LiteralString;
(function (LiteralString) {
function Escape(content) {
return content.replace(/'/g, "\\'");
}
LiteralString.Escape = Escape;
})(LiteralString || (LiteralString = {}));
// ------------------------------------------------------------------
// Errors
// ------------------------------------------------------------------
class TypeCompilerUnknownTypeError extends index_4.TypeBoxError {
constructor(schema) {
super('Unknown type');
this.schema = schema;
}
}
exports.TypeCompilerUnknownTypeError = TypeCompilerUnknownTypeError;
class TypeCompilerTypeGuardError extends index_4.TypeBoxError {
constructor(schema) {
super('Preflight validation check failed to guard for the given schema');
this.schema = schema;
}
}
exports.TypeCompilerTypeGuardError = TypeCompilerTypeGuardError;
// ------------------------------------------------------------------
// Policy
// ------------------------------------------------------------------
var Policy;
(function (Policy) {
function IsExactOptionalProperty(value, key, expression) {
return index_3.TypeSystemPolicy.ExactOptionalPropertyTypes ? `('${key}' in ${value} ? ${expression} : true)` : `(${MemberExpression.Encode(value, key)} !== undefined ? ${expression} : true)`;
}
Policy.IsExactOptionalProperty = IsExactOptionalProperty;
function IsObjectLike(value) {
return !index_3.TypeSystemPolicy.AllowArrayObject ? `(typeof ${value} === 'object' && ${value} !== null && !Array.isArray(${value}))` : `(typeof ${value} === 'object' && ${value} !== null)`;
}
Policy.IsObjectLike = IsObjectLike;
function IsRecordLike(value) {
return !index_3.TypeSystemPolicy.AllowArrayObject
? `(typeof ${value} === 'object' && ${value} !== null && !Array.isArray(${value}) && !(${value} instanceof Date) && !(${value} instanceof Uint8Array))`
: `(typeof ${value} === 'object' && ${value} !== null && !(${value} instanceof Date) && !(${value} instanceof Uint8Array))`;
}
Policy.IsRecordLike = IsRecordLike;
function IsNumberLike(value) {
return index_3.TypeSystemPolicy.AllowNaN ? `typeof ${value} === 'number'` : `Number.isFinite(${value})`;
}
Policy.IsNumberLike = IsNumberLike;
function IsVoidLike(value) {
return index_3.TypeSystemPolicy.AllowNullVoid ? `(${value} === undefined || ${value} === null)` : `${value} === undefined`;
}
Policy.IsVoidLike = IsVoidLike;
})(Policy || (exports.Policy = Policy = {}));
/** Compiles Types for Runtime Type Checking */
var TypeCompiler;
(function (TypeCompiler) {
// ----------------------------------------------------------------
// Guards
// ----------------------------------------------------------------
function IsAnyOrUnknown(schema) {
return schema[index_7.Kind] === 'Any' || schema[index_7.Kind] === 'Unknown';
}
// ----------------------------------------------------------------
// Types
// ----------------------------------------------------------------
function* FromAny(schema, references, value) {
yield 'true';
}
function* FromArgument(schema, references, value) {
yield 'true';
}
function* FromArray(schema, references, value) {
yield `Array.isArray(${value})`;
const [parameter, accumulator] = [CreateParameter('value', 'any'), CreateParameter('acc', 'number')];
if ((0, index_12.IsNumber)(schema.maxItems))
yield `${value}.length <= ${schema.maxItems}`;
if ((0, index_12.IsNumber)(schema.minItems))
yield `${value}.length >= ${schema.minItems}`;
const elementExpression = CreateExpression(schema.items, references, 'value');
// yield `${value}.every((${parameter}) => ${elementExpression})` // issue: 1519
yield `((array) => { for(const ${parameter} of array) if(!(${elementExpression})) { return false }; return true; })(${value})`;
if ((0, type_1.IsSchema)(schema.contains) || (0, index_12.IsNumber)(schema.minContains) || (0, index_12.IsNumber)(schema.maxContains)) {
const containsSchema = (0, type_1.IsSchema)(schema.contains) ? schema.contains : (0, index_10.Never)();
const checkExpression = CreateExpression(containsSchema, references, 'value');
const checkMinContains = (0, index_12.IsNumber)(schema.minContains) ? [`(count >= ${schema.minContains})`] : [];
const checkMaxContains = (0, index_12.IsNumber)(schema.maxContains) ? [`(count <= ${schema.maxContains})`] : [];
const checkCount = `const count = value.reduce((${accumulator}, ${parameter}) => ${checkExpression} ? acc + 1 : acc, 0)`;
const check = [`(count > 0)`, ...checkMinContains, ...checkMaxContains].join(' && ');
yield `((${parameter}) => { ${checkCount}; return ${check}})(${value})`;
}
if (schema.uniqueItems === true) {
const check = `const hashed = hash(element); if(set.has(hashed)) { return false } else { set.add(hashed) } } return true`;
const block = `const set = new Set(); for(const element of value) { ${check} }`;
yield `((${parameter}) => { ${block} )(${value})`;
}
}
function* FromAsyncIterator(schema, references, value) {
yield `(typeof value === 'object' && Symbol.asyncIterator in ${value})`;
}
function* FromBigInt(schema, references, value) {
yield `(typeof ${value} === 'bigint')`;
if ((0, index_12.IsBigInt)(schema.exclusiveMaximum))
yield `${value} < BigInt(${schema.exclusiveMaximum})`;
if ((0, index_12.IsBigInt)(schema.exclusiveMinimum))
yield `${value} > BigInt(${schema.exclusiveMinimum})`;
if ((0, index_12.IsBigInt)(schema.maximum))
yield `${value} <= BigInt(${schema.maximum})`;
if ((0, index_12.IsBigInt)(schema.minimum))
yield `${value} >= BigInt(${schema.minimum})`;
if ((0, index_12.IsBigInt)(schema.multipleOf))
yield `(${value} % BigInt(${schema.multipleOf})) === 0`;
}
function* FromBoolean(schema, references, value) {
yield `(typeof ${value} === 'boolean')`;
}
function* FromConstructor(schema, references, value) {
yield* Visit(schema.returns, references, `${value}.prototype`);
}
function* FromDate(schema, references, value) {
yield `(${value} instanceof Date) && Number.isFinite(${value}.getTime())`;
if ((0, index_12.IsNumber)(schema.exclusiveMaximumTimestamp))
yield `${value}.getTime() < ${schema.exclusiveMaximumTimestamp}`;
if ((0, index_12.IsNumber)(schema.exclusiveMinimumTimestamp))
yield `${value}.getTime() > ${schema.exclusiveMinimumTimestamp}`;
if ((0, index_12.IsNumber)(schema.maximumTimestamp))
yield `${value}.getTime() <= ${schema.maximumTimestamp}`;
if ((0, index_12.IsNumber)(schema.minimumTimestamp))
yield `${value}.getTime() >= ${schema.minimumTimestamp}`;
if ((0, index_12.IsNumber)(schema.multipleOfTimestamp))
yield `(${value}.getTime() % ${schema.multipleOfTimestamp}) === 0`;
}
function* FromFunction(schema, references, value) {
yield `(typeof ${value} === 'function')`;
}
function* FromImport(schema, references, value) {
const members = globalThis.Object.getOwnPropertyNames(schema.$defs).reduce((result, key) => {
return [...result, schema.$defs[key]];
}, []);
yield* Visit((0, index_11.Ref)(schema.$ref), [...references, ...members], value);
}
function* FromInteger(schema, references, value) {
yield `Number.isInteger(${value})`;
if ((0, index_12.IsNumber)(schema.exclusiveMaximum))
yield `${value} < ${schema.exclusiveMaximum}`;
if ((0, index_12.IsNumber)(schema.exclusiveMinimum))
yield `${value} > ${schema.exclusiveMinimum}`;
if ((0, index_12.IsNumber)(schema.maximum))
yield `${value} <= ${schema.maximum}`;
if ((0, index_12.IsNumber)(schema.minimum))
yield `${value} >= ${schema.minimum}`;
if ((0, index_12.IsNumber)(schema.multipleOf))
yield `(${value} % ${schema.multipleOf}) === 0`;
}
function* FromIntersect(schema, references, value) {
const check1 = schema.allOf.map((schema) => CreateExpression(schema, references, value)).join(' && ');
if (schema.unevaluatedProperties === false) {
const keyCheck = CreateVariable(`${new RegExp((0, index_9.KeyOfPattern)(schema))};`);
const check2 = `Object.getOwnPropertyNames(${value}).every(key => ${keyCheck}.test(key))`;
yield `(${check1} && ${check2})`;
}
else if ((0, type_1.IsSchema)(schema.unevaluatedProperties)) {
const keyCheck = CreateVariable(`${new RegExp((0, index_9.KeyOfPattern)(schema))};`);
const check2 = `Object.getOwnPropertyNames(${value}).every(key => ${keyCheck}.test(key) || ${CreateExpression(schema.unevaluatedProperties, references, `${value}[key]`)})`;
yield `(${check1} && ${check2})`;
}
else {
yield `(${check1})`;
}
}
function* FromIterator(schema, references, value) {
yield `(typeof value === 'object' && Symbol.iterator in ${value})`;
}
function* FromLiteral(schema, references, value) {
if (typeof schema.const === 'number' || typeof schema.const === 'boolean') {
yield `(${value} === ${schema.const})`;
}
else {
yield `(${value} === '${LiteralString.Escape(schema.const)}')`;
}
}
function* FromNever(schema, references, value) {
yield `false`;
}
function* FromNot(schema, references, value) {
const expression = CreateExpression(schema.not, references, value);
yield `(!${expression})`;
}
function* FromNull(schema, references, value) {
yield `(${value} === null)`;
}
function* FromNumber(schema, references, value) {
yield Policy.IsNumberLike(value);
if ((0, index_12.IsNumber)(schema.exclusiveMaximum))
yield `${value} < ${schema.exclusiveMaximum}`;
if ((0, index_12.IsNumber)(schema.exclusiveMinimum))
yield `${value} > ${schema.exclusiveMinimum}`;
if ((0, index_12.IsNumber)(schema.maximum))
yield `${value} <= ${schema.maximum}`;
if ((0, index_12.IsNumber)(schema.minimum))
yield `${value} >= ${schema.minimum}`;
if ((0, index_12.IsNumber)(schema.multipleOf))
yield `(${value} % ${schema.multipleOf}) === 0`;
}
function* FromObject(schema, references, value) {
yield Policy.IsObjectLike(value);
if ((0, index_12.IsNumber)(schema.minProperties))
yield `Object.getOwnPropertyNames(${value}).length >= ${schema.minProperties}`;
if ((0, index_12.IsNumber)(schema.maxProperties))
yield `Object.getOwnPropertyNames(${value}).length <= ${schema.maxProperties}`;
const knownKeys = Object.getOwnPropertyNames(schema.properties);
for (const knownKey of knownKeys) {
const memberExpression = MemberExpression.Encode(value, knownKey);
const property = schema.properties[knownKey];
if (schema.required && schema.required.includes(knownKey)) {
yield* Visit(property, references, memberExpression);
if ((0, extends_undefined_1.ExtendsUndefinedCheck)(property) || IsAnyOrUnknown(property))
yield `('${knownKey}' in ${value})`;
}
else {
const expression = CreateExpression(property, references, memberExpression);
yield Policy.IsExactOptionalProperty(value, knownKey, expression);
}
}
if (schema.additionalProperties === false) {
if (schema.required && schema.required.length === knownKeys.length) {
yield `Object.getOwnPropertyNames(${value}).length === ${knownKeys.length}`;
}
else {
const keys = `[${knownKeys.map((key) => `'${key}'`).join(', ')}]`;
yield `Object.getOwnPropertyNames(${value}).every(key => ${keys}.includes(key))`;
}
}
if (typeof schema.additionalProperties === 'object') {
const expression = CreateExpression(schema.additionalProperties, references, `${value}[key]`);
const keys = `[${knownKeys.map((key) => `'${key}'`).join(', ')}]`;
yield `(Object.getOwnPropertyNames(${value}).every(key => ${keys}.includes(key) || ${expression}))`;
}
}
function* FromPromise(schema, references, value) {
yield `${value} instanceof Promise`;
}
function* FromRecord(schema, references, value) {
yield Policy.IsRecordLike(value);
if ((0, index_12.IsNumber)(schema.minProperties))
yield `Object.getOwnPropertyNames(${value}).length >= ${schema.minProperties}`;
if ((0, index_12.IsNumber)(schema.maxProperties))
yield `Object.getOwnPropertyNames(${value}).length <= ${schema.maxProperties}`;
const [patternKey, patternSchema] = Object.entries(schema.patternProperties)[0];
const variable = CreateVariable(`${new RegExp(patternKey)}`);
const check1 = CreateExpression(patternSchema, references, 'value');
const check2 = (0, type_1.IsSchema)(schema.additionalProperties) ? CreateExpression(schema.additionalProperties, references, value) : schema.additionalProperties === false ? 'false' : 'true';
const expression = `(${variable}.test(key) ? ${check1} : ${check2})`;
yield `(Object.entries(${value}).every(([key, value]) => ${expression}))`;
}
function* FromRef(schema, references, value) {
const target = (0, index_5.Deref)(schema, references);
// Reference: If we have seen this reference before we can just yield and return the function call.
// If this isn't the case we defer to visit to generate and set the function for subsequent passes.
if (state.functions.has(schema.$ref))
return yield `${CreateFunctionName(schema.$ref)}(${value})`;
yield* Visit(target, references, value);
}
function* FromRegExp(schema, references, value) {
const variable = CreateVariable(`${new RegExp(schema.source, schema.flags)};`);
yield `(typeof ${value} === 'string')`;
if ((0, index_12.IsNumber)(schema.maxLength))
yield `${value}.length <= ${schema.maxLength}`;
if ((0, index_12.IsNumber)(schema.minLength))
yield `${value}.length >= ${schema.minLength}`;
yield `${variable}.test(${value})`;
}
function* FromString(schema, references, value) {
yield `(typeof ${value} === 'string')`;
if ((0, index_12.IsNumber)(schema.maxLength))
yield `${value}.length <= ${schema.maxLength}`;
if ((0, index_12.IsNumber)(schema.minLength))
yield `${value}.length >= ${schema.minLength}`;
if (schema.pattern !== undefined) {
const variable = CreateVariable(`${new RegExp(schema.pattern)};`);
yield `${variable}.test(${value})`;
}
if (schema.format !== undefined) {
yield `format('${schema.format}', ${value})`;
}
}
function* FromSymbol(schema, references, value) {
yield `(typeof ${value} === 'symbol')`;
}
function* FromTemplateLiteral(schema, references, value) {
yield `(typeof ${value} === 'string')`;
const variable = CreateVariable(`${new RegExp(schema.pattern)};`);
yield `${variable}.test(${value})`;
}
function* FromThis(schema, references, value) {
// Note: This types are assured to be hoisted prior to this call. Just yield the function.
yield `${CreateFunctionName(schema.$ref)}(${value})`;
}
function* FromTuple(schema, references, value) {
yield `Array.isArray(${value})`;
if (schema.items === undefined)
return yield `${value}.length === 0`;
yield `(${value}.length === ${schema.maxItems})`;
for (let i = 0; i < schema.items.length; i++) {
const expression = CreateExpression(schema.items[i], references, `${value}[${i}]`);
yield `${expression}`;
}
}
function* FromUndefined(schema, references, value) {
yield `${value} === undefined`;
}
function* FromUnion(schema, references, value) {
const expressions = schema.anyOf.map((schema) => CreateExpression(schema, references, value));
yield `(${expressions.join(' || ')})`;
}
function* FromUint8Array(schema, references, value) {
yield `${value} instanceof Uint8Array`;
if ((0, index_12.IsNumber)(schema.maxByteLength))
yield `(${value}.length <= ${schema.maxByteLength})`;
if ((0, index_12.IsNumber)(schema.minByteLength))
yield `(${value}.length >= ${schema.minByteLength})`;
}
function* FromUnknown(schema, references, value) {
yield 'true';
}
function* FromVoid(schema, references, value) {
yield Policy.IsVoidLike(value);
}
function* FromKind(schema, references, value) {
const instance = state.instances.size;
state.instances.set(instance, schema);
yield `kind('${schema[index_7.Kind]}', ${instance}, ${value})`;
}
function* Visit(schema, references, value, useHoisting = true) {
const references_ = (0, index_12.IsString)(schema.$id) ? [...references, schema] : references;
const schema_ = schema;
// --------------------------------------------------------------
// Hoisting
// --------------------------------------------------------------
if (useHoisting && (0, index_12.IsString)(schema.$id)) {
const functionName = CreateFunctionName(schema.$id);
if (state.functions.has(functionName)) {
return yield `${functionName}(${value})`;
}
else {
// Note: In the case of cyclic types, we need to create a 'functions' record
// to prevent infinitely re-visiting the CreateFunction. Subsequent attempts
// to visit will be caught by the above condition.
state.functions.set(functionName, '<deferred>');
const functionCode = CreateFunction(functionName, schema, references, 'value', false);
state.functions.set(functionName, functionCode);
return yield `${functionName}(${value})`;
}
}
switch (schema_[index_7.Kind]) {
case 'Any':
return yield* FromAny(schema_, references_, value);
case 'Argument':
return yield* FromArgument(schema_, references_, value);
case 'Array':
return yield* FromArray(schema_, references_, value);
case 'AsyncIterator':
return yield* FromAsyncIterator(schema_, references_, value);
case 'BigInt':
return yield* FromBigInt(schema_, references_, value);
case 'Boolean':
return yield* FromBoolean(schema_, references_, value);
case 'Constructor':
return yield* FromConstructor(schema_, references_, value);
case 'Date':
return yield* FromDate(schema_, references_, value);
case 'Function':
return yield* FromFunction(schema_, references_, value);
case 'Import':
return yield* FromImport(schema_, references_, value);
case 'Integer':
return yield* FromInteger(schema_, references_, value);
case 'Intersect':
return yield* FromIntersect(schema_, references_, value);
case 'Iterator':
return yield* FromIterator(schema_, references_, value);
case 'Literal':
return yield* FromLiteral(schema_, references_, value);
case 'Never':
return yield* FromNever(schema_, references_, value);
case 'Not':
return yield* FromNot(schema_, references_, value);
case 'Null':
return yield* FromNull(schema_, references_, value);
case 'Number':
return yield* FromNumber(schema_, references_, value);
case 'Object':
return yield* FromObject(schema_, references_, value);
case 'Promise':
return yield* FromPromise(schema_, references_, value);
case 'Record':
return yield* FromRecord(schema_, references_, value);
case 'Ref':
return yield* FromRef(schema_, references_, value);
case 'RegExp':
return yield* FromRegExp(schema_, references_, value);
case 'String':
return yield* FromString(schema_, references_, value);
case 'Symbol':
return yield* FromSymbol(schema_, references_, value);
case 'TemplateLiteral':
return yield* FromTemplateLiteral(schema_, references_, value);
case 'This':
return yield* FromThis(schema_, references_, value);
case 'Tuple':
return yield* FromTuple(schema_, references_, value);
case 'Undefined':
return yield* FromUndefined(schema_, references_, value);
case 'Union':
return yield* FromUnion(schema_, references_, value);
case 'Uint8Array':
return yield* FromUint8Array(schema_, references_, value);
case 'Unknown':
return yield* FromUnknown(schema_, references_, value);
case 'Void':
return yield* FromVoid(schema_, references_, value);
default:
if (!index_8.TypeRegistry.Has(schema_[index_7.Kind]))
throw new TypeCompilerUnknownTypeError(schema);
return yield* FromKind(schema_, references_, value);
}
}
// ----------------------------------------------------------------
// Compiler State
// ----------------------------------------------------------------
// prettier-ignore
const state = {
language: 'javascript', // target language
functions: new Map(), // local functions
variables: new Map(), // local variables
instances: new Map() // exterior kind instances
};
// ----------------------------------------------------------------
// Compiler Factory
// ----------------------------------------------------------------
function CreateExpression(schema, references, value, useHoisting = true) {
return `(${[...Visit(schema, references, value, useHoisting)].join(' && ')})`;
}
function CreateFunctionName($id) {
return `check_${Identifier.Encode($id)}`;
}
function CreateVariable(expression) {
const variableName = `local_${state.variables.size}`;
state.variables.set(variableName, `const ${variableName} = ${expression}`);
return variableName;
}
function CreateFunction(name, schema, references, value, useHoisting = true) {
const [newline, pad] = ['\n', (length) => ''.padStart(length, ' ')];
const parameter = CreateParameter('value', 'any');
const returns = CreateReturns('boolean');
const expression = [...Visit(schema, references, value, useHoisting)].map((expression) => `${pad(4)}${expression}`).join(` &&${newline}`);
return `function ${name}(${parameter})${returns} {${newline}${pad(2)}return (${newline}${expression}${newline}${pad(2)})\n}`;
}
function CreateParameter(name, type) {
const annotation = state.language === 'typescript' ? `: ${type}` : '';
return `${name}${annotation}`;
}
function CreateReturns(type) {
return state.language === 'typescript' ? `: ${type}` : '';
}
// ----------------------------------------------------------------
// Compile
// ----------------------------------------------------------------
function Build(schema, references, options) {
const functionCode = CreateFunction('check', schema, references, 'value'); // will populate functions and variables
const parameter = CreateParameter('value', 'any');
const returns = CreateReturns('boolean');
const functions = [...state.functions.values()];
const variables = [...state.variables.values()];
// prettier-ignore
const checkFunction = (0, index_12.IsString)(schema.$id) // ensure top level schemas with $id's are hoisted
? `return function check(${parameter})${returns} {\n return ${CreateFunctionName(schema.$id)}(value)\n}`
: `return ${functionCode}`;
return [...variables, ...functions, checkFunction].join('\n');
}
/** Generates the code used to assert this type and returns it as a string */
function Code(...args) {
const defaults = { language: 'javascript' };
// prettier-ignore
const [schema, references, options] = (args.length === 2 && (0, index_12.IsArray)(args[1]) ? [args[0], args[1], defaults] :
args.length === 2 && !(0, index_12.IsArray)(args[1]) ? [args[0], [], args[1]] :
args.length === 3 ? [args[0], args[1], args[2]] :
args.length === 1 ? [args[0], [], defaults] :
[null, [], defaults]);
// compiler-reset
state.language = options.language;
state.variables.clear();
state.functions.clear();
state.instances.clear();
if (!(0, type_1.IsSchema)(schema))
throw new TypeCompilerTypeGuardError(schema);
for (const schema of references)
if (!(0, type_1.IsSchema)(schema))
throw new TypeCompilerTypeGuardError(schema);
return Build(schema, references, options);
}
TypeCompiler.Code = Code;
/** Compiles a TypeBox type for optimal runtime type checking. Types must be valid TypeBox types of TSchema */
function Compile(schema, references = []) {
const generatedCode = Code(schema, references, { language: 'javascript' });
const compiledFunction = globalThis.Function('kind', 'format', 'hash', generatedCode);
const instances = new Map(state.instances);
function typeRegistryFunction(kind, instance, value) {
if (!index_8.TypeRegistry.Has(kind) || !instances.has(instance))
return false;
const checkFunc = index_8.TypeRegistry.Get(kind);
const schema = instances.get(instance);
return checkFunc(schema, value);
}
function formatRegistryFunction(format, value) {
if (!index_8.FormatRegistry.Has(format))
return false;
const checkFunc = index_8.FormatRegistry.Get(format);
return checkFunc(value);
}
function hashFunction(value) {
return (0, index_6.Hash)(value);
}
const checkFunction = compiledFunction(typeRegistryFunction, formatRegistryFunction, hashFunction);
return new TypeCheck(schema, references, checkFunction, generatedCode);
}
TypeCompiler.Compile = Compile;
})(TypeCompiler || (exports.TypeCompiler = TypeCompiler = {}));
@@ -0,0 +1,2 @@
export { ValueError, ValueErrorType, ValueErrorIterator } from '../errors/index';
export * from './compiler';
@@ -0,0 +1,22 @@
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __exportStar = (this && this.__exportStar) || function(m, exports) {
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.ValueErrorIterator = exports.ValueErrorType = void 0;
var index_1 = require("../errors/index");
Object.defineProperty(exports, "ValueErrorType", { enumerable: true, get: function () { return index_1.ValueErrorType; } });
Object.defineProperty(exports, "ValueErrorIterator", { enumerable: true, get: function () { return index_1.ValueErrorIterator; } });
__exportStar(require("./compiler"), exports);
@@ -0,0 +1,91 @@
import { TypeBoxError } from '../type/error/index';
import type { TSchema } from '../type/schema/index';
export declare enum ValueErrorType {
ArrayContains = 0,
ArrayMaxContains = 1,
ArrayMaxItems = 2,
ArrayMinContains = 3,
ArrayMinItems = 4,
ArrayUniqueItems = 5,
Array = 6,
AsyncIterator = 7,
BigIntExclusiveMaximum = 8,
BigIntExclusiveMinimum = 9,
BigIntMaximum = 10,
BigIntMinimum = 11,
BigIntMultipleOf = 12,
BigInt = 13,
Boolean = 14,
DateExclusiveMaximumTimestamp = 15,
DateExclusiveMinimumTimestamp = 16,
DateMaximumTimestamp = 17,
DateMinimumTimestamp = 18,
DateMultipleOfTimestamp = 19,
Date = 20,
Function = 21,
IntegerExclusiveMaximum = 22,
IntegerExclusiveMinimum = 23,
IntegerMaximum = 24,
IntegerMinimum = 25,
IntegerMultipleOf = 26,
Integer = 27,
IntersectUnevaluatedProperties = 28,
Intersect = 29,
Iterator = 30,
Kind = 31,
Literal = 32,
Never = 33,
Not = 34,
Null = 35,
NumberExclusiveMaximum = 36,
NumberExclusiveMinimum = 37,
NumberMaximum = 38,
NumberMinimum = 39,
NumberMultipleOf = 40,
Number = 41,
ObjectAdditionalProperties = 42,
ObjectMaxProperties = 43,
ObjectMinProperties = 44,
ObjectRequiredProperty = 45,
Object = 46,
Promise = 47,
RegExp = 48,
StringFormatUnknown = 49,
StringFormat = 50,
StringMaxLength = 51,
StringMinLength = 52,
StringPattern = 53,
String = 54,
Symbol = 55,
TupleLength = 56,
Tuple = 57,
Uint8ArrayMaxByteLength = 58,
Uint8ArrayMinByteLength = 59,
Uint8Array = 60,
Undefined = 61,
Union = 62,
Void = 63
}
export interface ValueError {
type: ValueErrorType;
schema: TSchema;
path: string;
value: unknown;
message: string;
errors: ValueErrorIterator[];
}
export declare class ValueErrorsUnknownTypeError extends TypeBoxError {
readonly schema: TSchema;
constructor(schema: TSchema);
}
export declare class ValueErrorIterator {
private readonly iterator;
constructor(iterator: IterableIterator<ValueError>);
[Symbol.iterator](): IterableIterator<ValueError>;
/** Returns the first value error or undefined if no errors */
First(): ValueError | undefined;
}
/** Returns an iterator for each error in this value. */
export declare function Errors<T extends TSchema>(schema: T, references: TSchema[], value: unknown): ValueErrorIterator;
/** Returns an iterator for each error in this value. */
export declare function Errors<T extends TSchema>(schema: T, value: unknown): ValueErrorIterator;
+599
View File
@@ -0,0 +1,599 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ValueErrorIterator = exports.ValueErrorsUnknownTypeError = exports.ValueErrorType = void 0;
exports.Errors = Errors;
const index_1 = require("../system/index");
const index_2 = require("../type/keyof/index");
const index_3 = require("../type/registry/index");
const extends_undefined_1 = require("../type/extends/extends-undefined");
const function_1 = require("./function");
const index_4 = require("../type/error/index");
const index_5 = require("../value/deref/index");
const index_6 = require("../value/hash/index");
const index_7 = require("../value/check/index");
const index_8 = require("../type/symbols/index");
const index_9 = require("../type/never/index");
// ------------------------------------------------------------------
// ValueGuard
// ------------------------------------------------------------------
// prettier-ignore
const index_10 = require("../value/guard/index");
// ------------------------------------------------------------------
// ValueErrorType
// ------------------------------------------------------------------
var ValueErrorType;
(function (ValueErrorType) {
ValueErrorType[ValueErrorType["ArrayContains"] = 0] = "ArrayContains";
ValueErrorType[ValueErrorType["ArrayMaxContains"] = 1] = "ArrayMaxContains";
ValueErrorType[ValueErrorType["ArrayMaxItems"] = 2] = "ArrayMaxItems";
ValueErrorType[ValueErrorType["ArrayMinContains"] = 3] = "ArrayMinContains";
ValueErrorType[ValueErrorType["ArrayMinItems"] = 4] = "ArrayMinItems";
ValueErrorType[ValueErrorType["ArrayUniqueItems"] = 5] = "ArrayUniqueItems";
ValueErrorType[ValueErrorType["Array"] = 6] = "Array";
ValueErrorType[ValueErrorType["AsyncIterator"] = 7] = "AsyncIterator";
ValueErrorType[ValueErrorType["BigIntExclusiveMaximum"] = 8] = "BigIntExclusiveMaximum";
ValueErrorType[ValueErrorType["BigIntExclusiveMinimum"] = 9] = "BigIntExclusiveMinimum";
ValueErrorType[ValueErrorType["BigIntMaximum"] = 10] = "BigIntMaximum";
ValueErrorType[ValueErrorType["BigIntMinimum"] = 11] = "BigIntMinimum";
ValueErrorType[ValueErrorType["BigIntMultipleOf"] = 12] = "BigIntMultipleOf";
ValueErrorType[ValueErrorType["BigInt"] = 13] = "BigInt";
ValueErrorType[ValueErrorType["Boolean"] = 14] = "Boolean";
ValueErrorType[ValueErrorType["DateExclusiveMaximumTimestamp"] = 15] = "DateExclusiveMaximumTimestamp";
ValueErrorType[ValueErrorType["DateExclusiveMinimumTimestamp"] = 16] = "DateExclusiveMinimumTimestamp";
ValueErrorType[ValueErrorType["DateMaximumTimestamp"] = 17] = "DateMaximumTimestamp";
ValueErrorType[ValueErrorType["DateMinimumTimestamp"] = 18] = "DateMinimumTimestamp";
ValueErrorType[ValueErrorType["DateMultipleOfTimestamp"] = 19] = "DateMultipleOfTimestamp";
ValueErrorType[ValueErrorType["Date"] = 20] = "Date";
ValueErrorType[ValueErrorType["Function"] = 21] = "Function";
ValueErrorType[ValueErrorType["IntegerExclusiveMaximum"] = 22] = "IntegerExclusiveMaximum";
ValueErrorType[ValueErrorType["IntegerExclusiveMinimum"] = 23] = "IntegerExclusiveMinimum";
ValueErrorType[ValueErrorType["IntegerMaximum"] = 24] = "IntegerMaximum";
ValueErrorType[ValueErrorType["IntegerMinimum"] = 25] = "IntegerMinimum";
ValueErrorType[ValueErrorType["IntegerMultipleOf"] = 26] = "IntegerMultipleOf";
ValueErrorType[ValueErrorType["Integer"] = 27] = "Integer";
ValueErrorType[ValueErrorType["IntersectUnevaluatedProperties"] = 28] = "IntersectUnevaluatedProperties";
ValueErrorType[ValueErrorType["Intersect"] = 29] = "Intersect";
ValueErrorType[ValueErrorType["Iterator"] = 30] = "Iterator";
ValueErrorType[ValueErrorType["Kind"] = 31] = "Kind";
ValueErrorType[ValueErrorType["Literal"] = 32] = "Literal";
ValueErrorType[ValueErrorType["Never"] = 33] = "Never";
ValueErrorType[ValueErrorType["Not"] = 34] = "Not";
ValueErrorType[ValueErrorType["Null"] = 35] = "Null";
ValueErrorType[ValueErrorType["NumberExclusiveMaximum"] = 36] = "NumberExclusiveMaximum";
ValueErrorType[ValueErrorType["NumberExclusiveMinimum"] = 37] = "NumberExclusiveMinimum";
ValueErrorType[ValueErrorType["NumberMaximum"] = 38] = "NumberMaximum";
ValueErrorType[ValueErrorType["NumberMinimum"] = 39] = "NumberMinimum";
ValueErrorType[ValueErrorType["NumberMultipleOf"] = 40] = "NumberMultipleOf";
ValueErrorType[ValueErrorType["Number"] = 41] = "Number";
ValueErrorType[ValueErrorType["ObjectAdditionalProperties"] = 42] = "ObjectAdditionalProperties";
ValueErrorType[ValueErrorType["ObjectMaxProperties"] = 43] = "ObjectMaxProperties";
ValueErrorType[ValueErrorType["ObjectMinProperties"] = 44] = "ObjectMinProperties";
ValueErrorType[ValueErrorType["ObjectRequiredProperty"] = 45] = "ObjectRequiredProperty";
ValueErrorType[ValueErrorType["Object"] = 46] = "Object";
ValueErrorType[ValueErrorType["Promise"] = 47] = "Promise";
ValueErrorType[ValueErrorType["RegExp"] = 48] = "RegExp";
ValueErrorType[ValueErrorType["StringFormatUnknown"] = 49] = "StringFormatUnknown";
ValueErrorType[ValueErrorType["StringFormat"] = 50] = "StringFormat";
ValueErrorType[ValueErrorType["StringMaxLength"] = 51] = "StringMaxLength";
ValueErrorType[ValueErrorType["StringMinLength"] = 52] = "StringMinLength";
ValueErrorType[ValueErrorType["StringPattern"] = 53] = "StringPattern";
ValueErrorType[ValueErrorType["String"] = 54] = "String";
ValueErrorType[ValueErrorType["Symbol"] = 55] = "Symbol";
ValueErrorType[ValueErrorType["TupleLength"] = 56] = "TupleLength";
ValueErrorType[ValueErrorType["Tuple"] = 57] = "Tuple";
ValueErrorType[ValueErrorType["Uint8ArrayMaxByteLength"] = 58] = "Uint8ArrayMaxByteLength";
ValueErrorType[ValueErrorType["Uint8ArrayMinByteLength"] = 59] = "Uint8ArrayMinByteLength";
ValueErrorType[ValueErrorType["Uint8Array"] = 60] = "Uint8Array";
ValueErrorType[ValueErrorType["Undefined"] = 61] = "Undefined";
ValueErrorType[ValueErrorType["Union"] = 62] = "Union";
ValueErrorType[ValueErrorType["Void"] = 63] = "Void";
})(ValueErrorType || (exports.ValueErrorType = ValueErrorType = {}));
// ------------------------------------------------------------------
// ValueErrors
// ------------------------------------------------------------------
class ValueErrorsUnknownTypeError extends index_4.TypeBoxError {
constructor(schema) {
super('Unknown type');
this.schema = schema;
}
}
exports.ValueErrorsUnknownTypeError = ValueErrorsUnknownTypeError;
// ------------------------------------------------------------------
// EscapeKey
// ------------------------------------------------------------------
function EscapeKey(key) {
return key.replace(/~/g, '~0').replace(/\//g, '~1'); // RFC6901 Path
}
// ------------------------------------------------------------------
// Guards
// ------------------------------------------------------------------
function IsDefined(value) {
return value !== undefined;
}
// ------------------------------------------------------------------
// ValueErrorIterator
// ------------------------------------------------------------------
class ValueErrorIterator {
constructor(iterator) {
this.iterator = iterator;
}
[Symbol.iterator]() {
return this.iterator;
}
/** Returns the first value error or undefined if no errors */
First() {
const next = this.iterator.next();
return next.done ? undefined : next.value;
}
}
exports.ValueErrorIterator = ValueErrorIterator;
// --------------------------------------------------------------------------
// Create
// --------------------------------------------------------------------------
function Create(errorType, schema, path, value, errors = []) {
return {
type: errorType,
schema,
path,
value,
message: (0, function_1.GetErrorFunction)()({ errorType, path, schema, value, errors }),
errors,
};
}
// --------------------------------------------------------------------------
// Types
// --------------------------------------------------------------------------
function* FromAny(schema, references, path, value) { }
function* FromArgument(schema, references, path, value) { }
function* FromArray(schema, references, path, value) {
if (!(0, index_10.IsArray)(value)) {
return yield Create(ValueErrorType.Array, schema, path, value);
}
if (IsDefined(schema.minItems) && !(value.length >= schema.minItems)) {
yield Create(ValueErrorType.ArrayMinItems, schema, path, value);
}
if (IsDefined(schema.maxItems) && !(value.length <= schema.maxItems)) {
yield Create(ValueErrorType.ArrayMaxItems, schema, path, value);
}
for (let i = 0; i < value.length; i++) {
yield* Visit(schema.items, references, `${path}/${i}`, value[i]);
}
// prettier-ignore
if (schema.uniqueItems === true && !((function () { const set = new Set(); for (const element of value) {
const hashed = (0, index_6.Hash)(element);
if (set.has(hashed)) {
return false;
}
else {
set.add(hashed);
}
} return true; })())) {
yield Create(ValueErrorType.ArrayUniqueItems, schema, path, value);
}
// contains
if (!(IsDefined(schema.contains) || IsDefined(schema.minContains) || IsDefined(schema.maxContains))) {
return;
}
const containsSchema = IsDefined(schema.contains) ? schema.contains : (0, index_9.Never)();
const containsCount = value.reduce((acc, value, index) => (Visit(containsSchema, references, `${path}${index}`, value).next().done === true ? acc + 1 : acc), 0);
if (containsCount === 0) {
yield Create(ValueErrorType.ArrayContains, schema, path, value);
}
if ((0, index_10.IsNumber)(schema.minContains) && containsCount < schema.minContains) {
yield Create(ValueErrorType.ArrayMinContains, schema, path, value);
}
if ((0, index_10.IsNumber)(schema.maxContains) && containsCount > schema.maxContains) {
yield Create(ValueErrorType.ArrayMaxContains, schema, path, value);
}
}
function* FromAsyncIterator(schema, references, path, value) {
if (!(0, index_10.IsAsyncIterator)(value))
yield Create(ValueErrorType.AsyncIterator, schema, path, value);
}
function* FromBigInt(schema, references, path, value) {
if (!(0, index_10.IsBigInt)(value))
return yield Create(ValueErrorType.BigInt, schema, path, value);
if (IsDefined(schema.exclusiveMaximum) && !(value < schema.exclusiveMaximum)) {
yield Create(ValueErrorType.BigIntExclusiveMaximum, schema, path, value);
}
if (IsDefined(schema.exclusiveMinimum) && !(value > schema.exclusiveMinimum)) {
yield Create(ValueErrorType.BigIntExclusiveMinimum, schema, path, value);
}
if (IsDefined(schema.maximum) && !(value <= schema.maximum)) {
yield Create(ValueErrorType.BigIntMaximum, schema, path, value);
}
if (IsDefined(schema.minimum) && !(value >= schema.minimum)) {
yield Create(ValueErrorType.BigIntMinimum, schema, path, value);
}
if (IsDefined(schema.multipleOf) && !(value % schema.multipleOf === BigInt(0))) {
yield Create(ValueErrorType.BigIntMultipleOf, schema, path, value);
}
}
function* FromBoolean(schema, references, path, value) {
if (!(0, index_10.IsBoolean)(value))
yield Create(ValueErrorType.Boolean, schema, path, value);
}
function* FromConstructor(schema, references, path, value) {
yield* Visit(schema.returns, references, path, value.prototype);
}
function* FromDate(schema, references, path, value) {
if (!(0, index_10.IsDate)(value))
return yield Create(ValueErrorType.Date, schema, path, value);
if (IsDefined(schema.exclusiveMaximumTimestamp) && !(value.getTime() < schema.exclusiveMaximumTimestamp)) {
yield Create(ValueErrorType.DateExclusiveMaximumTimestamp, schema, path, value);
}
if (IsDefined(schema.exclusiveMinimumTimestamp) && !(value.getTime() > schema.exclusiveMinimumTimestamp)) {
yield Create(ValueErrorType.DateExclusiveMinimumTimestamp, schema, path, value);
}
if (IsDefined(schema.maximumTimestamp) && !(value.getTime() <= schema.maximumTimestamp)) {
yield Create(ValueErrorType.DateMaximumTimestamp, schema, path, value);
}
if (IsDefined(schema.minimumTimestamp) && !(value.getTime() >= schema.minimumTimestamp)) {
yield Create(ValueErrorType.DateMinimumTimestamp, schema, path, value);
}
if (IsDefined(schema.multipleOfTimestamp) && !(value.getTime() % schema.multipleOfTimestamp === 0)) {
yield Create(ValueErrorType.DateMultipleOfTimestamp, schema, path, value);
}
}
function* FromFunction(schema, references, path, value) {
if (!(0, index_10.IsFunction)(value))
yield Create(ValueErrorType.Function, schema, path, value);
}
function* FromImport(schema, references, path, value) {
const definitions = globalThis.Object.values(schema.$defs);
const target = schema.$defs[schema.$ref];
yield* Visit(target, [...references, ...definitions], path, value);
}
function* FromInteger(schema, references, path, value) {
if (!(0, index_10.IsInteger)(value))
return yield Create(ValueErrorType.Integer, schema, path, value);
if (IsDefined(schema.exclusiveMaximum) && !(value < schema.exclusiveMaximum)) {
yield Create(ValueErrorType.IntegerExclusiveMaximum, schema, path, value);
}
if (IsDefined(schema.exclusiveMinimum) && !(value > schema.exclusiveMinimum)) {
yield Create(ValueErrorType.IntegerExclusiveMinimum, schema, path, value);
}
if (IsDefined(schema.maximum) && !(value <= schema.maximum)) {
yield Create(ValueErrorType.IntegerMaximum, schema, path, value);
}
if (IsDefined(schema.minimum) && !(value >= schema.minimum)) {
yield Create(ValueErrorType.IntegerMinimum, schema, path, value);
}
if (IsDefined(schema.multipleOf) && !(value % schema.multipleOf === 0)) {
yield Create(ValueErrorType.IntegerMultipleOf, schema, path, value);
}
}
function* FromIntersect(schema, references, path, value) {
let hasError = false;
for (const inner of schema.allOf) {
for (const error of Visit(inner, references, path, value)) {
hasError = true;
yield error;
}
}
if (hasError) {
return yield Create(ValueErrorType.Intersect, schema, path, value);
}
if (schema.unevaluatedProperties === false) {
const keyCheck = new RegExp((0, index_2.KeyOfPattern)(schema));
for (const valueKey of Object.getOwnPropertyNames(value)) {
if (!keyCheck.test(valueKey)) {
yield Create(ValueErrorType.IntersectUnevaluatedProperties, schema, `${path}/${valueKey}`, value);
}
}
}
if (typeof schema.unevaluatedProperties === 'object') {
const keyCheck = new RegExp((0, index_2.KeyOfPattern)(schema));
for (const valueKey of Object.getOwnPropertyNames(value)) {
if (!keyCheck.test(valueKey)) {
const next = Visit(schema.unevaluatedProperties, references, `${path}/${valueKey}`, value[valueKey]).next();
if (!next.done)
yield next.value; // yield interior
}
}
}
}
function* FromIterator(schema, references, path, value) {
if (!(0, index_10.IsIterator)(value))
yield Create(ValueErrorType.Iterator, schema, path, value);
}
function* FromLiteral(schema, references, path, value) {
if (!(value === schema.const))
yield Create(ValueErrorType.Literal, schema, path, value);
}
function* FromNever(schema, references, path, value) {
yield Create(ValueErrorType.Never, schema, path, value);
}
function* FromNot(schema, references, path, value) {
if (Visit(schema.not, references, path, value).next().done === true)
yield Create(ValueErrorType.Not, schema, path, value);
}
function* FromNull(schema, references, path, value) {
if (!(0, index_10.IsNull)(value))
yield Create(ValueErrorType.Null, schema, path, value);
}
function* FromNumber(schema, references, path, value) {
if (!index_1.TypeSystemPolicy.IsNumberLike(value))
return yield Create(ValueErrorType.Number, schema, path, value);
if (IsDefined(schema.exclusiveMaximum) && !(value < schema.exclusiveMaximum)) {
yield Create(ValueErrorType.NumberExclusiveMaximum, schema, path, value);
}
if (IsDefined(schema.exclusiveMinimum) && !(value > schema.exclusiveMinimum)) {
yield Create(ValueErrorType.NumberExclusiveMinimum, schema, path, value);
}
if (IsDefined(schema.maximum) && !(value <= schema.maximum)) {
yield Create(ValueErrorType.NumberMaximum, schema, path, value);
}
if (IsDefined(schema.minimum) && !(value >= schema.minimum)) {
yield Create(ValueErrorType.NumberMinimum, schema, path, value);
}
if (IsDefined(schema.multipleOf) && !(value % schema.multipleOf === 0)) {
yield Create(ValueErrorType.NumberMultipleOf, schema, path, value);
}
}
function* FromObject(schema, references, path, value) {
if (!index_1.TypeSystemPolicy.IsObjectLike(value))
return yield Create(ValueErrorType.Object, schema, path, value);
if (IsDefined(schema.minProperties) && !(Object.getOwnPropertyNames(value).length >= schema.minProperties)) {
yield Create(ValueErrorType.ObjectMinProperties, schema, path, value);
}
if (IsDefined(schema.maxProperties) && !(Object.getOwnPropertyNames(value).length <= schema.maxProperties)) {
yield Create(ValueErrorType.ObjectMaxProperties, schema, path, value);
}
const requiredKeys = Array.isArray(schema.required) ? schema.required : [];
const knownKeys = Object.getOwnPropertyNames(schema.properties);
const unknownKeys = Object.getOwnPropertyNames(value);
for (const requiredKey of requiredKeys) {
if (unknownKeys.includes(requiredKey))
continue;
yield Create(ValueErrorType.ObjectRequiredProperty, schema.properties[requiredKey], `${path}/${EscapeKey(requiredKey)}`, undefined);
}
if (schema.additionalProperties === false) {
for (const valueKey of unknownKeys) {
if (!knownKeys.includes(valueKey)) {
yield Create(ValueErrorType.ObjectAdditionalProperties, schema, `${path}/${EscapeKey(valueKey)}`, value[valueKey]);
}
}
}
if (typeof schema.additionalProperties === 'object') {
for (const valueKey of unknownKeys) {
if (knownKeys.includes(valueKey))
continue;
yield* Visit(schema.additionalProperties, references, `${path}/${EscapeKey(valueKey)}`, value[valueKey]);
}
}
for (const knownKey of knownKeys) {
const property = schema.properties[knownKey];
if (schema.required && schema.required.includes(knownKey)) {
yield* Visit(property, references, `${path}/${EscapeKey(knownKey)}`, value[knownKey]);
if ((0, extends_undefined_1.ExtendsUndefinedCheck)(schema) && !(knownKey in value)) {
yield Create(ValueErrorType.ObjectRequiredProperty, property, `${path}/${EscapeKey(knownKey)}`, undefined);
}
}
else {
if (index_1.TypeSystemPolicy.IsExactOptionalProperty(value, knownKey)) {
yield* Visit(property, references, `${path}/${EscapeKey(knownKey)}`, value[knownKey]);
}
}
}
}
function* FromPromise(schema, references, path, value) {
if (!(0, index_10.IsPromise)(value))
yield Create(ValueErrorType.Promise, schema, path, value);
}
function* FromRecord(schema, references, path, value) {
if (!index_1.TypeSystemPolicy.IsRecordLike(value))
return yield Create(ValueErrorType.Object, schema, path, value);
if (IsDefined(schema.minProperties) && !(Object.getOwnPropertyNames(value).length >= schema.minProperties)) {
yield Create(ValueErrorType.ObjectMinProperties, schema, path, value);
}
if (IsDefined(schema.maxProperties) && !(Object.getOwnPropertyNames(value).length <= schema.maxProperties)) {
yield Create(ValueErrorType.ObjectMaxProperties, schema, path, value);
}
const [patternKey, patternSchema] = Object.entries(schema.patternProperties)[0];
const regex = new RegExp(patternKey);
for (const [propertyKey, propertyValue] of Object.entries(value)) {
if (regex.test(propertyKey))
yield* Visit(patternSchema, references, `${path}/${EscapeKey(propertyKey)}`, propertyValue);
}
if (typeof schema.additionalProperties === 'object') {
for (const [propertyKey, propertyValue] of Object.entries(value)) {
if (!regex.test(propertyKey))
yield* Visit(schema.additionalProperties, references, `${path}/${EscapeKey(propertyKey)}`, propertyValue);
}
}
if (schema.additionalProperties === false) {
for (const [propertyKey, propertyValue] of Object.entries(value)) {
if (regex.test(propertyKey))
continue;
return yield Create(ValueErrorType.ObjectAdditionalProperties, schema, `${path}/${EscapeKey(propertyKey)}`, propertyValue);
}
}
}
function* FromRef(schema, references, path, value) {
yield* Visit((0, index_5.Deref)(schema, references), references, path, value);
}
function* FromRegExp(schema, references, path, value) {
if (!(0, index_10.IsString)(value))
return yield Create(ValueErrorType.String, schema, path, value);
if (IsDefined(schema.minLength) && !(value.length >= schema.minLength)) {
yield Create(ValueErrorType.StringMinLength, schema, path, value);
}
if (IsDefined(schema.maxLength) && !(value.length <= schema.maxLength)) {
yield Create(ValueErrorType.StringMaxLength, schema, path, value);
}
const regex = new RegExp(schema.source, schema.flags);
if (!regex.test(value)) {
return yield Create(ValueErrorType.RegExp, schema, path, value);
}
}
function* FromString(schema, references, path, value) {
if (!(0, index_10.IsString)(value))
return yield Create(ValueErrorType.String, schema, path, value);
if (IsDefined(schema.minLength) && !(value.length >= schema.minLength)) {
yield Create(ValueErrorType.StringMinLength, schema, path, value);
}
if (IsDefined(schema.maxLength) && !(value.length <= schema.maxLength)) {
yield Create(ValueErrorType.StringMaxLength, schema, path, value);
}
if ((0, index_10.IsString)(schema.pattern)) {
const regex = new RegExp(schema.pattern);
if (!regex.test(value)) {
yield Create(ValueErrorType.StringPattern, schema, path, value);
}
}
if ((0, index_10.IsString)(schema.format)) {
if (!index_3.FormatRegistry.Has(schema.format)) {
yield Create(ValueErrorType.StringFormatUnknown, schema, path, value);
}
else {
const format = index_3.FormatRegistry.Get(schema.format);
if (!format(value)) {
yield Create(ValueErrorType.StringFormat, schema, path, value);
}
}
}
}
function* FromSymbol(schema, references, path, value) {
if (!(0, index_10.IsSymbol)(value))
yield Create(ValueErrorType.Symbol, schema, path, value);
}
function* FromTemplateLiteral(schema, references, path, value) {
if (!(0, index_10.IsString)(value))
return yield Create(ValueErrorType.String, schema, path, value);
const regex = new RegExp(schema.pattern);
if (!regex.test(value)) {
yield Create(ValueErrorType.StringPattern, schema, path, value);
}
}
function* FromThis(schema, references, path, value) {
yield* Visit((0, index_5.Deref)(schema, references), references, path, value);
}
function* FromTuple(schema, references, path, value) {
if (!(0, index_10.IsArray)(value))
return yield Create(ValueErrorType.Tuple, schema, path, value);
if (schema.items === undefined && !(value.length === 0)) {
return yield Create(ValueErrorType.TupleLength, schema, path, value);
}
if (!(value.length === schema.maxItems)) {
return yield Create(ValueErrorType.TupleLength, schema, path, value);
}
if (!schema.items) {
return;
}
for (let i = 0; i < schema.items.length; i++) {
yield* Visit(schema.items[i], references, `${path}/${i}`, value[i]);
}
}
function* FromUndefined(schema, references, path, value) {
if (!(0, index_10.IsUndefined)(value))
yield Create(ValueErrorType.Undefined, schema, path, value);
}
function* FromUnion(schema, references, path, value) {
if ((0, index_7.Check)(schema, references, value))
return;
const errors = schema.anyOf.map((variant) => new ValueErrorIterator(Visit(variant, references, path, value)));
yield Create(ValueErrorType.Union, schema, path, value, errors);
}
function* FromUint8Array(schema, references, path, value) {
if (!(0, index_10.IsUint8Array)(value))
return yield Create(ValueErrorType.Uint8Array, schema, path, value);
if (IsDefined(schema.maxByteLength) && !(value.length <= schema.maxByteLength)) {
yield Create(ValueErrorType.Uint8ArrayMaxByteLength, schema, path, value);
}
if (IsDefined(schema.minByteLength) && !(value.length >= schema.minByteLength)) {
yield Create(ValueErrorType.Uint8ArrayMinByteLength, schema, path, value);
}
}
function* FromUnknown(schema, references, path, value) { }
function* FromVoid(schema, references, path, value) {
if (!index_1.TypeSystemPolicy.IsVoidLike(value))
yield Create(ValueErrorType.Void, schema, path, value);
}
function* FromKind(schema, references, path, value) {
const check = index_3.TypeRegistry.Get(schema[index_8.Kind]);
if (!check(schema, value))
yield Create(ValueErrorType.Kind, schema, path, value);
}
function* Visit(schema, references, path, value) {
const references_ = IsDefined(schema.$id) ? [...references, schema] : references;
const schema_ = schema;
switch (schema_[index_8.Kind]) {
case 'Any':
return yield* FromAny(schema_, references_, path, value);
case 'Argument':
return yield* FromArgument(schema_, references_, path, value);
case 'Array':
return yield* FromArray(schema_, references_, path, value);
case 'AsyncIterator':
return yield* FromAsyncIterator(schema_, references_, path, value);
case 'BigInt':
return yield* FromBigInt(schema_, references_, path, value);
case 'Boolean':
return yield* FromBoolean(schema_, references_, path, value);
case 'Constructor':
return yield* FromConstructor(schema_, references_, path, value);
case 'Date':
return yield* FromDate(schema_, references_, path, value);
case 'Function':
return yield* FromFunction(schema_, references_, path, value);
case 'Import':
return yield* FromImport(schema_, references_, path, value);
case 'Integer':
return yield* FromInteger(schema_, references_, path, value);
case 'Intersect':
return yield* FromIntersect(schema_, references_, path, value);
case 'Iterator':
return yield* FromIterator(schema_, references_, path, value);
case 'Literal':
return yield* FromLiteral(schema_, references_, path, value);
case 'Never':
return yield* FromNever(schema_, references_, path, value);
case 'Not':
return yield* FromNot(schema_, references_, path, value);
case 'Null':
return yield* FromNull(schema_, references_, path, value);
case 'Number':
return yield* FromNumber(schema_, references_, path, value);
case 'Object':
return yield* FromObject(schema_, references_, path, value);
case 'Promise':
return yield* FromPromise(schema_, references_, path, value);
case 'Record':
return yield* FromRecord(schema_, references_, path, value);
case 'Ref':
return yield* FromRef(schema_, references_, path, value);
case 'RegExp':
return yield* FromRegExp(schema_, references_, path, value);
case 'String':
return yield* FromString(schema_, references_, path, value);
case 'Symbol':
return yield* FromSymbol(schema_, references_, path, value);
case 'TemplateLiteral':
return yield* FromTemplateLiteral(schema_, references_, path, value);
case 'This':
return yield* FromThis(schema_, references_, path, value);
case 'Tuple':
return yield* FromTuple(schema_, references_, path, value);
case 'Undefined':
return yield* FromUndefined(schema_, references_, path, value);
case 'Union':
return yield* FromUnion(schema_, references_, path, value);
case 'Uint8Array':
return yield* FromUint8Array(schema_, references_, path, value);
case 'Unknown':
return yield* FromUnknown(schema_, references_, path, value);
case 'Void':
return yield* FromVoid(schema_, references_, path, value);
default:
if (!index_3.TypeRegistry.Has(schema_[index_8.Kind]))
throw new ValueErrorsUnknownTypeError(schema);
return yield* FromKind(schema_, references_, path, value);
}
}
/** Returns an iterator for each error in this value. */
function Errors(...args) {
const iterator = args.length === 3 ? Visit(args[0], args[1], '', args[2]) : Visit(args[0], [], '', args[1]);
return new ValueErrorIterator(iterator);
}
@@ -0,0 +1,21 @@
import { TSchema } from '../type/schema/index';
import { ValueErrorIterator, ValueErrorType } from './errors';
/** Creates an error message using en-US as the default locale */
export declare function DefaultErrorFunction(error: ErrorFunctionParameter): string;
export type ErrorFunctionParameter = {
/** The type of validation error */
errorType: ValueErrorType;
/** The path of the error */
path: string;
/** The schema associated with the error */
schema: TSchema;
/** The value associated with the error */
value: unknown;
/** Interior errors for this error */
errors: ValueErrorIterator[];
};
export type ErrorFunction = (parameter: ErrorFunctionParameter) => string;
/** Sets the error function used to generate error messages. */
export declare function SetErrorFunction(callback: ErrorFunction): void;
/** Gets the error function used to generate error messages */
export declare function GetErrorFunction(): ErrorFunction;
@@ -0,0 +1,153 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.DefaultErrorFunction = DefaultErrorFunction;
exports.SetErrorFunction = SetErrorFunction;
exports.GetErrorFunction = GetErrorFunction;
const index_1 = require("../type/symbols/index");
const errors_1 = require("./errors");
/** Creates an error message using en-US as the default locale */
function DefaultErrorFunction(error) {
switch (error.errorType) {
case errors_1.ValueErrorType.ArrayContains:
return 'Expected array to contain at least one matching value';
case errors_1.ValueErrorType.ArrayMaxContains:
return `Expected array to contain no more than ${error.schema.maxContains} matching values`;
case errors_1.ValueErrorType.ArrayMinContains:
return `Expected array to contain at least ${error.schema.minContains} matching values`;
case errors_1.ValueErrorType.ArrayMaxItems:
return `Expected array length to be less or equal to ${error.schema.maxItems}`;
case errors_1.ValueErrorType.ArrayMinItems:
return `Expected array length to be greater or equal to ${error.schema.minItems}`;
case errors_1.ValueErrorType.ArrayUniqueItems:
return 'Expected array elements to be unique';
case errors_1.ValueErrorType.Array:
return 'Expected array';
case errors_1.ValueErrorType.AsyncIterator:
return 'Expected AsyncIterator';
case errors_1.ValueErrorType.BigIntExclusiveMaximum:
return `Expected bigint to be less than ${error.schema.exclusiveMaximum}`;
case errors_1.ValueErrorType.BigIntExclusiveMinimum:
return `Expected bigint to be greater than ${error.schema.exclusiveMinimum}`;
case errors_1.ValueErrorType.BigIntMaximum:
return `Expected bigint to be less or equal to ${error.schema.maximum}`;
case errors_1.ValueErrorType.BigIntMinimum:
return `Expected bigint to be greater or equal to ${error.schema.minimum}`;
case errors_1.ValueErrorType.BigIntMultipleOf:
return `Expected bigint to be a multiple of ${error.schema.multipleOf}`;
case errors_1.ValueErrorType.BigInt:
return 'Expected bigint';
case errors_1.ValueErrorType.Boolean:
return 'Expected boolean';
case errors_1.ValueErrorType.DateExclusiveMinimumTimestamp:
return `Expected Date timestamp to be greater than ${error.schema.exclusiveMinimumTimestamp}`;
case errors_1.ValueErrorType.DateExclusiveMaximumTimestamp:
return `Expected Date timestamp to be less than ${error.schema.exclusiveMaximumTimestamp}`;
case errors_1.ValueErrorType.DateMinimumTimestamp:
return `Expected Date timestamp to be greater or equal to ${error.schema.minimumTimestamp}`;
case errors_1.ValueErrorType.DateMaximumTimestamp:
return `Expected Date timestamp to be less or equal to ${error.schema.maximumTimestamp}`;
case errors_1.ValueErrorType.DateMultipleOfTimestamp:
return `Expected Date timestamp to be a multiple of ${error.schema.multipleOfTimestamp}`;
case errors_1.ValueErrorType.Date:
return 'Expected Date';
case errors_1.ValueErrorType.Function:
return 'Expected function';
case errors_1.ValueErrorType.IntegerExclusiveMaximum:
return `Expected integer to be less than ${error.schema.exclusiveMaximum}`;
case errors_1.ValueErrorType.IntegerExclusiveMinimum:
return `Expected integer to be greater than ${error.schema.exclusiveMinimum}`;
case errors_1.ValueErrorType.IntegerMaximum:
return `Expected integer to be less or equal to ${error.schema.maximum}`;
case errors_1.ValueErrorType.IntegerMinimum:
return `Expected integer to be greater or equal to ${error.schema.minimum}`;
case errors_1.ValueErrorType.IntegerMultipleOf:
return `Expected integer to be a multiple of ${error.schema.multipleOf}`;
case errors_1.ValueErrorType.Integer:
return 'Expected integer';
case errors_1.ValueErrorType.IntersectUnevaluatedProperties:
return 'Unexpected property';
case errors_1.ValueErrorType.Intersect:
return 'Expected all values to match';
case errors_1.ValueErrorType.Iterator:
return 'Expected Iterator';
case errors_1.ValueErrorType.Literal:
return `Expected ${typeof error.schema.const === 'string' ? `'${error.schema.const}'` : error.schema.const}`;
case errors_1.ValueErrorType.Never:
return 'Never';
case errors_1.ValueErrorType.Not:
return 'Value should not match';
case errors_1.ValueErrorType.Null:
return 'Expected null';
case errors_1.ValueErrorType.NumberExclusiveMaximum:
return `Expected number to be less than ${error.schema.exclusiveMaximum}`;
case errors_1.ValueErrorType.NumberExclusiveMinimum:
return `Expected number to be greater than ${error.schema.exclusiveMinimum}`;
case errors_1.ValueErrorType.NumberMaximum:
return `Expected number to be less or equal to ${error.schema.maximum}`;
case errors_1.ValueErrorType.NumberMinimum:
return `Expected number to be greater or equal to ${error.schema.minimum}`;
case errors_1.ValueErrorType.NumberMultipleOf:
return `Expected number to be a multiple of ${error.schema.multipleOf}`;
case errors_1.ValueErrorType.Number:
return 'Expected number';
case errors_1.ValueErrorType.Object:
return 'Expected object';
case errors_1.ValueErrorType.ObjectAdditionalProperties:
return 'Unexpected property';
case errors_1.ValueErrorType.ObjectMaxProperties:
return `Expected object to have no more than ${error.schema.maxProperties} properties`;
case errors_1.ValueErrorType.ObjectMinProperties:
return `Expected object to have at least ${error.schema.minProperties} properties`;
case errors_1.ValueErrorType.ObjectRequiredProperty:
return 'Expected required property';
case errors_1.ValueErrorType.Promise:
return 'Expected Promise';
case errors_1.ValueErrorType.RegExp:
return 'Expected string to match regular expression';
case errors_1.ValueErrorType.StringFormatUnknown:
return `Unknown format '${error.schema.format}'`;
case errors_1.ValueErrorType.StringFormat:
return `Expected string to match '${error.schema.format}' format`;
case errors_1.ValueErrorType.StringMaxLength:
return `Expected string length less or equal to ${error.schema.maxLength}`;
case errors_1.ValueErrorType.StringMinLength:
return `Expected string length greater or equal to ${error.schema.minLength}`;
case errors_1.ValueErrorType.StringPattern:
return `Expected string to match '${error.schema.pattern}'`;
case errors_1.ValueErrorType.String:
return 'Expected string';
case errors_1.ValueErrorType.Symbol:
return 'Expected symbol';
case errors_1.ValueErrorType.TupleLength:
return `Expected tuple to have ${error.schema.maxItems || 0} elements`;
case errors_1.ValueErrorType.Tuple:
return 'Expected tuple';
case errors_1.ValueErrorType.Uint8ArrayMaxByteLength:
return `Expected byte length less or equal to ${error.schema.maxByteLength}`;
case errors_1.ValueErrorType.Uint8ArrayMinByteLength:
return `Expected byte length greater or equal to ${error.schema.minByteLength}`;
case errors_1.ValueErrorType.Uint8Array:
return 'Expected Uint8Array';
case errors_1.ValueErrorType.Undefined:
return 'Expected undefined';
case errors_1.ValueErrorType.Union:
return 'Expected union value';
case errors_1.ValueErrorType.Void:
return 'Expected void';
case errors_1.ValueErrorType.Kind:
return `Expected kind '${error.schema[index_1.Kind]}'`;
default:
return 'Unknown error type';
}
}
/** Manages error message providers */
let errorFunction = DefaultErrorFunction;
/** Sets the error function used to generate error messages. */
function SetErrorFunction(callback) {
errorFunction = callback;
}
/** Gets the error function used to generate error messages */
function GetErrorFunction() {
return errorFunction;
}
@@ -0,0 +1,2 @@
export * from './errors';
export * from './function';
+19
View File
@@ -0,0 +1,19 @@
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __exportStar = (this && this.__exportStar) || function(m, exports) {
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
Object.defineProperty(exports, "__esModule", { value: true });
__exportStar(require("./errors"), exports);
__exportStar(require("./function"), exports);
+71
View File
@@ -0,0 +1,71 @@
export * from './type/clone/index';
export * from './type/create/index';
export * from './type/error/index';
export * from './type/guard/index';
export * from './type/helpers/index';
export * from './type/patterns/index';
export * from './type/registry/index';
export * from './type/sets/index';
export * from './type/symbols/index';
export * from './type/any/index';
export * from './type/array/index';
export * from './type/argument/index';
export * from './type/async-iterator/index';
export * from './type/awaited/index';
export * from './type/bigint/index';
export * from './type/boolean/index';
export * from './type/composite/index';
export * from './type/const/index';
export * from './type/constructor/index';
export * from './type/constructor-parameters/index';
export * from './type/date/index';
export * from './type/enum/index';
export * from './type/exclude/index';
export * from './type/extends/index';
export * from './type/extract/index';
export * from './type/function/index';
export * from './type/indexed/index';
export * from './type/instance-type/index';
export * from './type/instantiate/index';
export * from './type/integer/index';
export * from './type/intersect/index';
export * from './type/iterator/index';
export * from './type/intrinsic/index';
export * from './type/keyof/index';
export * from './type/literal/index';
export * from './type/module/index';
export * from './type/mapped/index';
export * from './type/never/index';
export * from './type/not/index';
export * from './type/null/index';
export * from './type/number/index';
export * from './type/object/index';
export * from './type/omit/index';
export * from './type/optional/index';
export * from './type/parameters/index';
export * from './type/partial/index';
export * from './type/pick/index';
export * from './type/promise/index';
export * from './type/readonly/index';
export * from './type/readonly-optional/index';
export * from './type/record/index';
export * from './type/recursive/index';
export * from './type/ref/index';
export * from './type/regexp/index';
export * from './type/required/index';
export * from './type/rest/index';
export * from './type/return-type/index';
export * from './type/schema/index';
export * from './type/static/index';
export * from './type/string/index';
export * from './type/symbol/index';
export * from './type/template-literal/index';
export * from './type/transform/index';
export * from './type/tuple/index';
export * from './type/uint8array/index';
export * from './type/undefined/index';
export * from './type/union/index';
export * from './type/unknown/index';
export * from './type/unsafe/index';
export * from './type/void/index';
export * from './type/type/index';
+97
View File
@@ -0,0 +1,97 @@
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __exportStar = (this && this.__exportStar) || function(m, exports) {
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
Object.defineProperty(exports, "__esModule", { value: true });
// ------------------------------------------------------------------
// Infrastructure
// ------------------------------------------------------------------
__exportStar(require("./type/clone/index"), exports);
__exportStar(require("./type/create/index"), exports);
__exportStar(require("./type/error/index"), exports);
__exportStar(require("./type/guard/index"), exports);
__exportStar(require("./type/helpers/index"), exports);
__exportStar(require("./type/patterns/index"), exports);
__exportStar(require("./type/registry/index"), exports);
__exportStar(require("./type/sets/index"), exports);
__exportStar(require("./type/symbols/index"), exports);
// ------------------------------------------------------------------
// Types
// ------------------------------------------------------------------
__exportStar(require("./type/any/index"), exports);
__exportStar(require("./type/array/index"), exports);
__exportStar(require("./type/argument/index"), exports);
__exportStar(require("./type/async-iterator/index"), exports);
__exportStar(require("./type/awaited/index"), exports);
__exportStar(require("./type/bigint/index"), exports);
__exportStar(require("./type/boolean/index"), exports);
__exportStar(require("./type/composite/index"), exports);
__exportStar(require("./type/const/index"), exports);
__exportStar(require("./type/constructor/index"), exports);
__exportStar(require("./type/constructor-parameters/index"), exports);
__exportStar(require("./type/date/index"), exports);
__exportStar(require("./type/enum/index"), exports);
__exportStar(require("./type/exclude/index"), exports);
__exportStar(require("./type/extends/index"), exports);
__exportStar(require("./type/extract/index"), exports);
__exportStar(require("./type/function/index"), exports);
__exportStar(require("./type/indexed/index"), exports);
__exportStar(require("./type/instance-type/index"), exports);
__exportStar(require("./type/instantiate/index"), exports);
__exportStar(require("./type/integer/index"), exports);
__exportStar(require("./type/intersect/index"), exports);
__exportStar(require("./type/iterator/index"), exports);
__exportStar(require("./type/intrinsic/index"), exports);
__exportStar(require("./type/keyof/index"), exports);
__exportStar(require("./type/literal/index"), exports);
__exportStar(require("./type/module/index"), exports);
__exportStar(require("./type/mapped/index"), exports);
__exportStar(require("./type/never/index"), exports);
__exportStar(require("./type/not/index"), exports);
__exportStar(require("./type/null/index"), exports);
__exportStar(require("./type/number/index"), exports);
__exportStar(require("./type/object/index"), exports);
__exportStar(require("./type/omit/index"), exports);
__exportStar(require("./type/optional/index"), exports);
__exportStar(require("./type/parameters/index"), exports);
__exportStar(require("./type/partial/index"), exports);
__exportStar(require("./type/pick/index"), exports);
__exportStar(require("./type/promise/index"), exports);
__exportStar(require("./type/readonly/index"), exports);
__exportStar(require("./type/readonly-optional/index"), exports);
__exportStar(require("./type/record/index"), exports);
__exportStar(require("./type/recursive/index"), exports);
__exportStar(require("./type/ref/index"), exports);
__exportStar(require("./type/regexp/index"), exports);
__exportStar(require("./type/required/index"), exports);
__exportStar(require("./type/rest/index"), exports);
__exportStar(require("./type/return-type/index"), exports);
__exportStar(require("./type/schema/index"), exports);
__exportStar(require("./type/static/index"), exports);
__exportStar(require("./type/string/index"), exports);
__exportStar(require("./type/symbol/index"), exports);
__exportStar(require("./type/template-literal/index"), exports);
__exportStar(require("./type/transform/index"), exports);
__exportStar(require("./type/tuple/index"), exports);
__exportStar(require("./type/uint8array/index"), exports);
__exportStar(require("./type/undefined/index"), exports);
__exportStar(require("./type/union/index"), exports);
__exportStar(require("./type/unknown/index"), exports);
__exportStar(require("./type/unsafe/index"), exports);
__exportStar(require("./type/void/index"), exports);
// ------------------------------------------------------------------
// Type.*
// ------------------------------------------------------------------
__exportStar(require("./type/type/index"), exports);
@@ -0,0 +1,2 @@
export * as Runtime from './runtime/index';
export * as Static from './static/index';
+39
View File
@@ -0,0 +1,39 @@
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
var ownKeys = function(o) {
ownKeys = Object.getOwnPropertyNames || function (o) {
var ar = [];
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
return ar;
};
return ownKeys(o);
};
return function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
__setModuleDefault(result, mod);
return result;
};
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.Static = exports.Runtime = void 0;
exports.Runtime = __importStar(require("./runtime/index"));
exports.Static = __importStar(require("./static/index"));
@@ -0,0 +1,23 @@
import { IArray, IConst, IContext, IIdent, INumber, IOptional, IRef, IString, ITuple, IUnion } from './types';
/** Returns true if the value is a Array Parser */
export declare function IsArray(value: unknown): value is IArray;
/** Returns true if the value is a Const Parser */
export declare function IsConst(value: unknown): value is IConst;
/** Returns true if the value is a Context Parser */
export declare function IsContext(value: unknown): value is IContext;
/** Returns true if the value is a Ident Parser */
export declare function IsIdent(value: unknown): value is IIdent;
/** Returns true if the value is a Number Parser */
export declare function IsNumber(value: unknown): value is INumber;
/** Returns true if the value is a Optional Parser */
export declare function IsOptional(value: unknown): value is IOptional;
/** Returns true if the value is a Ref Parser */
export declare function IsRef(value: unknown): value is IRef;
/** Returns true if the value is a String Parser */
export declare function IsString(value: unknown): value is IString;
/** Returns true if the value is a Tuple Parser */
export declare function IsTuple(value: unknown): value is ITuple;
/** Returns true if the value is a Union Parser */
export declare function IsUnion(value: unknown): value is IUnion;
/** Returns true if the value is a Parser */
export declare function IsParser(value: unknown): value is IContext<unknown> | IUnion<unknown> | IArray<unknown> | IConst<unknown> | IIdent<unknown> | INumber<unknown> | IOptional<unknown> | IRef<unknown> | IString<unknown> | ITuple<unknown>;
@@ -0,0 +1,86 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.IsArray = IsArray;
exports.IsConst = IsConst;
exports.IsContext = IsContext;
exports.IsIdent = IsIdent;
exports.IsNumber = IsNumber;
exports.IsOptional = IsOptional;
exports.IsRef = IsRef;
exports.IsString = IsString;
exports.IsTuple = IsTuple;
exports.IsUnion = IsUnion;
exports.IsParser = IsParser;
// ------------------------------------------------------------------
// Value Guard
// ------------------------------------------------------------------
// prettier-ignore
function HasPropertyKey(value, key) {
return key in value;
}
// prettier-ignore
function IsObjectValue(value) {
return typeof value === 'object' && value !== null;
}
// prettier-ignore
function IsArrayValue(value) {
return globalThis.Array.isArray(value);
}
// ------------------------------------------------------------------
// Parser Guard
// ------------------------------------------------------------------
/** Returns true if the value is a Array Parser */
function IsArray(value) {
return IsObjectValue(value) && HasPropertyKey(value, 'type') && value.type === 'Array' && HasPropertyKey(value, 'parser') && IsObjectValue(value.parser);
}
/** Returns true if the value is a Const Parser */
function IsConst(value) {
return IsObjectValue(value) && HasPropertyKey(value, 'type') && value.type === 'Const' && HasPropertyKey(value, 'value') && typeof value.value === 'string';
}
/** Returns true if the value is a Context Parser */
function IsContext(value) {
return IsObjectValue(value) && HasPropertyKey(value, 'type') && value.type === 'Context' && HasPropertyKey(value, 'left') && IsParser(value.left) && HasPropertyKey(value, 'right') && IsParser(value.right);
}
/** Returns true if the value is a Ident Parser */
function IsIdent(value) {
return IsObjectValue(value) && HasPropertyKey(value, 'type') && value.type === 'Ident';
}
/** Returns true if the value is a Number Parser */
function IsNumber(value) {
return IsObjectValue(value) && HasPropertyKey(value, 'type') && value.type === 'Number';
}
/** Returns true if the value is a Optional Parser */
function IsOptional(value) {
return IsObjectValue(value) && HasPropertyKey(value, 'type') && value.type === 'Optional' && HasPropertyKey(value, 'parser') && IsObjectValue(value.parser);
}
/** Returns true if the value is a Ref Parser */
function IsRef(value) {
return IsObjectValue(value) && HasPropertyKey(value, 'type') && value.type === 'Ref' && HasPropertyKey(value, 'ref') && typeof value.ref === 'string';
}
/** Returns true if the value is a String Parser */
function IsString(value) {
return IsObjectValue(value) && HasPropertyKey(value, 'type') && value.type === 'String' && HasPropertyKey(value, 'options') && IsArrayValue(value.options);
}
/** Returns true if the value is a Tuple Parser */
function IsTuple(value) {
return IsObjectValue(value) && HasPropertyKey(value, 'type') && value.type === 'Tuple' && HasPropertyKey(value, 'parsers') && IsArrayValue(value.parsers);
}
/** Returns true if the value is a Union Parser */
function IsUnion(value) {
return IsObjectValue(value) && HasPropertyKey(value, 'type') && value.type === 'Union' && HasPropertyKey(value, 'parsers') && IsArrayValue(value.parsers);
}
/** Returns true if the value is a Parser */
function IsParser(value) {
// prettier-ignore
return (IsArray(value) ||
IsConst(value) ||
IsContext(value) ||
IsIdent(value) ||
IsNumber(value) ||
IsOptional(value) ||
IsRef(value) ||
IsString(value) ||
IsTuple(value) ||
IsUnion(value));
}
@@ -0,0 +1,5 @@
export * as Guard from './guard';
export * as Token from './token';
export * from './types';
export * from './module';
export * from './parse';
@@ -0,0 +1,45 @@
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
var ownKeys = function(o) {
ownKeys = Object.getOwnPropertyNames || function (o) {
var ar = [];
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
return ar;
};
return ownKeys(o);
};
return function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
__setModuleDefault(result, mod);
return result;
};
})();
var __exportStar = (this && this.__exportStar) || function(m, exports) {
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.Token = exports.Guard = void 0;
exports.Guard = __importStar(require("./guard"));
exports.Token = __importStar(require("./token"));
__exportStar(require("./types"), exports);
__exportStar(require("./module"), exports);
__exportStar(require("./parse"), exports);
@@ -0,0 +1,9 @@
import * as Types from './types';
export declare class Module<Properties extends Types.IModuleProperties = Types.IModuleProperties> {
private readonly properties;
constructor(properties: Properties);
/** Parses using one of the parsers defined on this instance */
Parse<Key extends keyof Properties>(key: Key, content: string, context: unknown): [] | [Types.StaticParser<Properties[Key]>, string];
/** Parses using one of the parsers defined on this instance */
Parse<Key extends keyof Properties>(key: Key, content: string): [] | [Types.StaticParser<Properties[Key]>, string];
}
@@ -0,0 +1,22 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Module = void 0;
const parse_1 = require("./parse");
// ------------------------------------------------------------------
// Module
// ------------------------------------------------------------------
class Module {
constructor(properties) {
this.properties = properties;
}
/** Parses using one of the parsers defined on this instance */
Parse(...args) {
// prettier-ignore
const [key, content, context] = (args.length === 3 ? [args[0], args[1], args[2]] :
args.length === 2 ? [args[0], args[1], undefined] :
(() => { throw Error('Invalid parse arguments'); })());
return (0, parse_1.Parse)(this.properties, this.properties[key], content, context);
}
}
exports.Module = Module;
@@ -0,0 +1,9 @@
import * as Types from './types';
/** Parses content using the given Parser */
export declare function Parse<Parser extends Types.IParser>(moduleProperties: Types.IModuleProperties, parser: Parser, code: string, context: unknown): [] | [Types.StaticParser<Parser>, string];
/** Parses content using the given Parser */
export declare function Parse<Parser extends Types.IParser>(moduleProperties: Types.IModuleProperties, parser: Parser, code: string): [] | [Types.StaticParser<Parser>, string];
/** Parses content using the given Parser */
export declare function Parse<Parser extends Types.IParser>(parser: Parser, content: string, context: unknown): [] | [Types.StaticParser<Parser>, string];
/** Parses content using the given Parser */
export declare function Parse<Parser extends Types.IParser>(parser: Parser, content: string): [] | [Types.StaticParser<Parser>, string];
@@ -0,0 +1,160 @@
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
var ownKeys = function(o) {
ownKeys = Object.getOwnPropertyNames || function (o) {
var ar = [];
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
return ar;
};
return ownKeys(o);
};
return function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
__setModuleDefault(result, mod);
return result;
};
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.Parse = Parse;
const Guard = __importStar(require("./guard"));
const Token = __importStar(require("./token"));
// ------------------------------------------------------------------
// Context
// ------------------------------------------------------------------
function ParseContext(moduleProperties, left, right, code, context) {
const result = ParseParser(moduleProperties, left, code, context);
return result.length === 2 ? ParseParser(moduleProperties, right, result[1], result[0]) : [];
}
// ------------------------------------------------------------------
// Array
// ------------------------------------------------------------------
function ParseArray(moduleProperties, parser, code, context) {
const buffer = [];
let rest = code;
while (rest.length > 0) {
const result = ParseParser(moduleProperties, parser, rest, context);
if (result.length === 0)
return [buffer, rest];
buffer.push(result[0]);
rest = result[1];
}
return [buffer, rest];
}
// ------------------------------------------------------------------
// Const
// ------------------------------------------------------------------
function ParseConst(value, code, context) {
return Token.Const(value, code);
}
// ------------------------------------------------------------------
// Ident
// ------------------------------------------------------------------
function ParseIdent(code, _context) {
return Token.Ident(code);
}
// ------------------------------------------------------------------
// Number
// ------------------------------------------------------------------
// prettier-ignore
function ParseNumber(code, _context) {
return Token.Number(code);
}
// ------------------------------------------------------------------
// Optional
// ------------------------------------------------------------------
function ParseOptional(moduleProperties, parser, code, context) {
const result = ParseParser(moduleProperties, parser, code, context);
return (result.length === 2 ? [[result[0]], result[1]] : [[], code]);
}
// ------------------------------------------------------------------
// Ref
// ------------------------------------------------------------------
function ParseRef(moduleProperties, ref, code, context) {
const parser = moduleProperties[ref];
if (!Guard.IsParser(parser))
throw Error(`Cannot dereference Parser '${ref}'`);
return ParseParser(moduleProperties, parser, code, context);
}
// ------------------------------------------------------------------
// String
// ------------------------------------------------------------------
// prettier-ignore
function ParseString(options, code, _context) {
return Token.String(options, code);
}
// ------------------------------------------------------------------
// Tuple
// ------------------------------------------------------------------
function ParseTuple(moduleProperties, parsers, code, context) {
const buffer = [];
let rest = code;
for (const parser of parsers) {
const result = ParseParser(moduleProperties, parser, rest, context);
if (result.length === 0)
return [];
buffer.push(result[0]);
rest = result[1];
}
return [buffer, rest];
}
// ------------------------------------------------------------------
// Union
// ------------------------------------------------------------------
// prettier-ignore
function ParseUnion(moduleProperties, parsers, code, context) {
for (const parser of parsers) {
const result = ParseParser(moduleProperties, parser, code, context);
if (result.length === 0)
continue;
return result;
}
return [];
}
// ------------------------------------------------------------------
// Parser
// ------------------------------------------------------------------
// prettier-ignore
function ParseParser(moduleProperties, parser, code, context) {
const result = (Guard.IsContext(parser) ? ParseContext(moduleProperties, parser.left, parser.right, code, context) :
Guard.IsArray(parser) ? ParseArray(moduleProperties, parser.parser, code, context) :
Guard.IsConst(parser) ? ParseConst(parser.value, code, context) :
Guard.IsIdent(parser) ? ParseIdent(code, context) :
Guard.IsNumber(parser) ? ParseNumber(code, context) :
Guard.IsOptional(parser) ? ParseOptional(moduleProperties, parser.parser, code, context) :
Guard.IsRef(parser) ? ParseRef(moduleProperties, parser.ref, code, context) :
Guard.IsString(parser) ? ParseString(parser.options, code, context) :
Guard.IsTuple(parser) ? ParseTuple(moduleProperties, parser.parsers, code, context) :
Guard.IsUnion(parser) ? ParseUnion(moduleProperties, parser.parsers, code, context) :
[]);
return (result.length === 2
? [parser.mapping(result[0], context), result[1]]
: result);
}
/** Parses content using the given parser */
// prettier-ignore
function Parse(...args) {
const withModuleProperties = typeof args[1] === 'string' ? false : true;
const [moduleProperties, parser, content, context] = withModuleProperties
? [args[0], args[1], args[2], args[3]]
: [{}, args[0], args[1], args[2]];
return ParseParser(moduleProperties, parser, content, context);
}
@@ -0,0 +1,8 @@
/** Takes the next constant string value skipping any whitespace */
export declare function Const(value: string, code: string): [] | [string, string];
/** Scans for the next Ident token */
export declare function Ident(code: string): [] | [string, string];
/** Scans for the next number token */
export declare function Number(code: string): [string, string] | [];
/** Scans the next Literal String value */
export declare function String(options: string[], code: string): [string, string] | [];
@@ -0,0 +1,230 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Const = Const;
exports.Ident = Ident;
exports.Number = Number;
exports.String = String;
// ------------------------------------------------------------------
// Chars
// ------------------------------------------------------------------
// prettier-ignore
var Chars;
(function (Chars) {
/** Returns true if the char code is a whitespace */
function IsWhitespace(value) {
return value === 32;
}
Chars.IsWhitespace = IsWhitespace;
/** Returns true if the char code is a newline */
function IsNewline(value) {
return value === 10;
}
Chars.IsNewline = IsNewline;
/** Returns true if the char code is a alpha */
function IsAlpha(value) {
return ((value >= 65 && value <= 90) || // A-Z
(value >= 97 && value <= 122) // a-z
);
}
Chars.IsAlpha = IsAlpha;
/** Returns true if the char code is zero */
function IsZero(value) {
return value === 48;
}
Chars.IsZero = IsZero;
/** Returns true if the char code is non-zero */
function IsNonZero(value) {
return value >= 49 && value <= 57;
}
Chars.IsNonZero = IsNonZero;
/** Returns true if the char code is a digit */
function IsDigit(value) {
return (IsNonZero(value) ||
IsZero(value));
}
Chars.IsDigit = IsDigit;
/** Returns true if the char code is a dot */
function IsDot(value) {
return value === 46;
}
Chars.IsDot = IsDot;
/** Returns true if this char code is a underscore */
function IsUnderscore(value) {
return value === 95;
}
Chars.IsUnderscore = IsUnderscore;
/** Returns true if this char code is a dollar sign */
function IsDollarSign(value) {
return value === 36;
}
Chars.IsDollarSign = IsDollarSign;
})(Chars || (Chars = {}));
// ------------------------------------------------------------------
// Trim
// ------------------------------------------------------------------
// prettier-ignore
var Trim;
(function (Trim) {
/** Trims Whitespace and retains Newline, Tabspaces, etc. */
function TrimWhitespaceOnly(code) {
for (let i = 0; i < code.length; i++) {
if (Chars.IsWhitespace(code.charCodeAt(i)))
continue;
return code.slice(i);
}
return code;
}
Trim.TrimWhitespaceOnly = TrimWhitespaceOnly;
/** Trims Whitespace including Newline, Tabspaces, etc. */
function TrimAll(code) {
return code.trimStart();
}
Trim.TrimAll = TrimAll;
})(Trim || (Trim = {}));
// ------------------------------------------------------------------
// Const
// ------------------------------------------------------------------
/** Checks the value matches the next string */
// prettier-ignore
function NextTokenCheck(value, code) {
if (value.length > code.length)
return false;
for (let i = 0; i < value.length; i++) {
if (value.charCodeAt(i) !== code.charCodeAt(i))
return false;
}
return true;
}
/** Gets the next constant string value or empty if no match */
// prettier-ignore
function NextConst(value, code) {
return NextTokenCheck(value, code)
? [code.slice(0, value.length), code.slice(value.length)]
: [];
}
/** Takes the next constant string value skipping any whitespace */
// prettier-ignore
function Const(value, code) {
if (value.length === 0)
return ['', code];
const char_0 = value.charCodeAt(0);
return (Chars.IsNewline(char_0) ? NextConst(value, Trim.TrimWhitespaceOnly(code)) :
Chars.IsWhitespace(char_0) ? NextConst(value, code) :
NextConst(value, Trim.TrimAll(code)));
}
// ------------------------------------------------------------------
// Ident
// ------------------------------------------------------------------
// prettier-ignore
function IdentIsFirst(char) {
return (Chars.IsAlpha(char) ||
Chars.IsDollarSign(char) ||
Chars.IsUnderscore(char));
}
// prettier-ignore
function IdentIsRest(char) {
return (Chars.IsAlpha(char) ||
Chars.IsDigit(char) ||
Chars.IsDollarSign(char) ||
Chars.IsUnderscore(char));
}
// prettier-ignore
function NextIdent(code) {
if (!IdentIsFirst(code.charCodeAt(0)))
return [];
for (let i = 1; i < code.length; i++) {
const char = code.charCodeAt(i);
if (IdentIsRest(char))
continue;
const slice = code.slice(0, i);
const rest = code.slice(i);
return [slice, rest];
}
return [code, ''];
}
/** Scans for the next Ident token */
// prettier-ignore
function Ident(code) {
return NextIdent(Trim.TrimAll(code));
}
// ------------------------------------------------------------------
// Number
// ------------------------------------------------------------------
/** Checks that the next number is not a leading zero */
// prettier-ignore
function NumberLeadingZeroCheck(code, index) {
const char_0 = code.charCodeAt(index + 0);
const char_1 = code.charCodeAt(index + 1);
return ((
// 1-9
Chars.IsNonZero(char_0)) || (
// 0
Chars.IsZero(char_0) &&
!Chars.IsDigit(char_1)) || (
// 0.
Chars.IsZero(char_0) &&
Chars.IsDot(char_1)) || (
// .0
Chars.IsDot(char_0) &&
Chars.IsDigit(char_1)));
}
/** Gets the next number token */
// prettier-ignore
function NextNumber(code) {
const negated = code.charAt(0) === '-';
const index = negated ? 1 : 0;
if (!NumberLeadingZeroCheck(code, index)) {
return [];
}
const dash = negated ? '-' : '';
let hasDot = false;
for (let i = index; i < code.length; i++) {
const char_i = code.charCodeAt(i);
if (Chars.IsDigit(char_i)) {
continue;
}
if (Chars.IsDot(char_i)) {
if (hasDot) {
const slice = code.slice(index, i);
const rest = code.slice(i);
return [`${dash}${slice}`, rest];
}
hasDot = true;
continue;
}
const slice = code.slice(index, i);
const rest = code.slice(i);
return [`${dash}${slice}`, rest];
}
return [code, ''];
}
/** Scans for the next number token */
// prettier-ignore
function Number(code) {
return NextNumber(Trim.TrimAll(code));
}
// ------------------------------------------------------------------
// String
// ------------------------------------------------------------------
// prettier-ignore
function NextString(options, code) {
const first = code.charAt(0);
if (!options.includes(first))
return [];
const quote = first;
for (let i = 1; i < code.length; i++) {
const char = code.charAt(i);
if (char === quote) {
const slice = code.slice(1, i);
const rest = code.slice(i + 1);
return [slice, rest];
}
}
return [];
}
/** Scans the next Literal String value */
// prettier-ignore
function String(options, code) {
return NextString(options, Trim.TrimAll(code));
}
@@ -0,0 +1,98 @@
export type IModuleProperties = Record<PropertyKey, IParser>;
/** Force output static type evaluation for Arrays */
export type StaticEnsure<T> = T extends infer R ? R : never;
/** Infers the Output Parameter for a Parser */
export type StaticParser<Parser extends IParser> = Parser extends IParser<infer Output extends unknown> ? Output : unknown;
export type IMapping<Input extends unknown = any, Output extends unknown = unknown> = (input: Input, context: any) => Output;
/** Maps input to output. This is the default Mapping */
export declare const Identity: (value: unknown) => unknown;
/** Maps the output as the given parameter T */
export declare const As: <T>(mapping: T) => ((value: unknown) => T);
export interface IParser<Output extends unknown = unknown> {
type: string;
mapping: IMapping<any, Output>;
}
export type ContextParameter<_Left extends IParser, Right extends IParser> = (StaticParser<Right>);
export interface IContext<Output extends unknown = unknown> extends IParser<Output> {
type: 'Context';
left: IParser;
right: IParser;
}
/** `[Context]` Creates a Context Parser */
export declare function Context<Left extends IParser, Right extends IParser, Mapping extends IMapping = IMapping<ContextParameter<Left, Right>>>(left: Left, right: Right, mapping: Mapping): IContext<ReturnType<Mapping>>;
/** `[Context]` Creates a Context Parser */
export declare function Context<Left extends IParser, Right extends IParser>(left: Left, right: Right): IContext<ContextParameter<Left, Right>>;
export type ArrayParameter<Parser extends IParser> = StaticEnsure<StaticParser<Parser>[]>;
export interface IArray<Output extends unknown = unknown> extends IParser<Output> {
type: 'Array';
parser: IParser;
}
/** `[EBNF]` Creates an Array Parser */
export declare function Array<Parser extends IParser, Mapping extends IMapping = IMapping<ArrayParameter<Parser>>>(parser: Parser, mapping: Mapping): IArray<ReturnType<Mapping>>;
/** `[EBNF]` Creates an Array Parser */
export declare function Array<Parser extends IParser>(parser: Parser): IArray<ArrayParameter<Parser>>;
export interface IConst<Output extends unknown = unknown> extends IParser<Output> {
type: 'Const';
value: string;
}
/** `[TERM]` Creates a Const Parser */
export declare function Const<Value extends string, Mapping extends IMapping<Value>>(value: Value, mapping: Mapping): IConst<ReturnType<Mapping>>;
/** `[TERM]` Creates a Const Parser */
export declare function Const<Value extends string>(value: Value): IConst<Value>;
export interface IRef<Output extends unknown = unknown> extends IParser<Output> {
type: 'Ref';
ref: string;
}
/** `[BNF]` Creates a Ref Parser. This Parser can only be used in the context of a Module */
export declare function Ref<Type extends unknown, Mapping extends IMapping<Type>>(ref: string, mapping: Mapping): IRef<ReturnType<Mapping>>;
/** `[BNF]` Creates a Ref Parser. This Parser can only be used in the context of a Module */
export declare function Ref<Type extends unknown>(ref: string): IRef<Type>;
export interface IString<Output extends unknown = unknown> extends IParser<Output> {
type: 'String';
options: string[];
}
/** `[TERM]` Creates a String Parser. Options are an array of permissable quote characters */
export declare function String<Mapping extends IMapping<string>>(options: string[], mapping: Mapping): IString<ReturnType<Mapping>>;
/** `[TERM]` Creates a String Parser. Options are an array of permissable quote characters */
export declare function String(options: string[]): IString<string>;
export interface IIdent<Output extends unknown = unknown> extends IParser<Output> {
type: 'Ident';
}
/** `[TERM]` Creates an Ident Parser where Ident matches any valid JavaScript identifier */
export declare function Ident<Mapping extends IMapping<string>>(mapping: Mapping): IIdent<ReturnType<Mapping>>;
/** `[TERM]` Creates an Ident Parser where Ident matches any valid JavaScript identifier */
export declare function Ident(): IIdent<string>;
export interface INumber<Output extends unknown = unknown> extends IParser<Output> {
type: 'Number';
}
/** `[TERM]` Creates an Number Parser */
export declare function Number<Mapping extends IMapping<string>>(mapping: Mapping): INumber<ReturnType<Mapping>>;
/** `[TERM]` Creates an Number Parser */
export declare function Number(): INumber<string>;
export type OptionalParameter<Parser extends IParser, Result extends unknown = [StaticParser<Parser>] | []> = (Result);
export interface IOptional<Output extends unknown = unknown> extends IParser<Output> {
type: 'Optional';
parser: IParser;
}
/** `[EBNF]` Creates an Optional Parser */
export declare function Optional<Parser extends IParser, Mapping extends IMapping = IMapping<OptionalParameter<Parser>>>(parser: Parser, mapping: Mapping): IOptional<ReturnType<Mapping>>;
/** `[EBNF]` Creates an Optional Parser */
export declare function Optional<Parser extends IParser>(parser: Parser): IOptional<OptionalParameter<Parser>>;
export type TupleParameter<Parsers extends IParser[], Result extends unknown[] = []> = StaticEnsure<Parsers extends [infer Left extends IParser, ...infer Right extends IParser[]] ? TupleParameter<Right, [...Result, StaticEnsure<StaticParser<Left>>]> : Result>;
export interface ITuple<Output extends unknown = unknown> extends IParser<Output> {
type: 'Tuple';
parsers: IParser[];
}
/** `[BNF]` Creates a Tuple Parser */
export declare function Tuple<Parsers extends IParser[], Mapping extends IMapping = IMapping<TupleParameter<Parsers>>>(parsers: [...Parsers], mapping: Mapping): ITuple<ReturnType<Mapping>>;
/** `[BNF]` Creates a Tuple Parser */
export declare function Tuple<Parsers extends IParser[]>(parsers: [...Parsers]): ITuple<TupleParameter<Parsers>>;
export type UnionParameter<Parsers extends IParser[], Result extends unknown = never> = StaticEnsure<Parsers extends [infer Left extends IParser, ...infer Right extends IParser[]] ? UnionParameter<Right, Result | StaticParser<Left>> : Result>;
export interface IUnion<Output extends unknown = unknown> extends IParser<Output> {
type: 'Union';
parsers: IParser[];
}
/** `[BNF]` Creates a Union parser */
export declare function Union<Parsers extends IParser[], Mapping extends IMapping = IMapping<UnionParameter<Parsers>>>(parsers: [...Parsers], mapping: Mapping): IUnion<ReturnType<Mapping>>;
/** `[BNF]` Creates a Union parser */
export declare function Union<Parsers extends IParser[]>(parsers: [...Parsers]): IUnion<UnionParameter<Parsers>>;
@@ -0,0 +1,71 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.As = exports.Identity = void 0;
exports.Context = Context;
exports.Array = Array;
exports.Const = Const;
exports.Ref = Ref;
exports.String = String;
exports.Ident = Ident;
exports.Number = Number;
exports.Optional = Optional;
exports.Tuple = Tuple;
exports.Union = Union;
/** Maps input to output. This is the default Mapping */
const Identity = (value) => value;
exports.Identity = Identity;
/** Maps the output as the given parameter T */
// prettier-ignore
const As = (mapping) => (_) => mapping;
exports.As = As;
/** `[Context]` Creates a Context Parser */
function Context(...args) {
const [left, right, mapping] = args.length === 3 ? [args[0], args[1], args[2]] : [args[0], args[1], exports.Identity];
return { type: 'Context', left, right, mapping };
}
/** `[EBNF]` Creates an Array Parser */
function Array(...args) {
const [parser, mapping] = args.length === 2 ? [args[0], args[1]] : [args[0], exports.Identity];
return { type: 'Array', parser, mapping };
}
/** `[TERM]` Creates a Const Parser */
function Const(...args) {
const [value, mapping] = args.length === 2 ? [args[0], args[1]] : [args[0], exports.Identity];
return { type: 'Const', value, mapping };
}
/** `[BNF]` Creates a Ref Parser. This Parser can only be used in the context of a Module */
function Ref(...args) {
const [ref, mapping] = args.length === 2 ? [args[0], args[1]] : [args[0], exports.Identity];
return { type: 'Ref', ref, mapping };
}
/** `[TERM]` Creates a String Parser. Options are an array of permissable quote characters */
function String(...params) {
const [options, mapping] = params.length === 2 ? [params[0], params[1]] : [params[0], exports.Identity];
return { type: 'String', options, mapping };
}
/** `[TERM]` Creates an Ident Parser where Ident matches any valid JavaScript identifier */
function Ident(...params) {
const mapping = params.length === 1 ? params[0] : exports.Identity;
return { type: 'Ident', mapping };
}
/** `[TERM]` Creates an Number Parser */
function Number(...params) {
const mapping = params.length === 1 ? params[0] : exports.Identity;
return { type: 'Number', mapping };
}
/** `[EBNF]` Creates an Optional Parser */
function Optional(...args) {
const [parser, mapping] = args.length === 2 ? [args[0], args[1]] : [args[0], exports.Identity];
return { type: 'Optional', parser, mapping };
}
/** `[BNF]` Creates a Tuple Parser */
function Tuple(...args) {
const [parsers, mapping] = args.length === 2 ? [args[0], args[1]] : [args[0], exports.Identity];
return { type: 'Tuple', parsers, mapping };
}
/** `[BNF]` Creates a Union parser */
function Union(...args) {
const [parsers, mapping] = args.length === 2 ? [args[0], args[1]] : [args[0], exports.Identity];
return { type: 'Union', parsers, mapping };
}
@@ -0,0 +1,3 @@
export * as Token from './token';
export * from './parse';
export * from './types';
@@ -0,0 +1,43 @@
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
var ownKeys = function(o) {
ownKeys = Object.getOwnPropertyNames || function (o) {
var ar = [];
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
return ar;
};
return ownKeys(o);
};
return function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
__setModuleDefault(result, mod);
return result;
};
})();
var __exportStar = (this && this.__exportStar) || function(m, exports) {
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.Token = void 0;
exports.Token = __importStar(require("./token"));
__exportStar(require("./parse"), exports);
__exportStar(require("./types"), exports);
@@ -0,0 +1,20 @@
import * as Tokens from './token';
import * as Types from './types';
type ContextParser<Left extends Types.IParser, Right extends Types.IParser, Code extends string, Context extends unknown> = (Parse<Left, Code, Context> extends [infer Context extends unknown, infer Rest extends string] ? Parse<Right, Rest, Context> : []);
type ArrayParser<Parser extends Types.IParser, Code extends string, Context extends unknown, Result extends unknown[] = []> = (Parse<Parser, Code, Context> extends [infer Value1 extends unknown, infer Rest extends string] ? ArrayParser<Parser, Rest, Context, [...Result, Value1]> : [Result, Code]);
type ConstParser<Value extends string, Code extends string, _Context extends unknown> = (Tokens.Const<Value, Code> extends [infer Match extends Value, infer Rest extends string] ? [Match, Rest] : []);
type IdentParser<Code extends string, _Context extends unknown> = (Tokens.Ident<Code> extends [infer Match extends string, infer Rest extends string] ? [Match, Rest] : []);
type NumberParser<Code extends string, _Context extends unknown> = (Tokens.Number<Code> extends [infer Match extends string, infer Rest extends string] ? [Match, Rest] : []);
type OptionalParser<Parser extends Types.IParser, Code extends string, Context extends unknown> = (Parse<Parser, Code, Context> extends [infer Value extends unknown, infer Rest extends string] ? [[Value], Rest] : [[], Code]);
type StringParser<Options extends string[], Code extends string, _Context extends unknown> = (Tokens.String<Options, Code> extends [infer Match extends string, infer Rest extends string] ? [Match, Rest] : []);
type TupleParser<Parsers extends Types.IParser[], Code extends string, Context extends unknown, Result extends unknown[] = []> = (Parsers extends [infer Left extends Types.IParser, ...infer Right extends Types.IParser[]] ? Parse<Left, Code, Context> extends [infer Value extends unknown, infer Rest extends string] ? TupleParser<Right, Rest, Context, [...Result, Value]> : [] : [Result, Code]);
type UnionParser<Parsers extends Types.IParser[], Code extends string, Context extends unknown> = (Parsers extends [infer Left extends Types.IParser, ...infer Right extends Types.IParser[]] ? Parse<Left, Code, Context> extends [infer Value extends unknown, infer Rest extends string] ? [Value, Rest] : UnionParser<Right, Code, Context> : []);
type ParseCode<Type extends Types.IParser, Code extends string, Context extends unknown = unknown> = (Type extends Types.Context<infer Left extends Types.IParser, infer Right extends Types.IParser> ? ContextParser<Left, Right, Code, Context> : Type extends Types.Array<infer Parser extends Types.IParser> ? ArrayParser<Parser, Code, Context> : Type extends Types.Const<infer Value extends string> ? ConstParser<Value, Code, Context> : Type extends Types.Ident ? IdentParser<Code, Context> : Type extends Types.Number ? NumberParser<Code, Context> : Type extends Types.Optional<infer Parser extends Types.IParser> ? OptionalParser<Parser, Code, Context> : Type extends Types.String<infer Options extends string[]> ? StringParser<Options, Code, Context> : Type extends Types.Tuple<infer Parsers extends Types.IParser[]> ? TupleParser<Parsers, Code, Context> : Type extends Types.Union<infer Parsers extends Types.IParser[]> ? UnionParser<Parsers, Code, Context> : [
]);
type ParseMapping<Parser extends Types.IParser, Result extends unknown, Context extends unknown = unknown> = ((Parser['mapping'] & {
input: Result;
context: Context;
})['output']);
/** Parses code with the given parser */
export type Parse<Type extends Types.IParser, Code extends string, Context extends unknown = unknown> = (ParseCode<Type, Code, Context> extends [infer L extends unknown, infer R extends string] ? [ParseMapping<Type, L, Context>, R] : []);
export {};
@@ -0,0 +1,3 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1,108 @@
declare namespace Chars {
type Empty = '';
type Space = ' ';
type Newline = '\n';
type Dot = '.';
type Hyphen = '-';
type Digit = [
'0',
'1',
'2',
'3',
'4',
'5',
'6',
'7',
'8',
'9'
];
type Alpha = [
'a',
'b',
'c',
'd',
'e',
'f',
'g',
'h',
'i',
'j',
'k',
'l',
'm',
'n',
'o',
'p',
'q',
'r',
's',
't',
'u',
'v',
'w',
'x',
'y',
'z',
'A',
'B',
'C',
'D',
'E',
'F',
'G',
'H',
'I',
'J',
'K',
'L',
'M',
'N',
'O',
'P',
'Q',
'R',
'S',
'T',
'U',
'V',
'W',
'X',
'Y',
'Z'
];
}
declare namespace Trim {
type W4 = `${W3}${W3}`;
type W3 = `${W2}${W2}`;
type W2 = `${W1}${W1}`;
type W1 = `${W0}${W0}`;
type W0 = ` `;
/** Trims whitespace only */
export type TrimWhitespace<Code extends string> = (Code extends `${W4}${infer Rest extends string}` ? TrimWhitespace<Rest> : Code extends `${W3}${infer Rest extends string}` ? TrimWhitespace<Rest> : Code extends `${W1}${infer Rest extends string}` ? TrimWhitespace<Rest> : Code extends `${W0}${infer Rest extends string}` ? TrimWhitespace<Rest> : Code);
/** Trims Whitespace and Newline */
export type TrimAll<Code extends string> = (Code extends `${W4}${infer Rest extends string}` ? TrimAll<Rest> : Code extends `${W3}${infer Rest extends string}` ? TrimAll<Rest> : Code extends `${W1}${infer Rest extends string}` ? TrimAll<Rest> : Code extends `${W0}${infer Rest extends string}` ? TrimAll<Rest> : Code extends `${Chars.Newline}${infer Rest extends string}` ? TrimAll<Rest> : Code);
export {};
}
/** Scans for the next match union */
type NextUnion<Variants extends string[], Code extends string> = (Variants extends [infer Variant extends string, ...infer Rest1 extends string[]] ? NextConst<Variant, Code> extends [infer Match extends string, infer Rest2 extends string] ? [Match, Rest2] : NextUnion<Rest1, Code> : []);
type NextConst<Value extends string, Code extends string> = (Code extends `${Value}${infer Rest extends string}` ? [Value, Rest] : []);
/** Scans for the next constant value */
export type Const<Value extends string, Code extends string> = (Value extends '' ? ['', Code] : Value extends `${infer First extends string}${string}` ? (First extends Chars.Newline ? NextConst<Value, Trim.TrimWhitespace<Code>> : First extends Chars.Space ? NextConst<Value, Code> : NextConst<Value, Trim.TrimAll<Code>>) : never);
type NextNumberNegate<Code extends string> = (Code extends `${Chars.Hyphen}${infer Rest extends string}` ? [Chars.Hyphen, Rest] : [Chars.Empty, Code]);
type NextNumberZeroCheck<Code extends string> = (Code extends `0${infer Rest}` ? NextUnion<Chars.Digit, Rest> extends [string, string] ? false : true : true);
type NextNumberScan<Code extends string, HasDecimal extends boolean = false, Result extends string = Chars.Empty> = (NextUnion<[...Chars.Digit, Chars.Dot], Code> extends [infer Char extends string, infer Rest extends string] ? Char extends Chars.Dot ? HasDecimal extends false ? NextNumberScan<Rest, true, `${Result}${Char}`> : [Result, `.${Rest}`] : NextNumberScan<Rest, HasDecimal, `${Result}${Char}`> : [Result, Code]);
export type NextNumber<Code extends string> = (NextNumberNegate<Code> extends [infer Negate extends string, infer Rest extends string] ? NextNumberZeroCheck<Rest> extends true ? NextNumberScan<Rest> extends [infer Number extends string, infer Rest2 extends string] ? Number extends Chars.Empty ? [] : [`${Negate}${Number}`, Rest2] : [] : [] : []);
/** Scans for the next literal number */
export type Number<Code extends string> = NextNumber<Trim.TrimAll<Code>>;
type NextStringQuote<Options extends string[], Code extends string> = NextUnion<Options, Code>;
type NextStringBody<Code extends string, Quote extends string, Result extends string = Chars.Empty> = (Code extends `${infer Char extends string}${infer Rest extends string}` ? Char extends Quote ? [Result, Rest] : NextStringBody<Rest, Quote, `${Result}${Char}`> : []);
type NextString<Options extends string[], Code extends string> = (NextStringQuote<Options, Code> extends [infer Quote extends string, infer Rest extends string] ? NextStringBody<Rest, Quote> extends [infer String extends string, infer Rest extends string] ? [String, Rest] : [] : []);
/** Scans for the next literal string */
export type String<Options extends string[], Code extends string> = NextString<Options, Trim.TrimAll<Code>>;
type IdentLeft = [...Chars.Alpha, '_', '$'];
type IdentRight = [...Chars.Digit, ...IdentLeft];
type NextIdentScan<Code extends string, Result extends string = Chars.Empty> = (NextUnion<IdentRight, Code> extends [infer Char extends string, infer Rest extends string] ? NextIdentScan<Rest, `${Result}${Char}`> : [Result, Code]);
type NextIdent<Code extends string> = (NextUnion<IdentLeft, Code> extends [infer Left extends string, infer Rest1 extends string] ? NextIdentScan<Rest1> extends [infer Right extends string, infer Rest2 extends string] ? [`${Left}${Right}`, Rest2] : [] : []);
/** Scans for the next Ident */
export type Ident<Code extends string> = NextIdent<Trim.TrimAll<Code>>;
export {};
@@ -0,0 +1,3 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1,69 @@
/**
* `[ACTION]` Inference mapping base type. Used to specify semantic actions for
* Parser productions. This type is implemented as a higher-kinded type where
* productions are received on the `input` property with mapping assigned
* the `output` property. The parsing context is available on the `context`
* property.
*/
export interface IMapping {
context: unknown;
input: unknown;
output: unknown;
}
/** `[ACTION]` Default inference mapping. */
export interface Identity extends IMapping {
output: this['input'];
}
/** `[ACTION]` Maps the given argument `T` as the mapping output */
export interface As<T> extends IMapping {
output: T;
}
/** Base type Parser implemented by all other parsers */
export interface IParser<Mapping extends IMapping = Identity> {
type: string;
mapping: Mapping;
}
/** `[Context]` Creates a Context Parser */
export interface Context<Left extends IParser = IParser, Right extends IParser = IParser, Mapping extends IMapping = Identity> extends IParser<Mapping> {
type: 'Context';
left: Left;
right: Right;
}
/** `[EBNF]` Creates an Array Parser */
export interface Array<Parser extends IParser = IParser, Mapping extends IMapping = Identity> extends IParser<Mapping> {
type: 'Array';
parser: Parser;
}
/** `[TERM]` Creates a Const Parser */
export interface Const<Value extends string = string, Mapping extends IMapping = Identity> extends IParser<Mapping> {
type: 'Const';
value: Value;
}
/** `[TERM]` Creates an Ident Parser. */
export interface Ident<Mapping extends IMapping = Identity> extends IParser<Mapping> {
type: 'Ident';
}
/** `[TERM]` Creates a Number Parser. */
export interface Number<Mapping extends IMapping = Identity> extends IParser<Mapping> {
type: 'Number';
}
/** `[EBNF]` Creates a Optional Parser */
export interface Optional<Parser extends IParser = IParser, Mapping extends IMapping = Identity> extends IParser<Mapping> {
type: 'Optional';
parser: Parser;
}
/** `[TERM]` Creates a String Parser. Options are an array of permissable quote characters */
export interface String<Options extends string[], Mapping extends IMapping = Identity> extends IParser<Mapping> {
type: 'String';
quote: Options;
}
/** `[BNF]` Creates a Tuple Parser */
export interface Tuple<Parsers extends IParser[] = [], Mapping extends IMapping = Identity> extends IParser<Mapping> {
type: 'Tuple';
parsers: [...Parsers];
}
/** `[BNF]` Creates a Union Parser */
export interface Union<Parsers extends IParser[] = [], Mapping extends IMapping = Identity> extends IParser<Mapping> {
type: 'Union';
parsers: [...Parsers];
}
@@ -0,0 +1,3 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1 @@
export * from './syntax';
+18
View File
@@ -0,0 +1,18 @@
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __exportStar = (this && this.__exportStar) || function(m, exports) {
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
Object.defineProperty(exports, "__esModule", { value: true });
__exportStar(require("./syntax"), exports);
@@ -0,0 +1,167 @@
import * as T from '../type/index';
type TDereference<Context extends T.TProperties, Key extends string> = (Key extends keyof Context ? Context[Key] : T.TRef<Key>);
type TDelimitedDecode<Input extends ([unknown, unknown] | unknown)[], Result extends unknown[] = []> = (Input extends [infer Left, ...infer Right] ? Left extends [infer Item, infer _] ? TDelimitedDecode<Right, [...Result, Item]> : TDelimitedDecode<Right, [...Result, Left]> : Result);
type TDelimited<Input extends [unknown, unknown]> = Input extends [infer Left extends unknown[], infer Right extends unknown[]] ? TDelimitedDecode<[...Left, ...Right]> : [];
export type TGenericReferenceParameterListMapping<Input extends [unknown, unknown], Context extends T.TProperties> = TDelimited<Input>;
export declare function GenericReferenceParameterListMapping(input: [unknown, unknown], context: unknown): unknown[];
export type TGenericReferenceMapping<Input extends [unknown, unknown, unknown, unknown], Context extends T.TProperties, Result = Context extends T.TProperties ? Input extends [infer Reference extends string, '<', infer Args extends T.TSchema[], '>'] ? T.TInstantiate<TDereference<Context, Reference>, Args> : never : never> = Result;
export declare function GenericReferenceMapping(input: [unknown, unknown, unknown, unknown], context: unknown): T.TSchema;
export type TGenericArgumentsListMapping<Input extends [unknown, unknown], Context extends T.TProperties> = TDelimited<Input>;
export declare function GenericArgumentsListMapping(input: [unknown, unknown], context: unknown): unknown[];
type GenericArgumentsContext<Arguments extends string[], Context extends T.TProperties, Result extends T.TProperties = {}> = (Arguments extends [...infer Left extends string[], infer Right extends string] ? GenericArgumentsContext<Left, Context, Result & {
[_ in Right]: T.TArgument<Left['length']>;
}> : T.Evaluate<Result & Context>);
export type TGenericArgumentsMapping<Input extends [unknown, unknown, unknown], Context extends T.TProperties> = Input extends ['<', infer Arguments extends string[], '>'] ? Context extends infer Context extends T.TProperties ? GenericArgumentsContext<Arguments, Context> : never : never;
declare const GenericArgumentsContext: (_arguments: string[], context: T.TProperties) => T.TProperties;
export declare function GenericArgumentsMapping(input: [unknown, unknown, unknown], context: unknown): T.TProperties;
export type TKeywordStringMapping<Input extends 'string', Context extends T.TProperties> = T.TString;
export declare function KeywordStringMapping(input: 'string', context: unknown): T.TString;
export type TKeywordNumberMapping<Input extends 'number', Context extends T.TProperties> = T.TNumber;
export declare function KeywordNumberMapping(input: 'number', context: unknown): T.TNumber;
export type TKeywordBooleanMapping<Input extends 'boolean', Context extends T.TProperties> = T.TBoolean;
export declare function KeywordBooleanMapping(input: 'boolean', context: unknown): T.TBoolean;
export type TKeywordUndefinedMapping<Input extends 'undefined', Context extends T.TProperties> = T.TUndefined;
export declare function KeywordUndefinedMapping(input: 'undefined', context: unknown): T.TUndefined;
export type TKeywordNullMapping<Input extends 'null', Context extends T.TProperties> = T.TNull;
export declare function KeywordNullMapping(input: 'null', context: unknown): T.TNull;
export type TKeywordIntegerMapping<Input extends 'integer', Context extends T.TProperties> = T.TInteger;
export declare function KeywordIntegerMapping(input: 'integer', context: unknown): T.TInteger;
export type TKeywordBigIntMapping<Input extends 'bigint', Context extends T.TProperties> = T.TBigInt;
export declare function KeywordBigIntMapping(input: 'bigint', context: unknown): T.TBigInt;
export type TKeywordUnknownMapping<Input extends 'unknown', Context extends T.TProperties> = T.TUnknown;
export declare function KeywordUnknownMapping(input: 'unknown', context: unknown): T.TUnknown;
export type TKeywordAnyMapping<Input extends 'any', Context extends T.TProperties> = T.TAny;
export declare function KeywordAnyMapping(input: 'any', context: unknown): T.TAny;
export type TKeywordNeverMapping<Input extends 'never', Context extends T.TProperties> = T.TNever;
export declare function KeywordNeverMapping(input: 'never', context: unknown): T.TNever;
export type TKeywordSymbolMapping<Input extends 'symbol', Context extends T.TProperties> = T.TSymbol;
export declare function KeywordSymbolMapping(input: 'symbol', context: unknown): T.TSymbol;
export type TKeywordVoidMapping<Input extends 'void', Context extends T.TProperties> = T.TVoid;
export declare function KeywordVoidMapping(input: 'void', context: unknown): T.TVoid;
export type TKeywordMapping<Input extends unknown, Context extends T.TProperties> = Input;
export declare function KeywordMapping(input: unknown, context: unknown): unknown;
export type TLiteralStringMapping<Input extends string, Context extends T.TProperties> = Input extends T.TLiteralValue ? T.TLiteral<Input> : never;
export declare function LiteralStringMapping(input: string, context: unknown): T.TLiteral<string>;
export type TLiteralNumberMapping<Input extends string, Context extends T.TProperties> = Input extends `${infer Value extends number}` ? T.TLiteral<Value> : never;
export declare function LiteralNumberMapping(input: string, context: unknown): T.TLiteral<number>;
export type TLiteralBooleanMapping<Input extends 'true' | 'false', Context extends T.TProperties> = Input extends 'true' ? T.TLiteral<true> : T.TLiteral<false>;
export declare function LiteralBooleanMapping(input: 'true' | 'false', context: unknown): T.TLiteral<boolean>;
export type TLiteralMapping<Input extends unknown, Context extends T.TProperties> = Input;
export declare function LiteralMapping(input: unknown, context: unknown): unknown;
export type TKeyOfMapping<Input extends [unknown] | [], Context extends T.TProperties> = Input extends [unknown] ? true : false;
export declare function KeyOfMapping(input: [unknown] | [], context: unknown): boolean;
type TIndexArrayMappingReduce<Input extends unknown[], Result extends unknown[] = []> = (Input extends [infer Left extends unknown, ...infer Right extends unknown[]] ? Left extends ['[', infer Type extends T.TSchema, ']'] ? TIndexArrayMappingReduce<Right, [...Result, [Type]]> : TIndexArrayMappingReduce<Right, [...Result, []]> : Result);
export type TIndexArrayMapping<Input extends ([unknown, unknown, unknown] | [unknown, unknown])[], Context extends T.TProperties> = Input extends unknown[] ? TIndexArrayMappingReduce<Input> : [];
export declare function IndexArrayMapping(input: ([unknown, unknown, unknown] | [unknown, unknown])[], context: unknown): unknown[];
export type TExtendsMapping<Input extends [unknown, unknown, unknown, unknown, unknown, unknown] | [], Context extends T.TProperties> = Input extends ['extends', infer Type extends T.TSchema, '?', infer True extends T.TSchema, ':', infer False extends T.TSchema] ? [Type, True, False] : [];
export declare function ExtendsMapping(input: [unknown, unknown, unknown, unknown, unknown, unknown] | [], context: unknown): unknown[];
export type TBaseMapping<Input extends [unknown, unknown, unknown] | unknown, Context extends T.TProperties> = (Input extends ['(', infer Type extends T.TSchema, ')'] ? Type : Input extends infer Type extends T.TSchema ? Type : never);
export declare function BaseMapping(input: [unknown, unknown, unknown] | unknown, context: unknown): unknown;
type TFactorIndexArray<Type extends T.TSchema, IndexArray extends unknown[]> = (IndexArray extends [...infer Left extends unknown[], infer Right extends T.TSchema[]] ? (Right extends [infer Indexer extends T.TSchema] ? T.TIndex<TFactorIndexArray<Type, Left>, T.TIndexPropertyKeys<Indexer>> : Right extends [] ? T.TArray<TFactorIndexArray<Type, Left>> : T.TNever) : Type);
type TFactorExtends<Type extends T.TSchema, Extends extends unknown[]> = (Extends extends [infer Right extends T.TSchema, infer True extends T.TSchema, infer False extends T.TSchema] ? T.TExtends<Type, Right, True, False> : Type);
export type TFactorMapping<Input extends [unknown, unknown, unknown, unknown], Context extends T.TProperties> = Input extends [infer KeyOf extends boolean, infer Type extends T.TSchema, infer IndexArray extends unknown[], infer Extends extends unknown[]] ? KeyOf extends true ? TFactorExtends<T.TKeyOf<TFactorIndexArray<Type, IndexArray>>, Extends> : TFactorExtends<TFactorIndexArray<Type, IndexArray>, Extends> : never;
export declare function FactorMapping(input: [unknown, unknown, unknown, unknown], context: unknown): T.TSchema;
type TExprBinaryMapping<Left extends T.TSchema, Rest extends unknown[]> = (Rest extends [infer Operator extends unknown, infer Right extends T.TSchema, infer Next extends unknown[]] ? (TExprBinaryMapping<Right, Next> extends infer Schema extends T.TSchema ? (Operator extends '&' ? (Schema extends T.TIntersect<infer Types extends T.TSchema[]> ? T.TIntersect<[Left, ...Types]> : T.TIntersect<[Left, Schema]>) : Operator extends '|' ? (Schema extends T.TUnion<infer Types extends T.TSchema[]> ? T.TUnion<[Left, ...Types]> : T.TUnion<[Left, Schema]>) : never) : never) : Left);
export type TExprTermTailMapping<Input extends [unknown, unknown, unknown] | [], Context extends T.TProperties> = Input;
export declare function ExprTermTailMapping(input: [unknown, unknown, unknown] | [], context: unknown): [] | [unknown, unknown, unknown];
export type TExprTermMapping<Input extends [unknown, unknown], Context extends T.TProperties> = (Input extends [infer Left extends T.TSchema, infer Rest extends unknown[]] ? TExprBinaryMapping<Left, Rest> : []);
export declare function ExprTermMapping(input: [unknown, unknown], context: unknown): T.TSchema;
export type TExprTailMapping<Input extends [unknown, unknown, unknown] | [], Context extends T.TProperties> = Input;
export declare function ExprTailMapping(input: [unknown, unknown, unknown] | [], context: unknown): [] | [unknown, unknown, unknown];
export type TExprMapping<Input extends [unknown, unknown], Context extends T.TProperties> = Input extends [infer Left extends T.TSchema, infer Rest extends unknown[]] ? TExprBinaryMapping<Left, Rest> : [];
export declare function ExprMapping(input: [unknown, unknown], context: unknown): T.TSchema;
export type TTypeMapping<Input extends unknown, Context extends T.TProperties> = Input;
export declare function TypeMapping(input: unknown, context: unknown): unknown;
export type TPropertyKeyMapping<Input extends string, Context extends T.TProperties> = Input;
export declare function PropertyKeyMapping(input: string, context: unknown): string;
export type TReadonlyMapping<Input extends [unknown] | [], Context extends T.TProperties> = Input extends [unknown] ? true : false;
export declare function ReadonlyMapping(input: [unknown] | [], context: unknown): boolean;
export type TOptionalMapping<Input extends [unknown] | [], Context extends T.TProperties> = Input extends [unknown] ? true : false;
export declare function OptionalMapping(input: [unknown] | [], context: unknown): boolean;
export type TPropertyMapping<Input extends [unknown, unknown, unknown, unknown, unknown], Context extends T.TProperties> = Input extends [infer IsReadonly extends boolean, infer Key extends string, infer IsOptional extends boolean, string, infer Type extends T.TSchema] ? {
[_ in Key]: ([
IsReadonly,
IsOptional
] extends [true, true] ? T.TReadonlyOptional<Type> : [
IsReadonly,
IsOptional
] extends [true, false] ? T.TReadonly<Type> : [
IsReadonly,
IsOptional
] extends [false, true] ? T.TOptional<Type> : Type);
} : never;
export declare function PropertyMapping(input: [unknown, unknown, unknown, unknown, unknown], context: unknown): {
[x: string]: T.TSchema;
};
export type TPropertyDelimiterMapping<Input extends [unknown, unknown] | [unknown], Context extends T.TProperties> = Input;
export declare function PropertyDelimiterMapping(input: [unknown, unknown] | [unknown], context: unknown): [unknown] | [unknown, unknown];
export type TPropertyListMapping<Input extends [unknown, unknown], Context extends T.TProperties> = TDelimited<Input>;
export declare function PropertyListMapping(input: [unknown, unknown], context: unknown): unknown[];
type TObjectMappingReduce<PropertiesList extends T.TProperties[], Result extends T.TProperties = {}> = (PropertiesList extends [infer Left extends T.TProperties, ...infer Right extends T.TProperties[]] ? TObjectMappingReduce<Right, Result & Left> : {
[Key in keyof Result]: Result[Key];
});
export type TObjectMapping<Input extends [unknown, unknown, unknown], Context extends T.TProperties> = Input extends ['{', infer PropertyList extends T.TProperties[], '}'] ? T.TObject<TObjectMappingReduce<PropertyList>> : never;
export declare function ObjectMapping(input: [unknown, unknown, unknown], context: unknown): T.TObject<T.TProperties>;
export type TElementListMapping<Input extends [unknown, unknown], Context extends T.TProperties> = TDelimited<Input>;
export declare function ElementListMapping(input: [unknown, unknown], context: unknown): unknown[];
export type TTupleMapping<Input extends [unknown, unknown, unknown], Context extends T.TProperties> = Input extends ['[', infer Types extends T.TSchema[], ']'] ? T.TTuple<Types> : never;
export declare function TupleMapping(input: [unknown, unknown, unknown], context: unknown): T.TTuple<T.TSchema[]>;
export type TParameterMapping<Input extends [unknown, unknown, unknown], Context extends T.TProperties> = Input extends [string, ':', infer Type extends T.TSchema] ? Type : never;
export declare function ParameterMapping(input: [unknown, unknown, unknown], context: unknown): T.TSchema;
export type TParameterListMapping<Input extends [unknown, unknown], Context extends T.TProperties> = TDelimited<Input>;
export declare function ParameterListMapping(input: [unknown, unknown], context: unknown): unknown[];
export type TFunctionMapping<Input extends [unknown, unknown, unknown, unknown, unknown], Context extends T.TProperties> = Input extends ['(', infer ParameterList extends T.TSchema[], ')', '=>', infer ReturnType extends T.TSchema] ? T.TFunction<ParameterList, ReturnType> : never;
export declare function FunctionMapping(input: [unknown, unknown, unknown, unknown, unknown], context: unknown): T.TFunction<T.TSchema[], T.TSchema>;
export type TConstructorMapping<Input extends [unknown, unknown, unknown, unknown, unknown, unknown], Context extends T.TProperties> = Input extends ['new', '(', infer ParameterList extends T.TSchema[], ')', '=>', infer InstanceType extends T.TSchema] ? T.TConstructor<ParameterList, InstanceType> : never;
export declare function ConstructorMapping(input: [unknown, unknown, unknown, unknown, unknown, unknown], context: unknown): T.TConstructor<T.TSchema[], T.TSchema>;
export type TMappedMapping<Input extends [unknown, unknown, unknown, unknown, unknown, unknown, unknown, unknown, unknown], Context extends T.TProperties> = Input extends ['{', '[', infer _Key extends string, 'in', infer _Right extends T.TSchema, ']', ':', infer _Type extends T.TSchema, '}'] ? T.TLiteral<'Mapped types not supported'> : never;
export declare function MappedMapping(input: [unknown, unknown, unknown, unknown, unknown, unknown, unknown, unknown, unknown], context: unknown): T.TLiteral<"Mapped types not supported">;
export type TAsyncIteratorMapping<Input extends [unknown, unknown, unknown, unknown], Context extends T.TProperties> = Input extends ['AsyncIterator', '<', infer Type extends T.TSchema, '>'] ? T.TAsyncIterator<Type> : never;
export declare function AsyncIteratorMapping(input: [unknown, unknown, unknown, unknown], context: unknown): T.TAsyncIterator<T.TSchema>;
export type TIteratorMapping<Input extends [unknown, unknown, unknown, unknown], Context extends T.TProperties> = Input extends ['Iterator', '<', infer Type extends T.TSchema, '>'] ? T.TIterator<Type> : never;
export declare function IteratorMapping(input: [unknown, unknown, unknown, unknown], context: unknown): T.TIterator<T.TSchema>;
export type TArgumentMapping<Input extends [unknown, unknown, unknown, unknown], Context extends T.TProperties> = Input extends ['Argument', '<', infer Type extends T.TSchema, '>'] ? Type extends T.TLiteral<infer Index extends number> ? T.TArgument<Index> : T.TNever : never;
export declare function ArgumentMapping(input: [unknown, unknown, unknown, unknown], context: unknown): T.TNever | T.TArgument<number>;
export type TAwaitedMapping<Input extends [unknown, unknown, unknown, unknown], Context extends T.TProperties> = Input extends ['Awaited', '<', infer Type extends T.TSchema, '>'] ? T.TAwaited<Type> : never;
export declare function AwaitedMapping(input: [unknown, unknown, unknown, unknown], context: unknown): T.TSchema;
export type TArrayMapping<Input extends [unknown, unknown, unknown, unknown], Context extends T.TProperties> = Input extends ['Array', '<', infer Type extends T.TSchema, '>'] ? T.TArray<Type> : never;
export declare function ArrayMapping(input: [unknown, unknown, unknown, unknown], context: unknown): T.TArray<T.TSchema>;
export type TRecordMapping<Input extends [unknown, unknown, unknown, unknown, unknown, unknown], Context extends T.TProperties> = Input extends ['Record', '<', infer Key extends T.TSchema, ',', infer Type extends T.TSchema, '>'] ? T.TRecordOrObject<Key, Type> : never;
export declare function RecordMapping(input: [unknown, unknown, unknown, unknown, unknown, unknown], context: unknown): T.TNever;
export type TPromiseMapping<Input extends [unknown, unknown, unknown, unknown], Context extends T.TProperties> = Input extends ['Promise', '<', infer Type extends T.TSchema, '>'] ? T.TPromise<Type> : never;
export declare function PromiseMapping(input: [unknown, unknown, unknown, unknown], context: unknown): T.TPromise<T.TSchema>;
export type TConstructorParametersMapping<Input extends [unknown, unknown, unknown, unknown], Context extends T.TProperties> = Input extends ['ConstructorParameters', '<', infer Type extends T.TSchema, '>'] ? T.TConstructorParameters<Type> : never;
export declare function ConstructorParametersMapping(input: [unknown, unknown, unknown, unknown], context: unknown): T.TNever;
export type TFunctionParametersMapping<Input extends [unknown, unknown, unknown, unknown], Context extends T.TProperties> = Input extends ['Parameters', '<', infer Type extends T.TSchema, '>'] ? T.TParameters<Type> : never;
export declare function FunctionParametersMapping(input: [unknown, unknown, unknown, unknown], context: unknown): T.TNever;
export type TInstanceTypeMapping<Input extends [unknown, unknown, unknown, unknown], Context extends T.TProperties> = Input extends ['InstanceType', '<', infer Type extends T.TSchema, '>'] ? T.TInstanceType<Type> : never;
export declare function InstanceTypeMapping(input: [unknown, unknown, unknown, unknown], context: unknown): T.TNever;
export type TReturnTypeMapping<Input extends [unknown, unknown, unknown, unknown], Context extends T.TProperties> = Input extends ['ReturnType', '<', infer Type extends T.TSchema, '>'] ? T.TReturnType<Type> : never;
export declare function ReturnTypeMapping(input: [unknown, unknown, unknown, unknown], context: unknown): T.TNever;
export type TPartialMapping<Input extends [unknown, unknown, unknown, unknown], Context extends T.TProperties> = Input extends ['Partial', '<', infer Type extends T.TSchema, '>'] ? T.TPartial<Type> : never;
export declare function PartialMapping(input: [unknown, unknown, unknown, unknown], context: unknown): T.TObject<{}>;
export type TRequiredMapping<Input extends [unknown, unknown, unknown, unknown], Context extends T.TProperties> = Input extends ['Required', '<', infer Type extends T.TSchema, '>'] ? T.TRequired<Type> : never;
export declare function RequiredMapping(input: [unknown, unknown, unknown, unknown], context: unknown): T.TObject<{}>;
export type TPickMapping<Input extends [unknown, unknown, unknown, unknown, unknown, unknown], Context extends T.TProperties> = Input extends ['Pick', '<', infer Type extends T.TSchema, ',', infer Key extends T.TSchema, '>'] ? T.TPick<Type, Key> : never;
export declare function PickMapping(input: [unknown, unknown, unknown, unknown, unknown, unknown], context: unknown): T.TObject<{}>;
export type TOmitMapping<Input extends [unknown, unknown, unknown, unknown, unknown, unknown], Context extends T.TProperties> = Input extends ['Omit', '<', infer Type extends T.TSchema, ',', infer Key extends T.TSchema, '>'] ? T.TOmit<Type, Key> : never;
export declare function OmitMapping(input: [unknown, unknown, unknown, unknown, unknown, unknown], context: unknown): T.TObject<{}>;
export type TExcludeMapping<Input extends [unknown, unknown, unknown, unknown, unknown, unknown], Context extends T.TProperties> = Input extends ['Exclude', '<', infer Type extends T.TSchema, ',', infer Key extends T.TSchema, '>'] ? T.TExclude<Type, Key> : never;
export declare function ExcludeMapping(input: [unknown, unknown, unknown, unknown, unknown, unknown], context: unknown): T.TNever;
export type TExtractMapping<Input extends [unknown, unknown, unknown, unknown, unknown, unknown], Context extends T.TProperties> = Input extends ['Extract', '<', infer Type extends T.TSchema, ',', infer Key extends T.TSchema, '>'] ? T.TExtract<Type, Key> : never;
export declare function ExtractMapping(input: [unknown, unknown, unknown, unknown, unknown, unknown], context: unknown): T.TSchema;
export type TUppercaseMapping<Input extends [unknown, unknown, unknown, unknown], Context extends T.TProperties> = Input extends ['Uppercase', '<', infer Type extends T.TSchema, '>'] ? T.TUppercase<Type> : never;
export declare function UppercaseMapping(input: [unknown, unknown, unknown, unknown], context: unknown): T.TSchema;
export type TLowercaseMapping<Input extends [unknown, unknown, unknown, unknown], Context extends T.TProperties> = Input extends ['Lowercase', '<', infer Type extends T.TSchema, '>'] ? T.TLowercase<Type> : never;
export declare function LowercaseMapping(input: [unknown, unknown, unknown, unknown], context: unknown): T.TSchema;
export type TCapitalizeMapping<Input extends [unknown, unknown, unknown, unknown], Context extends T.TProperties> = Input extends ['Capitalize', '<', infer Type extends T.TSchema, '>'] ? T.TCapitalize<Type> : never;
export declare function CapitalizeMapping(input: [unknown, unknown, unknown, unknown], context: unknown): T.TSchema;
export type TUncapitalizeMapping<Input extends [unknown, unknown, unknown, unknown], Context extends T.TProperties> = Input extends ['Uncapitalize', '<', infer Type extends T.TSchema, '>'] ? T.TUncapitalize<Type> : never;
export declare function UncapitalizeMapping(input: [unknown, unknown, unknown, unknown], context: unknown): T.TSchema;
export type TDateMapping<Input extends 'Date', Context extends T.TProperties> = T.TDate;
export declare function DateMapping(input: 'Date', context: unknown): T.TDate;
export type TUint8ArrayMapping<Input extends 'Uint8Array', Context extends T.TProperties> = T.TUint8Array;
export declare function Uint8ArrayMapping(input: 'Uint8Array', context: unknown): T.TUint8Array;
export type TReferenceMapping<Input extends string, Context extends T.TProperties> = Context extends T.TProperties ? Input extends string ? TDereference<Context, Input> : never : never;
export declare function ReferenceMapping(input: string, context: unknown): T.TSchema;
export {};
@@ -0,0 +1,491 @@
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
var ownKeys = function(o) {
ownKeys = Object.getOwnPropertyNames || function (o) {
var ar = [];
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
return ar;
};
return ownKeys(o);
};
return function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
__setModuleDefault(result, mod);
return result;
};
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.GenericReferenceParameterListMapping = GenericReferenceParameterListMapping;
exports.GenericReferenceMapping = GenericReferenceMapping;
exports.GenericArgumentsListMapping = GenericArgumentsListMapping;
exports.GenericArgumentsMapping = GenericArgumentsMapping;
exports.KeywordStringMapping = KeywordStringMapping;
exports.KeywordNumberMapping = KeywordNumberMapping;
exports.KeywordBooleanMapping = KeywordBooleanMapping;
exports.KeywordUndefinedMapping = KeywordUndefinedMapping;
exports.KeywordNullMapping = KeywordNullMapping;
exports.KeywordIntegerMapping = KeywordIntegerMapping;
exports.KeywordBigIntMapping = KeywordBigIntMapping;
exports.KeywordUnknownMapping = KeywordUnknownMapping;
exports.KeywordAnyMapping = KeywordAnyMapping;
exports.KeywordNeverMapping = KeywordNeverMapping;
exports.KeywordSymbolMapping = KeywordSymbolMapping;
exports.KeywordVoidMapping = KeywordVoidMapping;
exports.KeywordMapping = KeywordMapping;
exports.LiteralStringMapping = LiteralStringMapping;
exports.LiteralNumberMapping = LiteralNumberMapping;
exports.LiteralBooleanMapping = LiteralBooleanMapping;
exports.LiteralMapping = LiteralMapping;
exports.KeyOfMapping = KeyOfMapping;
exports.IndexArrayMapping = IndexArrayMapping;
exports.ExtendsMapping = ExtendsMapping;
exports.BaseMapping = BaseMapping;
exports.FactorMapping = FactorMapping;
exports.ExprTermTailMapping = ExprTermTailMapping;
exports.ExprTermMapping = ExprTermMapping;
exports.ExprTailMapping = ExprTailMapping;
exports.ExprMapping = ExprMapping;
exports.TypeMapping = TypeMapping;
exports.PropertyKeyMapping = PropertyKeyMapping;
exports.ReadonlyMapping = ReadonlyMapping;
exports.OptionalMapping = OptionalMapping;
exports.PropertyMapping = PropertyMapping;
exports.PropertyDelimiterMapping = PropertyDelimiterMapping;
exports.PropertyListMapping = PropertyListMapping;
exports.ObjectMapping = ObjectMapping;
exports.ElementListMapping = ElementListMapping;
exports.TupleMapping = TupleMapping;
exports.ParameterMapping = ParameterMapping;
exports.ParameterListMapping = ParameterListMapping;
exports.FunctionMapping = FunctionMapping;
exports.ConstructorMapping = ConstructorMapping;
exports.MappedMapping = MappedMapping;
exports.AsyncIteratorMapping = AsyncIteratorMapping;
exports.IteratorMapping = IteratorMapping;
exports.ArgumentMapping = ArgumentMapping;
exports.AwaitedMapping = AwaitedMapping;
exports.ArrayMapping = ArrayMapping;
exports.RecordMapping = RecordMapping;
exports.PromiseMapping = PromiseMapping;
exports.ConstructorParametersMapping = ConstructorParametersMapping;
exports.FunctionParametersMapping = FunctionParametersMapping;
exports.InstanceTypeMapping = InstanceTypeMapping;
exports.ReturnTypeMapping = ReturnTypeMapping;
exports.PartialMapping = PartialMapping;
exports.RequiredMapping = RequiredMapping;
exports.PickMapping = PickMapping;
exports.OmitMapping = OmitMapping;
exports.ExcludeMapping = ExcludeMapping;
exports.ExtractMapping = ExtractMapping;
exports.UppercaseMapping = UppercaseMapping;
exports.LowercaseMapping = LowercaseMapping;
exports.CapitalizeMapping = CapitalizeMapping;
exports.UncapitalizeMapping = UncapitalizeMapping;
exports.DateMapping = DateMapping;
exports.Uint8ArrayMapping = Uint8ArrayMapping;
exports.ReferenceMapping = ReferenceMapping;
const T = __importStar(require("../type/index"));
// prettier-ignore
const Dereference = (context, key) => {
return key in context ? context[key] : T.Ref(key);
};
// prettier-ignore
const DelimitedDecode = (input, result = []) => {
return input.reduce((result, left) => {
return T.ValueGuard.IsArray(left) && left.length === 2
? [...result, left[0]]
: [...result, left];
}, []);
};
// prettier-ignore
const Delimited = (input) => {
const [left, right] = input;
return DelimitedDecode([...left, ...right]);
};
// prettier-ignore
function GenericReferenceParameterListMapping(input, context) {
return Delimited(input);
}
// prettier-ignore
function GenericReferenceMapping(input, context) {
const type = Dereference(context, input[0]);
const args = input[2];
return T.Instantiate(type, args);
}
// prettier-ignore
function GenericArgumentsListMapping(input, context) {
return Delimited(input);
}
// ...
// prettier-ignore
const GenericArgumentsContext = (_arguments, context) => {
return _arguments.reduce((result, arg, index) => {
return { ...result, [arg]: T.Argument(index) };
}, context);
};
// prettier-ignore
function GenericArgumentsMapping(input, context) {
return input.length === 3
? GenericArgumentsContext(input[1], context)
: {};
}
// prettier-ignore
function KeywordStringMapping(input, context) {
return T.String();
}
// prettier-ignore
function KeywordNumberMapping(input, context) {
return T.Number();
}
// prettier-ignore
function KeywordBooleanMapping(input, context) {
return T.Boolean();
}
// prettier-ignore
function KeywordUndefinedMapping(input, context) {
return T.Undefined();
}
// prettier-ignore
function KeywordNullMapping(input, context) {
return T.Null();
}
// prettier-ignore
function KeywordIntegerMapping(input, context) {
return T.Integer();
}
// prettier-ignore
function KeywordBigIntMapping(input, context) {
return T.BigInt();
}
// prettier-ignore
function KeywordUnknownMapping(input, context) {
return T.Unknown();
}
// prettier-ignore
function KeywordAnyMapping(input, context) {
return T.Any();
}
// prettier-ignore
function KeywordNeverMapping(input, context) {
return T.Never();
}
// prettier-ignore
function KeywordSymbolMapping(input, context) {
return T.Symbol();
}
// prettier-ignore
function KeywordVoidMapping(input, context) {
return T.Void();
}
// prettier-ignore
function KeywordMapping(input, context) {
return input;
}
// prettier-ignore
function LiteralStringMapping(input, context) {
return T.Literal(input);
}
// prettier-ignore
function LiteralNumberMapping(input, context) {
return T.Literal(parseFloat(input));
}
// prettier-ignore
function LiteralBooleanMapping(input, context) {
return T.Literal(input === 'true');
}
// prettier-ignore
function LiteralMapping(input, context) {
return input;
}
// prettier-ignore
function KeyOfMapping(input, context) {
return input.length > 0;
}
// prettier-ignore
function IndexArrayMapping(input, context) {
return input.reduce((result, current) => {
return current.length === 3
? [...result, [current[1]]]
: [...result, []];
}, []);
}
// prettier-ignore
function ExtendsMapping(input, context) {
return input.length === 6
? [input[1], input[3], input[5]]
: [];
}
// prettier-ignore
function BaseMapping(input, context) {
return T.ValueGuard.IsArray(input) && input.length === 3 ? input[1] : input;
}
// ...
// prettier-ignore
const FactorIndexArray = (Type, indexArray) => {
return indexArray.reduceRight((result, right) => {
const _right = right;
return (_right.length === 1 ? T.Index(result, _right[0]) :
_right.length === 0 ? T.Array(result, _right[0]) :
T.Never());
}, Type);
};
// prettier-ignore
const FactorExtends = (Type, Extends) => {
return Extends.length === 3
? T.Extends(Type, Extends[0], Extends[1], Extends[2])
: Type;
};
// prettier-ignore
function FactorMapping(input, context) {
const [KeyOf, Type, IndexArray, Extends] = input;
return KeyOf
? FactorExtends(T.KeyOf(FactorIndexArray(Type, IndexArray)), Extends)
: FactorExtends(FactorIndexArray(Type, IndexArray), Extends);
}
// prettier-ignore
function ExprBinaryMapping(Left, Rest) {
return (Rest.length === 3 ? (() => {
const [Operator, Right, Next] = Rest;
const Schema = ExprBinaryMapping(Right, Next);
if (Operator === '&') {
return T.TypeGuard.IsIntersect(Schema)
? T.Intersect([Left, ...Schema.allOf])
: T.Intersect([Left, Schema]);
}
if (Operator === '|') {
return T.TypeGuard.IsUnion(Schema)
? T.Union([Left, ...Schema.anyOf])
: T.Union([Left, Schema]);
}
throw 1;
})() : Left);
}
// prettier-ignore
function ExprTermTailMapping(input, context) {
return input;
}
// prettier-ignore
function ExprTermMapping(input, context) {
const [left, rest] = input;
return ExprBinaryMapping(left, rest);
}
// prettier-ignore
function ExprTailMapping(input, context) {
return input;
}
// prettier-ignore
function ExprMapping(input, context) {
const [left, rest] = input;
return ExprBinaryMapping(left, rest);
}
// prettier-ignore
function TypeMapping(input, context) {
return input;
}
// prettier-ignore
function PropertyKeyMapping(input, context) {
return input;
}
// prettier-ignore
function ReadonlyMapping(input, context) {
return input.length > 0;
}
// prettier-ignore
function OptionalMapping(input, context) {
return input.length > 0;
}
// prettier-ignore
function PropertyMapping(input, context) {
const [isReadonly, key, isOptional, _colon, type] = input;
return {
[key]: (isReadonly && isOptional ? T.ReadonlyOptional(type) :
isReadonly && !isOptional ? T.Readonly(type) :
!isReadonly && isOptional ? T.Optional(type) :
type)
};
}
// prettier-ignore
function PropertyDelimiterMapping(input, context) {
return input;
}
// prettier-ignore
function PropertyListMapping(input, context) {
return Delimited(input);
}
// prettier-ignore
function ObjectMapping(input, context) {
const propertyList = input[1];
return T.Object(propertyList.reduce((result, property) => {
return { ...result, ...property };
}, {}));
}
// prettier-ignore
function ElementListMapping(input, context) {
return Delimited(input);
}
// prettier-ignore
function TupleMapping(input, context) {
return T.Tuple(input[1]);
}
// prettier-ignore
function ParameterMapping(input, context) {
const [_ident, _colon, type] = input;
return type;
}
// prettier-ignore
function ParameterListMapping(input, context) {
return Delimited(input);
}
// prettier-ignore
function FunctionMapping(input, context) {
const [_lparan, parameterList, _rparan, _arrow, returnType] = input;
return T.Function(parameterList, returnType);
}
// prettier-ignore
function ConstructorMapping(input, context) {
const [_new, _lparan, parameterList, _rparan, _arrow, instanceType] = input;
return T.Constructor(parameterList, instanceType);
}
// prettier-ignore
function MappedMapping(input, context) {
const [_lbrace, _lbracket, _key, _in, _right, _rbracket, _colon, _type] = input;
return T.Literal('Mapped types not supported');
}
// prettier-ignore
function AsyncIteratorMapping(input, context) {
const [_name, _langle, type, _rangle] = input;
return T.AsyncIterator(type);
}
// prettier-ignore
function IteratorMapping(input, context) {
const [_name, _langle, type, _rangle] = input;
return T.Iterator(type);
}
// prettier-ignore
function ArgumentMapping(input, context) {
return T.KindGuard.IsLiteralNumber(input[2])
? T.Argument(Math.trunc(input[2].const))
: T.Never();
}
// prettier-ignore
function AwaitedMapping(input, context) {
const [_name, _langle, type, _rangle] = input;
return T.Awaited(type);
}
// prettier-ignore
function ArrayMapping(input, context) {
const [_name, _langle, type, _rangle] = input;
return T.Array(type);
}
// prettier-ignore
function RecordMapping(input, context) {
const [_name, _langle, key, _comma, type, _rangle] = input;
return T.Record(key, type);
}
// prettier-ignore
function PromiseMapping(input, context) {
const [_name, _langle, type, _rangle] = input;
return T.Promise(type);
}
// prettier-ignore
function ConstructorParametersMapping(input, context) {
const [_name, _langle, type, _rangle] = input;
return T.ConstructorParameters(type);
}
// prettier-ignore
function FunctionParametersMapping(input, context) {
const [_name, _langle, type, _rangle] = input;
return T.Parameters(type);
}
// prettier-ignore
function InstanceTypeMapping(input, context) {
const [_name, _langle, type, _rangle] = input;
return T.InstanceType(type);
}
// prettier-ignore
function ReturnTypeMapping(input, context) {
const [_name, _langle, type, _rangle] = input;
return T.ReturnType(type);
}
// prettier-ignore
function PartialMapping(input, context) {
const [_name, _langle, type, _rangle] = input;
return T.Partial(type);
}
// prettier-ignore
function RequiredMapping(input, context) {
const [_name, _langle, type, _rangle] = input;
return T.Required(type);
}
// prettier-ignore
function PickMapping(input, context) {
const [_name, _langle, key, _comma, type, _rangle] = input;
return T.Pick(key, type);
}
// prettier-ignore
function OmitMapping(input, context) {
const [_name, _langle, key, _comma, type, _rangle] = input;
return T.Omit(key, type);
}
// prettier-ignore
function ExcludeMapping(input, context) {
const [_name, _langle, key, _comma, type, _rangle] = input;
return T.Exclude(key, type);
}
// prettier-ignore
function ExtractMapping(input, context) {
const [_name, _langle, key, _comma, type, _rangle] = input;
return T.Extract(key, type);
}
// prettier-ignore
function UppercaseMapping(input, context) {
const [_name, _langle, type, _rangle] = input;
return T.Uppercase(type);
}
// prettier-ignore
function LowercaseMapping(input, context) {
const [_name, _langle, type, _rangle] = input;
return T.Lowercase(type);
}
// prettier-ignore
function CapitalizeMapping(input, context) {
const [_name, _langle, type, _rangle] = input;
return T.Capitalize(type);
}
// prettier-ignore
function UncapitalizeMapping(input, context) {
const [_name, _langle, type, _rangle] = input;
return T.Uncapitalize(type);
}
// prettier-ignore
function DateMapping(input, context) {
return T.Date();
}
// prettier-ignore
function Uint8ArrayMapping(input, context) {
return T.Uint8Array();
}
// prettier-ignore
function ReferenceMapping(input, context) {
const target = Dereference(context, input);
return target;
}
@@ -0,0 +1,162 @@
import { Static } from '../parser/index';
import * as T from '../type/index';
import * as S from './mapping';
export type TGenericReferenceParameterList_0<Input extends string, Context extends T.TProperties, Result extends unknown[] = []> = (TType<Input, Context> extends [infer _0, infer Input extends string] ? (Static.Token.Const<',', Input> extends [infer _1, infer Input extends string] ? [[_0, _1], Input] : []) : []) extends [infer _0, infer Input extends string] ? TGenericReferenceParameterList_0<Input, Context, [...Result, _0]> : [Result, Input];
export type TGenericReferenceParameterList<Input extends string, Context extends T.TProperties = {}> = (TGenericReferenceParameterList_0<Input, Context> extends [infer _0, infer Input extends string] ? ((TType<Input, Context> extends [infer _0, infer Input extends string] ? [[_0], Input] : []) extends [infer _0, infer Input extends string] ? [_0, Input] : [[], Input] extends [infer _0, infer Input extends string] ? [_0, Input] : []) extends [infer _1, infer Input extends string] ? [[_0, _1], Input] : [] : []) extends [infer _0 extends [unknown, unknown], infer Input extends string] ? [S.TGenericReferenceParameterListMapping<_0, Context>, Input] : [];
export type TGenericReference<Input extends string, Context extends T.TProperties = {}> = (Static.Token.Ident<Input> extends [infer _0, infer Input extends string] ? Static.Token.Const<'<', Input> extends [infer _1, infer Input extends string] ? TGenericReferenceParameterList<Input, Context> extends [infer _2, infer Input extends string] ? Static.Token.Const<'>', Input> extends [infer _3, infer Input extends string] ? [[_0, _1, _2, _3], Input] : [] : [] : [] : []) extends [infer _0 extends [unknown, unknown, unknown, unknown], infer Input extends string] ? [S.TGenericReferenceMapping<_0, Context>, Input] : [];
export type TGenericArgumentsList_0<Input extends string, Context extends T.TProperties, Result extends unknown[] = []> = (Static.Token.Ident<Input> extends [infer _0, infer Input extends string] ? (Static.Token.Const<',', Input> extends [infer _1, infer Input extends string] ? [[_0, _1], Input] : []) : []) extends [infer _0, infer Input extends string] ? TGenericArgumentsList_0<Input, Context, [...Result, _0]> : [Result, Input];
export type TGenericArgumentsList<Input extends string, Context extends T.TProperties = {}> = (TGenericArgumentsList_0<Input, Context> extends [infer _0, infer Input extends string] ? ((Static.Token.Ident<Input> extends [infer _0, infer Input extends string] ? [[_0], Input] : []) extends [infer _0, infer Input extends string] ? [_0, Input] : [[], Input] extends [infer _0, infer Input extends string] ? [_0, Input] : []) extends [infer _1, infer Input extends string] ? [[_0, _1], Input] : [] : []) extends [infer _0 extends [unknown, unknown], infer Input extends string] ? [S.TGenericArgumentsListMapping<_0, Context>, Input] : [];
export type TGenericArguments<Input extends string, Context extends T.TProperties = {}> = (Static.Token.Const<'<', Input> extends [infer _0, infer Input extends string] ? TGenericArgumentsList<Input, Context> extends [infer _1, infer Input extends string] ? Static.Token.Const<'>', Input> extends [infer _2, infer Input extends string] ? [[_0, _1, _2], Input] : [] : [] : []) extends [infer _0 extends [unknown, unknown, unknown], infer Input extends string] ? [S.TGenericArgumentsMapping<_0, Context>, Input] : [];
export type TKeywordString<Input extends string, Context extends T.TProperties = {}> = Static.Token.Const<'string', Input> extends [infer _0 extends 'string', infer Input extends string] ? [S.TKeywordStringMapping<_0, Context>, Input] : [];
export type TKeywordNumber<Input extends string, Context extends T.TProperties = {}> = Static.Token.Const<'number', Input> extends [infer _0 extends 'number', infer Input extends string] ? [S.TKeywordNumberMapping<_0, Context>, Input] : [];
export type TKeywordBoolean<Input extends string, Context extends T.TProperties = {}> = Static.Token.Const<'boolean', Input> extends [infer _0 extends 'boolean', infer Input extends string] ? [S.TKeywordBooleanMapping<_0, Context>, Input] : [];
export type TKeywordUndefined<Input extends string, Context extends T.TProperties = {}> = Static.Token.Const<'undefined', Input> extends [infer _0 extends 'undefined', infer Input extends string] ? [S.TKeywordUndefinedMapping<_0, Context>, Input] : [];
export type TKeywordNull<Input extends string, Context extends T.TProperties = {}> = Static.Token.Const<'null', Input> extends [infer _0 extends 'null', infer Input extends string] ? [S.TKeywordNullMapping<_0, Context>, Input] : [];
export type TKeywordInteger<Input extends string, Context extends T.TProperties = {}> = Static.Token.Const<'integer', Input> extends [infer _0 extends 'integer', infer Input extends string] ? [S.TKeywordIntegerMapping<_0, Context>, Input] : [];
export type TKeywordBigInt<Input extends string, Context extends T.TProperties = {}> = Static.Token.Const<'bigint', Input> extends [infer _0 extends 'bigint', infer Input extends string] ? [S.TKeywordBigIntMapping<_0, Context>, Input] : [];
export type TKeywordUnknown<Input extends string, Context extends T.TProperties = {}> = Static.Token.Const<'unknown', Input> extends [infer _0 extends 'unknown', infer Input extends string] ? [S.TKeywordUnknownMapping<_0, Context>, Input] : [];
export type TKeywordAny<Input extends string, Context extends T.TProperties = {}> = Static.Token.Const<'any', Input> extends [infer _0 extends 'any', infer Input extends string] ? [S.TKeywordAnyMapping<_0, Context>, Input] : [];
export type TKeywordNever<Input extends string, Context extends T.TProperties = {}> = Static.Token.Const<'never', Input> extends [infer _0 extends 'never', infer Input extends string] ? [S.TKeywordNeverMapping<_0, Context>, Input] : [];
export type TKeywordSymbol<Input extends string, Context extends T.TProperties = {}> = Static.Token.Const<'symbol', Input> extends [infer _0 extends 'symbol', infer Input extends string] ? [S.TKeywordSymbolMapping<_0, Context>, Input] : [];
export type TKeywordVoid<Input extends string, Context extends T.TProperties = {}> = Static.Token.Const<'void', Input> extends [infer _0 extends 'void', infer Input extends string] ? [S.TKeywordVoidMapping<_0, Context>, Input] : [];
export type TKeyword<Input extends string, Context extends T.TProperties = {}> = (TKeywordString<Input, Context> extends [infer _0, infer Input extends string] ? [_0, Input] : TKeywordNumber<Input, Context> extends [infer _0, infer Input extends string] ? [_0, Input] : TKeywordBoolean<Input, Context> extends [infer _0, infer Input extends string] ? [_0, Input] : TKeywordUndefined<Input, Context> extends [infer _0, infer Input extends string] ? [_0, Input] : TKeywordNull<Input, Context> extends [infer _0, infer Input extends string] ? [_0, Input] : TKeywordInteger<Input, Context> extends [infer _0, infer Input extends string] ? [_0, Input] : TKeywordBigInt<Input, Context> extends [infer _0, infer Input extends string] ? [_0, Input] : TKeywordUnknown<Input, Context> extends [infer _0, infer Input extends string] ? [_0, Input] : TKeywordAny<Input, Context> extends [infer _0, infer Input extends string] ? [_0, Input] : TKeywordNever<Input, Context> extends [infer _0, infer Input extends string] ? [_0, Input] : TKeywordSymbol<Input, Context> extends [infer _0, infer Input extends string] ? [_0, Input] : TKeywordVoid<Input, Context> extends [infer _0, infer Input extends string] ? [_0, Input] : []) extends [infer _0 extends unknown, infer Input extends string] ? [S.TKeywordMapping<_0, Context>, Input] : [];
export type TLiteralString<Input extends string, Context extends T.TProperties = {}> = Static.Token.String<["'", '"', '`'], Input> extends [infer _0 extends string, infer Input extends string] ? [S.TLiteralStringMapping<_0, Context>, Input] : [];
export type TLiteralNumber<Input extends string, Context extends T.TProperties = {}> = Static.Token.Number<Input> extends [infer _0 extends string, infer Input extends string] ? [S.TLiteralNumberMapping<_0, Context>, Input] : [];
export type TLiteralBoolean<Input extends string, Context extends T.TProperties = {}> = (Static.Token.Const<'true', Input> extends [infer _0, infer Input extends string] ? [_0, Input] : Static.Token.Const<'false', Input> extends [infer _0, infer Input extends string] ? [_0, Input] : []) extends [infer _0 extends 'true' | 'false', infer Input extends string] ? [S.TLiteralBooleanMapping<_0, Context>, Input] : [];
export type TLiteral<Input extends string, Context extends T.TProperties = {}> = (TLiteralBoolean<Input, Context> extends [infer _0, infer Input extends string] ? [_0, Input] : TLiteralNumber<Input, Context> extends [infer _0, infer Input extends string] ? [_0, Input] : TLiteralString<Input, Context> extends [infer _0, infer Input extends string] ? [_0, Input] : []) extends [infer _0 extends unknown, infer Input extends string] ? [S.TLiteralMapping<_0, Context>, Input] : [];
export type TKeyOf<Input extends string, Context extends T.TProperties = {}> = ((Static.Token.Const<'keyof', Input> extends [infer _0, infer Input extends string] ? [[_0], Input] : []) extends [infer _0, infer Input extends string] ? [_0, Input] : [[], Input] extends [infer _0, infer Input extends string] ? [_0, Input] : []) extends [infer _0 extends [unknown] | [], infer Input extends string] ? [S.TKeyOfMapping<_0, Context>, Input] : [];
export type TIndexArray_0<Input extends string, Context extends T.TProperties, Result extends unknown[] = []> = ((Static.Token.Const<'[', Input> extends [infer _0, infer Input extends string] ? TType<Input, Context> extends [infer _1, infer Input extends string] ? Static.Token.Const<']', Input> extends [infer _2, infer Input extends string] ? [[_0, _1, _2], Input] : [] : [] : []) extends [infer _0, infer Input extends string] ? [_0, Input] : (Static.Token.Const<'[', Input> extends [infer _0, infer Input extends string] ? (Static.Token.Const<']', Input> extends [infer _1, infer Input extends string] ? [[_0, _1], Input] : []) : []) extends [
infer _0,
infer Input extends string
] ? [_0, Input] : []) extends [infer _0, infer Input extends string] ? TIndexArray_0<Input, Context, [...Result, _0]> : [Result, Input];
export type TIndexArray<Input extends string, Context extends T.TProperties = {}> = TIndexArray_0<Input, Context> extends [infer _0 extends ([unknown, unknown, unknown] | [unknown, unknown])[], infer Input extends string] ? [S.TIndexArrayMapping<_0, Context>, Input] : [];
export type TExtends<Input extends string, Context extends T.TProperties = {}> = ((Static.Token.Const<'extends', Input> extends [infer _0, infer Input extends string] ? TType<Input, Context> extends [infer _1, infer Input extends string] ? Static.Token.Const<'?', Input> extends [infer _2, infer Input extends string] ? TType<Input, Context> extends [infer _3, infer Input extends string] ? Static.Token.Const<':', Input> extends [infer _4, infer Input extends string] ? TType<Input, Context> extends [infer _5, infer Input extends string] ? [[_0, _1, _2, _3, _4, _5], Input] : [] : [] : [] : [] : [] : []) extends [infer _0, infer Input extends string] ? [_0, Input] : [[], Input] extends [infer _0, infer Input extends string] ? [_0, Input] : []) extends [infer _0 extends [unknown, unknown, unknown, unknown, unknown, unknown] | [], infer Input extends string] ? [S.TExtendsMapping<_0, Context>, Input] : [];
export type TBase<Input extends string, Context extends T.TProperties = {}> = ((Static.Token.Const<'(', Input> extends [infer _0, infer Input extends string] ? TType<Input, Context> extends [infer _1, infer Input extends string] ? Static.Token.Const<')', Input> extends [infer _2, infer Input extends string] ? [[_0, _1, _2], Input] : [] : [] : []) extends [infer _0, infer Input extends string] ? [_0, Input] : TKeyword<Input, Context> extends [infer _0, infer Input extends string] ? [_0, Input] : TObject<Input, Context> extends [infer _0, infer Input extends string] ? [_0, Input] : TTuple<Input, Context> extends [infer _0, infer Input extends string] ? [_0, Input] : TLiteral<Input, Context> extends [infer _0, infer Input extends string] ? [_0, Input] : TConstructor<Input, Context> extends [infer _0, infer Input extends string] ? [_0, Input] : TFunction<Input, Context> extends [infer _0, infer Input extends string] ? [_0, Input] : TMapped<Input, Context> extends [infer _0, infer Input extends string] ? [_0, Input] : TAsyncIterator<Input, Context> extends [infer _0, infer Input extends string] ? [_0, Input] : TIterator<Input, Context> extends [infer _0, infer Input extends string] ? [_0, Input] : TConstructorParameters<Input, Context> extends [infer _0, infer Input extends string] ? [_0, Input] : TFunctionParameters<Input, Context> extends [infer _0, infer Input extends string] ? [_0, Input] : TInstanceType<Input, Context> extends [infer _0, infer Input extends string] ? [_0, Input] : TReturnType<Input, Context> extends [infer _0, infer Input extends string] ? [_0, Input] : TArgument<Input, Context> extends [infer _0, infer Input extends string] ? [_0, Input] : TAwaited<Input, Context> extends [infer _0, infer Input extends string] ? [_0, Input] : TArray<Input, Context> extends [infer _0, infer Input extends string] ? [_0, Input] : TRecord<Input, Context> extends [infer _0, infer Input extends string] ? [_0, Input] : TPromise<Input, Context> extends [infer _0, infer Input extends string] ? [_0, Input] : TPartial<Input, Context> extends [infer _0, infer Input extends string] ? [_0, Input] : TRequired<Input, Context> extends [infer _0, infer Input extends string] ? [_0, Input] : TPick<Input, Context> extends [infer _0, infer Input extends string] ? [_0, Input] : TOmit<Input, Context> extends [infer _0, infer Input extends string] ? [_0, Input] : TExclude<Input, Context> extends [infer _0, infer Input extends string] ? [_0, Input] : TExtract<Input, Context> extends [infer _0, infer Input extends string] ? [_0, Input] : TUppercase<Input, Context> extends [infer _0, infer Input extends string] ? [_0, Input] : TLowercase<Input, Context> extends [infer _0, infer Input extends string] ? [_0, Input] : TCapitalize<Input, Context> extends [infer _0, infer Input extends string] ? [_0, Input] : TUncapitalize<Input, Context> extends [infer _0, infer Input extends string] ? [_0, Input] : TDate<Input, Context> extends [infer _0, infer Input extends string] ? [_0, Input] : TUint8Array<Input, Context> extends [infer _0, infer Input extends string] ? [_0, Input] : TGenericReference<Input, Context> extends [infer _0, infer Input extends string] ? [_0, Input] : TReference<Input, Context> extends [infer _0, infer Input extends string] ? [_0, Input] : []) extends [infer _0 extends [unknown, unknown, unknown] | unknown, infer Input extends string] ? [S.TBaseMapping<_0, Context>, Input] : [];
export type TFactor<Input extends string, Context extends T.TProperties = {}> = (TKeyOf<Input, Context> extends [infer _0, infer Input extends string] ? TBase<Input, Context> extends [infer _1, infer Input extends string] ? TIndexArray<Input, Context> extends [infer _2, infer Input extends string] ? TExtends<Input, Context> extends [infer _3, infer Input extends string] ? [[_0, _1, _2, _3], Input] : [] : [] : [] : []) extends [infer _0 extends [unknown, unknown, unknown, unknown], infer Input extends string] ? [S.TFactorMapping<_0, Context>, Input] : [];
export type TExprTermTail<Input extends string, Context extends T.TProperties = {}> = ((Static.Token.Const<'&', Input> extends [infer _0, infer Input extends string] ? TFactor<Input, Context> extends [infer _1, infer Input extends string] ? TExprTermTail<Input, Context> extends [infer _2, infer Input extends string] ? [[_0, _1, _2], Input] : [] : [] : []) extends [infer _0, infer Input extends string] ? [_0, Input] : [[], Input] extends [infer _0, infer Input extends string] ? [_0, Input] : []) extends [infer _0 extends [unknown, unknown, unknown] | [], infer Input extends string] ? [S.TExprTermTailMapping<_0, Context>, Input] : [];
export type TExprTerm<Input extends string, Context extends T.TProperties = {}> = (TFactor<Input, Context> extends [infer _0, infer Input extends string] ? (TExprTermTail<Input, Context> extends [infer _1, infer Input extends string] ? [[_0, _1], Input] : []) : []) extends [infer _0 extends [unknown, unknown], infer Input extends string] ? [S.TExprTermMapping<_0, Context>, Input] : [];
export type TExprTail<Input extends string, Context extends T.TProperties = {}> = ((Static.Token.Const<'|', Input> extends [infer _0, infer Input extends string] ? TExprTerm<Input, Context> extends [infer _1, infer Input extends string] ? TExprTail<Input, Context> extends [infer _2, infer Input extends string] ? [[_0, _1, _2], Input] : [] : [] : []) extends [infer _0, infer Input extends string] ? [_0, Input] : [[], Input] extends [infer _0, infer Input extends string] ? [_0, Input] : []) extends [infer _0 extends [unknown, unknown, unknown] | [], infer Input extends string] ? [S.TExprTailMapping<_0, Context>, Input] : [];
export type TExpr<Input extends string, Context extends T.TProperties = {}> = (TExprTerm<Input, Context> extends [infer _0, infer Input extends string] ? (TExprTail<Input, Context> extends [infer _1, infer Input extends string] ? [[_0, _1], Input] : []) : []) extends [infer _0 extends [unknown, unknown], infer Input extends string] ? [S.TExprMapping<_0, Context>, Input] : [];
export type TType<Input extends string, Context extends T.TProperties = {}> = (TGenericArguments<Input, Context> extends [infer _0 extends T.TProperties, infer Input extends string] ? TExpr<Input, _0> : [] extends [infer _0, infer Input extends string] ? [_0, Input] : TExpr<Input, Context> extends [infer _0, infer Input extends string] ? [_0, Input] : []) extends [infer _0 extends unknown, infer Input extends string] ? [S.TTypeMapping<_0, Context>, Input] : [];
export type TPropertyKey<Input extends string, Context extends T.TProperties = {}> = (Static.Token.Ident<Input> extends [infer _0, infer Input extends string] ? [_0, Input] : Static.Token.String<["'", '"'], Input> extends [infer _0, infer Input extends string] ? [_0, Input] : []) extends [infer _0 extends string, infer Input extends string] ? [S.TPropertyKeyMapping<_0, Context>, Input] : [];
export type TReadonly<Input extends string, Context extends T.TProperties = {}> = ((Static.Token.Const<'readonly', Input> extends [infer _0, infer Input extends string] ? [[_0], Input] : []) extends [infer _0, infer Input extends string] ? [_0, Input] : [[], Input] extends [infer _0, infer Input extends string] ? [_0, Input] : []) extends [infer _0 extends [unknown] | [], infer Input extends string] ? [S.TReadonlyMapping<_0, Context>, Input] : [];
export type TOptional<Input extends string, Context extends T.TProperties = {}> = ((Static.Token.Const<'?', Input> extends [infer _0, infer Input extends string] ? [[_0], Input] : []) extends [infer _0, infer Input extends string] ? [_0, Input] : [[], Input] extends [infer _0, infer Input extends string] ? [_0, Input] : []) extends [infer _0 extends [unknown] | [], infer Input extends string] ? [S.TOptionalMapping<_0, Context>, Input] : [];
export type TProperty<Input extends string, Context extends T.TProperties = {}> = (TReadonly<Input, Context> extends [infer _0, infer Input extends string] ? TPropertyKey<Input, Context> extends [infer _1, infer Input extends string] ? TOptional<Input, Context> extends [infer _2, infer Input extends string] ? Static.Token.Const<':', Input> extends [infer _3, infer Input extends string] ? TType<Input, Context> extends [infer _4, infer Input extends string] ? [[_0, _1, _2, _3, _4], Input] : [] : [] : [] : [] : []) extends [infer _0 extends [unknown, unknown, unknown, unknown, unknown], infer Input extends string] ? [S.TPropertyMapping<_0, Context>, Input] : [];
export type TPropertyDelimiter<Input extends string, Context extends T.TProperties = {}> = ((Static.Token.Const<',', Input> extends [infer _0, infer Input extends string] ? (Static.Token.Const<'\n', Input> extends [infer _1, infer Input extends string] ? [[_0, _1], Input] : []) : []) extends [
infer _0,
infer Input extends string
] ? [_0, Input] : (Static.Token.Const<';', Input> extends [infer _0, infer Input extends string] ? (Static.Token.Const<'\n', Input> extends [infer _1, infer Input extends string] ? [[_0, _1], Input] : []) : []) extends [
infer _0,
infer Input extends string
] ? [_0, Input] : (Static.Token.Const<',', Input> extends [infer _0, infer Input extends string] ? [[_0], Input] : []) extends [infer _0, infer Input extends string] ? [_0, Input] : (Static.Token.Const<';', Input> extends [infer _0, infer Input extends string] ? [[_0], Input] : []) extends [infer _0, infer Input extends string] ? [_0, Input] : (Static.Token.Const<'\n', Input> extends [infer _0, infer Input extends string] ? [[_0], Input] : []) extends [infer _0, infer Input extends string] ? [_0, Input] : []) extends [infer _0 extends [unknown, unknown] | [unknown], infer Input extends string] ? [S.TPropertyDelimiterMapping<_0, Context>, Input] : [];
export type TPropertyList_0<Input extends string, Context extends T.TProperties, Result extends unknown[] = []> = (TProperty<Input, Context> extends [infer _0, infer Input extends string] ? (TPropertyDelimiter<Input, Context> extends [infer _1, infer Input extends string] ? [[_0, _1], Input] : []) : []) extends [infer _0, infer Input extends string] ? TPropertyList_0<Input, Context, [...Result, _0]> : [Result, Input];
export type TPropertyList<Input extends string, Context extends T.TProperties = {}> = (TPropertyList_0<Input, Context> extends [infer _0, infer Input extends string] ? ((TProperty<Input, Context> extends [infer _0, infer Input extends string] ? [[_0], Input] : []) extends [infer _0, infer Input extends string] ? [_0, Input] : [[], Input] extends [infer _0, infer Input extends string] ? [_0, Input] : []) extends [infer _1, infer Input extends string] ? [[_0, _1], Input] : [] : []) extends [infer _0 extends [unknown, unknown], infer Input extends string] ? [S.TPropertyListMapping<_0, Context>, Input] : [];
export type TObject<Input extends string, Context extends T.TProperties = {}> = (Static.Token.Const<'{', Input> extends [infer _0, infer Input extends string] ? TPropertyList<Input, Context> extends [infer _1, infer Input extends string] ? Static.Token.Const<'}', Input> extends [infer _2, infer Input extends string] ? [[_0, _1, _2], Input] : [] : [] : []) extends [infer _0 extends [unknown, unknown, unknown], infer Input extends string] ? [S.TObjectMapping<_0, Context>, Input] : [];
export type TElementList_0<Input extends string, Context extends T.TProperties, Result extends unknown[] = []> = (TType<Input, Context> extends [infer _0, infer Input extends string] ? (Static.Token.Const<',', Input> extends [infer _1, infer Input extends string] ? [[_0, _1], Input] : []) : []) extends [infer _0, infer Input extends string] ? TElementList_0<Input, Context, [...Result, _0]> : [Result, Input];
export type TElementList<Input extends string, Context extends T.TProperties = {}> = (TElementList_0<Input, Context> extends [infer _0, infer Input extends string] ? ((TType<Input, Context> extends [infer _0, infer Input extends string] ? [[_0], Input] : []) extends [infer _0, infer Input extends string] ? [_0, Input] : [[], Input] extends [infer _0, infer Input extends string] ? [_0, Input] : []) extends [infer _1, infer Input extends string] ? [[_0, _1], Input] : [] : []) extends [infer _0 extends [unknown, unknown], infer Input extends string] ? [S.TElementListMapping<_0, Context>, Input] : [];
export type TTuple<Input extends string, Context extends T.TProperties = {}> = (Static.Token.Const<'[', Input> extends [infer _0, infer Input extends string] ? TElementList<Input, Context> extends [infer _1, infer Input extends string] ? Static.Token.Const<']', Input> extends [infer _2, infer Input extends string] ? [[_0, _1, _2], Input] : [] : [] : []) extends [infer _0 extends [unknown, unknown, unknown], infer Input extends string] ? [S.TTupleMapping<_0, Context>, Input] : [];
export type TParameter<Input extends string, Context extends T.TProperties = {}> = (Static.Token.Ident<Input> extends [infer _0, infer Input extends string] ? Static.Token.Const<':', Input> extends [infer _1, infer Input extends string] ? TType<Input, Context> extends [infer _2, infer Input extends string] ? [[_0, _1, _2], Input] : [] : [] : []) extends [infer _0 extends [unknown, unknown, unknown], infer Input extends string] ? [S.TParameterMapping<_0, Context>, Input] : [];
export type TParameterList_0<Input extends string, Context extends T.TProperties, Result extends unknown[] = []> = (TParameter<Input, Context> extends [infer _0, infer Input extends string] ? (Static.Token.Const<',', Input> extends [infer _1, infer Input extends string] ? [[_0, _1], Input] : []) : []) extends [infer _0, infer Input extends string] ? TParameterList_0<Input, Context, [...Result, _0]> : [Result, Input];
export type TParameterList<Input extends string, Context extends T.TProperties = {}> = (TParameterList_0<Input, Context> extends [infer _0, infer Input extends string] ? ((TParameter<Input, Context> extends [infer _0, infer Input extends string] ? [[_0], Input] : []) extends [infer _0, infer Input extends string] ? [_0, Input] : [[], Input] extends [infer _0, infer Input extends string] ? [_0, Input] : []) extends [infer _1, infer Input extends string] ? [[_0, _1], Input] : [] : []) extends [infer _0 extends [unknown, unknown], infer Input extends string] ? [S.TParameterListMapping<_0, Context>, Input] : [];
export type TFunction<Input extends string, Context extends T.TProperties = {}> = (Static.Token.Const<'(', Input> extends [infer _0, infer Input extends string] ? TParameterList<Input, Context> extends [infer _1, infer Input extends string] ? Static.Token.Const<')', Input> extends [infer _2, infer Input extends string] ? Static.Token.Const<'=>', Input> extends [infer _3, infer Input extends string] ? TType<Input, Context> extends [infer _4, infer Input extends string] ? [[_0, _1, _2, _3, _4], Input] : [] : [] : [] : [] : []) extends [infer _0 extends [unknown, unknown, unknown, unknown, unknown], infer Input extends string] ? [S.TFunctionMapping<_0, Context>, Input] : [];
export type TConstructor<Input extends string, Context extends T.TProperties = {}> = (Static.Token.Const<'new', Input> extends [infer _0, infer Input extends string] ? Static.Token.Const<'(', Input> extends [infer _1, infer Input extends string] ? TParameterList<Input, Context> extends [infer _2, infer Input extends string] ? Static.Token.Const<')', Input> extends [infer _3, infer Input extends string] ? Static.Token.Const<'=>', Input> extends [infer _4, infer Input extends string] ? TType<Input, Context> extends [infer _5, infer Input extends string] ? [[_0, _1, _2, _3, _4, _5], Input] : [] : [] : [] : [] : [] : []) extends [infer _0 extends [unknown, unknown, unknown, unknown, unknown, unknown], infer Input extends string] ? [S.TConstructorMapping<_0, Context>, Input] : [];
export type TMapped<Input extends string, Context extends T.TProperties = {}> = (Static.Token.Const<'{', Input> extends [infer _0, infer Input extends string] ? Static.Token.Const<'[', Input> extends [infer _1, infer Input extends string] ? Static.Token.Ident<Input> extends [infer _2, infer Input extends string] ? Static.Token.Const<'in', Input> extends [infer _3, infer Input extends string] ? TType<Input, Context> extends [infer _4, infer Input extends string] ? Static.Token.Const<']', Input> extends [infer _5, infer Input extends string] ? Static.Token.Const<':', Input> extends [infer _6, infer Input extends string] ? TType<Input, Context> extends [infer _7, infer Input extends string] ? Static.Token.Const<'}', Input> extends [infer _8, infer Input extends string] ? [[_0, _1, _2, _3, _4, _5, _6, _7, _8], Input] : [] : [] : [] : [] : [] : [] : [] : [] : []) extends [infer _0 extends [unknown, unknown, unknown, unknown, unknown, unknown, unknown, unknown, unknown], infer Input extends string] ? [S.TMappedMapping<_0, Context>, Input] : [];
export type TAsyncIterator<Input extends string, Context extends T.TProperties = {}> = (Static.Token.Const<'AsyncIterator', Input> extends [infer _0, infer Input extends string] ? Static.Token.Const<'<', Input> extends [infer _1, infer Input extends string] ? TType<Input, Context> extends [infer _2, infer Input extends string] ? Static.Token.Const<'>', Input> extends [infer _3, infer Input extends string] ? [[_0, _1, _2, _3], Input] : [] : [] : [] : []) extends [infer _0 extends [unknown, unknown, unknown, unknown], infer Input extends string] ? [S.TAsyncIteratorMapping<_0, Context>, Input] : [];
export type TIterator<Input extends string, Context extends T.TProperties = {}> = (Static.Token.Const<'Iterator', Input> extends [infer _0, infer Input extends string] ? Static.Token.Const<'<', Input> extends [infer _1, infer Input extends string] ? TType<Input, Context> extends [infer _2, infer Input extends string] ? Static.Token.Const<'>', Input> extends [infer _3, infer Input extends string] ? [[_0, _1, _2, _3], Input] : [] : [] : [] : []) extends [infer _0 extends [unknown, unknown, unknown, unknown], infer Input extends string] ? [S.TIteratorMapping<_0, Context>, Input] : [];
export type TArgument<Input extends string, Context extends T.TProperties = {}> = (Static.Token.Const<'Argument', Input> extends [infer _0, infer Input extends string] ? Static.Token.Const<'<', Input> extends [infer _1, infer Input extends string] ? TType<Input, Context> extends [infer _2, infer Input extends string] ? Static.Token.Const<'>', Input> extends [infer _3, infer Input extends string] ? [[_0, _1, _2, _3], Input] : [] : [] : [] : []) extends [infer _0 extends [unknown, unknown, unknown, unknown], infer Input extends string] ? [S.TArgumentMapping<_0, Context>, Input] : [];
export type TAwaited<Input extends string, Context extends T.TProperties = {}> = (Static.Token.Const<'Awaited', Input> extends [infer _0, infer Input extends string] ? Static.Token.Const<'<', Input> extends [infer _1, infer Input extends string] ? TType<Input, Context> extends [infer _2, infer Input extends string] ? Static.Token.Const<'>', Input> extends [infer _3, infer Input extends string] ? [[_0, _1, _2, _3], Input] : [] : [] : [] : []) extends [infer _0 extends [unknown, unknown, unknown, unknown], infer Input extends string] ? [S.TAwaitedMapping<_0, Context>, Input] : [];
export type TArray<Input extends string, Context extends T.TProperties = {}> = (Static.Token.Const<'Array', Input> extends [infer _0, infer Input extends string] ? Static.Token.Const<'<', Input> extends [infer _1, infer Input extends string] ? TType<Input, Context> extends [infer _2, infer Input extends string] ? Static.Token.Const<'>', Input> extends [infer _3, infer Input extends string] ? [[_0, _1, _2, _3], Input] : [] : [] : [] : []) extends [infer _0 extends [unknown, unknown, unknown, unknown], infer Input extends string] ? [S.TArrayMapping<_0, Context>, Input] : [];
export type TRecord<Input extends string, Context extends T.TProperties = {}> = (Static.Token.Const<'Record', Input> extends [infer _0, infer Input extends string] ? Static.Token.Const<'<', Input> extends [infer _1, infer Input extends string] ? TType<Input, Context> extends [infer _2, infer Input extends string] ? Static.Token.Const<',', Input> extends [infer _3, infer Input extends string] ? TType<Input, Context> extends [infer _4, infer Input extends string] ? Static.Token.Const<'>', Input> extends [infer _5, infer Input extends string] ? [[_0, _1, _2, _3, _4, _5], Input] : [] : [] : [] : [] : [] : []) extends [infer _0 extends [unknown, unknown, unknown, unknown, unknown, unknown], infer Input extends string] ? [S.TRecordMapping<_0, Context>, Input] : [];
export type TPromise<Input extends string, Context extends T.TProperties = {}> = (Static.Token.Const<'Promise', Input> extends [infer _0, infer Input extends string] ? Static.Token.Const<'<', Input> extends [infer _1, infer Input extends string] ? TType<Input, Context> extends [infer _2, infer Input extends string] ? Static.Token.Const<'>', Input> extends [infer _3, infer Input extends string] ? [[_0, _1, _2, _3], Input] : [] : [] : [] : []) extends [infer _0 extends [unknown, unknown, unknown, unknown], infer Input extends string] ? [S.TPromiseMapping<_0, Context>, Input] : [];
export type TConstructorParameters<Input extends string, Context extends T.TProperties = {}> = (Static.Token.Const<'ConstructorParameters', Input> extends [infer _0, infer Input extends string] ? Static.Token.Const<'<', Input> extends [infer _1, infer Input extends string] ? TType<Input, Context> extends [infer _2, infer Input extends string] ? Static.Token.Const<'>', Input> extends [infer _3, infer Input extends string] ? [[_0, _1, _2, _3], Input] : [] : [] : [] : []) extends [infer _0 extends [unknown, unknown, unknown, unknown], infer Input extends string] ? [S.TConstructorParametersMapping<_0, Context>, Input] : [];
export type TFunctionParameters<Input extends string, Context extends T.TProperties = {}> = (Static.Token.Const<'Parameters', Input> extends [infer _0, infer Input extends string] ? Static.Token.Const<'<', Input> extends [infer _1, infer Input extends string] ? TType<Input, Context> extends [infer _2, infer Input extends string] ? Static.Token.Const<'>', Input> extends [infer _3, infer Input extends string] ? [[_0, _1, _2, _3], Input] : [] : [] : [] : []) extends [infer _0 extends [unknown, unknown, unknown, unknown], infer Input extends string] ? [S.TFunctionParametersMapping<_0, Context>, Input] : [];
export type TInstanceType<Input extends string, Context extends T.TProperties = {}> = (Static.Token.Const<'InstanceType', Input> extends [infer _0, infer Input extends string] ? Static.Token.Const<'<', Input> extends [infer _1, infer Input extends string] ? TType<Input, Context> extends [infer _2, infer Input extends string] ? Static.Token.Const<'>', Input> extends [infer _3, infer Input extends string] ? [[_0, _1, _2, _3], Input] : [] : [] : [] : []) extends [infer _0 extends [unknown, unknown, unknown, unknown], infer Input extends string] ? [S.TInstanceTypeMapping<_0, Context>, Input] : [];
export type TReturnType<Input extends string, Context extends T.TProperties = {}> = (Static.Token.Const<'ReturnType', Input> extends [infer _0, infer Input extends string] ? Static.Token.Const<'<', Input> extends [infer _1, infer Input extends string] ? TType<Input, Context> extends [infer _2, infer Input extends string] ? Static.Token.Const<'>', Input> extends [infer _3, infer Input extends string] ? [[_0, _1, _2, _3], Input] : [] : [] : [] : []) extends [infer _0 extends [unknown, unknown, unknown, unknown], infer Input extends string] ? [S.TReturnTypeMapping<_0, Context>, Input] : [];
export type TPartial<Input extends string, Context extends T.TProperties = {}> = (Static.Token.Const<'Partial', Input> extends [infer _0, infer Input extends string] ? Static.Token.Const<'<', Input> extends [infer _1, infer Input extends string] ? TType<Input, Context> extends [infer _2, infer Input extends string] ? Static.Token.Const<'>', Input> extends [infer _3, infer Input extends string] ? [[_0, _1, _2, _3], Input] : [] : [] : [] : []) extends [infer _0 extends [unknown, unknown, unknown, unknown], infer Input extends string] ? [S.TPartialMapping<_0, Context>, Input] : [];
export type TRequired<Input extends string, Context extends T.TProperties = {}> = (Static.Token.Const<'Required', Input> extends [infer _0, infer Input extends string] ? Static.Token.Const<'<', Input> extends [infer _1, infer Input extends string] ? TType<Input, Context> extends [infer _2, infer Input extends string] ? Static.Token.Const<'>', Input> extends [infer _3, infer Input extends string] ? [[_0, _1, _2, _3], Input] : [] : [] : [] : []) extends [infer _0 extends [unknown, unknown, unknown, unknown], infer Input extends string] ? [S.TRequiredMapping<_0, Context>, Input] : [];
export type TPick<Input extends string, Context extends T.TProperties = {}> = (Static.Token.Const<'Pick', Input> extends [infer _0, infer Input extends string] ? Static.Token.Const<'<', Input> extends [infer _1, infer Input extends string] ? TType<Input, Context> extends [infer _2, infer Input extends string] ? Static.Token.Const<',', Input> extends [infer _3, infer Input extends string] ? TType<Input, Context> extends [infer _4, infer Input extends string] ? Static.Token.Const<'>', Input> extends [infer _5, infer Input extends string] ? [[_0, _1, _2, _3, _4, _5], Input] : [] : [] : [] : [] : [] : []) extends [infer _0 extends [unknown, unknown, unknown, unknown, unknown, unknown], infer Input extends string] ? [S.TPickMapping<_0, Context>, Input] : [];
export type TOmit<Input extends string, Context extends T.TProperties = {}> = (Static.Token.Const<'Omit', Input> extends [infer _0, infer Input extends string] ? Static.Token.Const<'<', Input> extends [infer _1, infer Input extends string] ? TType<Input, Context> extends [infer _2, infer Input extends string] ? Static.Token.Const<',', Input> extends [infer _3, infer Input extends string] ? TType<Input, Context> extends [infer _4, infer Input extends string] ? Static.Token.Const<'>', Input> extends [infer _5, infer Input extends string] ? [[_0, _1, _2, _3, _4, _5], Input] : [] : [] : [] : [] : [] : []) extends [infer _0 extends [unknown, unknown, unknown, unknown, unknown, unknown], infer Input extends string] ? [S.TOmitMapping<_0, Context>, Input] : [];
export type TExclude<Input extends string, Context extends T.TProperties = {}> = (Static.Token.Const<'Exclude', Input> extends [infer _0, infer Input extends string] ? Static.Token.Const<'<', Input> extends [infer _1, infer Input extends string] ? TType<Input, Context> extends [infer _2, infer Input extends string] ? Static.Token.Const<',', Input> extends [infer _3, infer Input extends string] ? TType<Input, Context> extends [infer _4, infer Input extends string] ? Static.Token.Const<'>', Input> extends [infer _5, infer Input extends string] ? [[_0, _1, _2, _3, _4, _5], Input] : [] : [] : [] : [] : [] : []) extends [infer _0 extends [unknown, unknown, unknown, unknown, unknown, unknown], infer Input extends string] ? [S.TExcludeMapping<_0, Context>, Input] : [];
export type TExtract<Input extends string, Context extends T.TProperties = {}> = (Static.Token.Const<'Extract', Input> extends [infer _0, infer Input extends string] ? Static.Token.Const<'<', Input> extends [infer _1, infer Input extends string] ? TType<Input, Context> extends [infer _2, infer Input extends string] ? Static.Token.Const<',', Input> extends [infer _3, infer Input extends string] ? TType<Input, Context> extends [infer _4, infer Input extends string] ? Static.Token.Const<'>', Input> extends [infer _5, infer Input extends string] ? [[_0, _1, _2, _3, _4, _5], Input] : [] : [] : [] : [] : [] : []) extends [infer _0 extends [unknown, unknown, unknown, unknown, unknown, unknown], infer Input extends string] ? [S.TExtractMapping<_0, Context>, Input] : [];
export type TUppercase<Input extends string, Context extends T.TProperties = {}> = (Static.Token.Const<'Uppercase', Input> extends [infer _0, infer Input extends string] ? Static.Token.Const<'<', Input> extends [infer _1, infer Input extends string] ? TType<Input, Context> extends [infer _2, infer Input extends string] ? Static.Token.Const<'>', Input> extends [infer _3, infer Input extends string] ? [[_0, _1, _2, _3], Input] : [] : [] : [] : []) extends [infer _0 extends [unknown, unknown, unknown, unknown], infer Input extends string] ? [S.TUppercaseMapping<_0, Context>, Input] : [];
export type TLowercase<Input extends string, Context extends T.TProperties = {}> = (Static.Token.Const<'Lowercase', Input> extends [infer _0, infer Input extends string] ? Static.Token.Const<'<', Input> extends [infer _1, infer Input extends string] ? TType<Input, Context> extends [infer _2, infer Input extends string] ? Static.Token.Const<'>', Input> extends [infer _3, infer Input extends string] ? [[_0, _1, _2, _3], Input] : [] : [] : [] : []) extends [infer _0 extends [unknown, unknown, unknown, unknown], infer Input extends string] ? [S.TLowercaseMapping<_0, Context>, Input] : [];
export type TCapitalize<Input extends string, Context extends T.TProperties = {}> = (Static.Token.Const<'Capitalize', Input> extends [infer _0, infer Input extends string] ? Static.Token.Const<'<', Input> extends [infer _1, infer Input extends string] ? TType<Input, Context> extends [infer _2, infer Input extends string] ? Static.Token.Const<'>', Input> extends [infer _3, infer Input extends string] ? [[_0, _1, _2, _3], Input] : [] : [] : [] : []) extends [infer _0 extends [unknown, unknown, unknown, unknown], infer Input extends string] ? [S.TCapitalizeMapping<_0, Context>, Input] : [];
export type TUncapitalize<Input extends string, Context extends T.TProperties = {}> = (Static.Token.Const<'Uncapitalize', Input> extends [infer _0, infer Input extends string] ? Static.Token.Const<'<', Input> extends [infer _1, infer Input extends string] ? TType<Input, Context> extends [infer _2, infer Input extends string] ? Static.Token.Const<'>', Input> extends [infer _3, infer Input extends string] ? [[_0, _1, _2, _3], Input] : [] : [] : [] : []) extends [infer _0 extends [unknown, unknown, unknown, unknown], infer Input extends string] ? [S.TUncapitalizeMapping<_0, Context>, Input] : [];
export type TDate<Input extends string, Context extends T.TProperties = {}> = Static.Token.Const<'Date', Input> extends [infer _0 extends 'Date', infer Input extends string] ? [S.TDateMapping<_0, Context>, Input] : [];
export type TUint8Array<Input extends string, Context extends T.TProperties = {}> = Static.Token.Const<'Uint8Array', Input> extends [infer _0 extends 'Uint8Array', infer Input extends string] ? [S.TUint8ArrayMapping<_0, Context>, Input] : [];
export type TReference<Input extends string, Context extends T.TProperties = {}> = Static.Token.Ident<Input> extends [infer _0 extends string, infer Input extends string] ? [S.TReferenceMapping<_0, Context>, Input] : [];
export declare const GenericReferenceParameterList_0: (input: string, context: T.TProperties, result?: unknown[]) => [unknown[], string];
export declare const GenericReferenceParameterList: (input: string, context?: T.TProperties) => [unknown, string] | [];
export declare const GenericReference: (input: string, context?: T.TProperties) => [unknown, string] | [];
export declare const GenericArgumentsList_0: (input: string, context: T.TProperties, result?: unknown[]) => [unknown[], string];
export declare const GenericArgumentsList: (input: string, context?: T.TProperties) => [unknown, string] | [];
export declare const GenericArguments: (input: string, context?: T.TProperties) => [unknown, string] | [];
export declare const KeywordString: (input: string, context?: T.TProperties) => [unknown, string] | [];
export declare const KeywordNumber: (input: string, context?: T.TProperties) => [unknown, string] | [];
export declare const KeywordBoolean: (input: string, context?: T.TProperties) => [unknown, string] | [];
export declare const KeywordUndefined: (input: string, context?: T.TProperties) => [unknown, string] | [];
export declare const KeywordNull: (input: string, context?: T.TProperties) => [unknown, string] | [];
export declare const KeywordInteger: (input: string, context?: T.TProperties) => [unknown, string] | [];
export declare const KeywordBigInt: (input: string, context?: T.TProperties) => [unknown, string] | [];
export declare const KeywordUnknown: (input: string, context?: T.TProperties) => [unknown, string] | [];
export declare const KeywordAny: (input: string, context?: T.TProperties) => [unknown, string] | [];
export declare const KeywordNever: (input: string, context?: T.TProperties) => [unknown, string] | [];
export declare const KeywordSymbol: (input: string, context?: T.TProperties) => [unknown, string] | [];
export declare const KeywordVoid: (input: string, context?: T.TProperties) => [unknown, string] | [];
export declare const Keyword: (input: string, context?: T.TProperties) => [unknown, string] | [];
export declare const LiteralString: (input: string, context?: T.TProperties) => [unknown, string] | [];
export declare const LiteralNumber: (input: string, context?: T.TProperties) => [unknown, string] | [];
export declare const LiteralBoolean: (input: string, context?: T.TProperties) => [unknown, string] | [];
export declare const Literal: (input: string, context?: T.TProperties) => [unknown, string] | [];
export declare const KeyOf: (input: string, context?: T.TProperties) => [unknown, string] | [];
export declare const IndexArray_0: (input: string, context: T.TProperties, result?: unknown[]) => [unknown[], string];
export declare const IndexArray: (input: string, context?: T.TProperties) => [unknown, string] | [];
export declare const Extends: (input: string, context?: T.TProperties) => [unknown, string] | [];
export declare const Base: (input: string, context?: T.TProperties) => [unknown, string] | [];
export declare const Factor: (input: string, context?: T.TProperties) => [unknown, string] | [];
export declare const ExprTermTail: (input: string, context?: T.TProperties) => [unknown, string] | [];
export declare const ExprTerm: (input: string, context?: T.TProperties) => [unknown, string] | [];
export declare const ExprTail: (input: string, context?: T.TProperties) => [unknown, string] | [];
export declare const Expr: (input: string, context?: T.TProperties) => [unknown, string] | [];
export declare const Type: (input: string, context?: T.TProperties) => [unknown, string] | [];
export declare const PropertyKey: (input: string, context?: T.TProperties) => [unknown, string] | [];
export declare const Readonly: (input: string, context?: T.TProperties) => [unknown, string] | [];
export declare const Optional: (input: string, context?: T.TProperties) => [unknown, string] | [];
export declare const Property: (input: string, context?: T.TProperties) => [unknown, string] | [];
export declare const PropertyDelimiter: (input: string, context?: T.TProperties) => [unknown, string] | [];
export declare const PropertyList_0: (input: string, context: T.TProperties, result?: unknown[]) => [unknown[], string];
export declare const PropertyList: (input: string, context?: T.TProperties) => [unknown, string] | [];
export declare const _Object: (input: string, context?: T.TProperties) => [unknown, string] | [];
export declare const ElementList_0: (input: string, context: T.TProperties, result?: unknown[]) => [unknown[], string];
export declare const ElementList: (input: string, context?: T.TProperties) => [unknown, string] | [];
export declare const Tuple: (input: string, context?: T.TProperties) => [unknown, string] | [];
export declare const Parameter: (input: string, context?: T.TProperties) => [unknown, string] | [];
export declare const ParameterList_0: (input: string, context: T.TProperties, result?: unknown[]) => [unknown[], string];
export declare const ParameterList: (input: string, context?: T.TProperties) => [unknown, string] | [];
export declare const Function: (input: string, context?: T.TProperties) => [unknown, string] | [];
export declare const Constructor: (input: string, context?: T.TProperties) => [unknown, string] | [];
export declare const Mapped: (input: string, context?: T.TProperties) => [unknown, string] | [];
export declare const AsyncIterator: (input: string, context?: T.TProperties) => [unknown, string] | [];
export declare const Iterator: (input: string, context?: T.TProperties) => [unknown, string] | [];
export declare const Argument: (input: string, context?: T.TProperties) => [unknown, string] | [];
export declare const Awaited: (input: string, context?: T.TProperties) => [unknown, string] | [];
export declare const Array: (input: string, context?: T.TProperties) => [unknown, string] | [];
export declare const Record: (input: string, context?: T.TProperties) => [unknown, string] | [];
export declare const Promise: (input: string, context?: T.TProperties) => [unknown, string] | [];
export declare const ConstructorParameters: (input: string, context?: T.TProperties) => [unknown, string] | [];
export declare const FunctionParameters: (input: string, context?: T.TProperties) => [unknown, string] | [];
export declare const InstanceType: (input: string, context?: T.TProperties) => [unknown, string] | [];
export declare const ReturnType: (input: string, context?: T.TProperties) => [unknown, string] | [];
export declare const Partial: (input: string, context?: T.TProperties) => [unknown, string] | [];
export declare const Required: (input: string, context?: T.TProperties) => [unknown, string] | [];
export declare const Pick: (input: string, context?: T.TProperties) => [unknown, string] | [];
export declare const Omit: (input: string, context?: T.TProperties) => [unknown, string] | [];
export declare const Exclude: (input: string, context?: T.TProperties) => [unknown, string] | [];
export declare const Extract: (input: string, context?: T.TProperties) => [unknown, string] | [];
export declare const Uppercase: (input: string, context?: T.TProperties) => [unknown, string] | [];
export declare const Lowercase: (input: string, context?: T.TProperties) => [unknown, string] | [];
export declare const Capitalize: (input: string, context?: T.TProperties) => [unknown, string] | [];
export declare const Uncapitalize: (input: string, context?: T.TProperties) => [unknown, string] | [];
export declare const Date: (input: string, context?: T.TProperties) => [unknown, string] | [];
export declare const Uint8Array: (input: string, context?: T.TProperties) => [unknown, string] | [];
export declare const Reference: (input: string, context?: T.TProperties) => [unknown, string] | [];
+191
View File
@@ -0,0 +1,191 @@
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
var ownKeys = function(o) {
ownKeys = Object.getOwnPropertyNames || function (o) {
var ar = [];
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
return ar;
};
return ownKeys(o);
};
return function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
__setModuleDefault(result, mod);
return result;
};
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.Constructor = exports.Function = exports.ParameterList = exports.ParameterList_0 = exports.Parameter = exports.Tuple = exports.ElementList = exports.ElementList_0 = exports._Object = exports.PropertyList = exports.PropertyList_0 = exports.PropertyDelimiter = exports.Property = exports.Optional = exports.Readonly = exports.PropertyKey = exports.Type = exports.Expr = exports.ExprTail = exports.ExprTerm = exports.ExprTermTail = exports.Factor = exports.Base = exports.Extends = exports.IndexArray = exports.IndexArray_0 = exports.KeyOf = exports.Literal = exports.LiteralBoolean = exports.LiteralNumber = exports.LiteralString = exports.Keyword = exports.KeywordVoid = exports.KeywordSymbol = exports.KeywordNever = exports.KeywordAny = exports.KeywordUnknown = exports.KeywordBigInt = exports.KeywordInteger = exports.KeywordNull = exports.KeywordUndefined = exports.KeywordBoolean = exports.KeywordNumber = exports.KeywordString = exports.GenericArguments = exports.GenericArgumentsList = exports.GenericArgumentsList_0 = exports.GenericReference = exports.GenericReferenceParameterList = exports.GenericReferenceParameterList_0 = void 0;
exports.Reference = exports.Uint8Array = exports.Date = exports.Uncapitalize = exports.Capitalize = exports.Lowercase = exports.Uppercase = exports.Extract = exports.Exclude = exports.Omit = exports.Pick = exports.Required = exports.Partial = exports.ReturnType = exports.InstanceType = exports.FunctionParameters = exports.ConstructorParameters = exports.Promise = exports.Record = exports.Array = exports.Awaited = exports.Argument = exports.Iterator = exports.AsyncIterator = exports.Mapped = void 0;
const index_1 = require("../parser/index");
const S = __importStar(require("./mapping"));
const If = (result, left, right = () => []) => (result.length === 2 ? left(result) : right());
const GenericReferenceParameterList_0 = (input, context, result = []) => If(If((0, exports.Type)(input, context), ([_0, input]) => If(index_1.Runtime.Token.Const(',', input), ([_1, input]) => [[_0, _1], input])), ([_0, input]) => (0, exports.GenericReferenceParameterList_0)(input, context, [...result, _0]), () => [result, input]);
exports.GenericReferenceParameterList_0 = GenericReferenceParameterList_0;
const GenericReferenceParameterList = (input, context = {}) => If(If((0, exports.GenericReferenceParameterList_0)(input, context), ([_0, input]) => If(If(If((0, exports.Type)(input, context), ([_0, input]) => [[_0], input]), ([_0, input]) => [_0, input], () => If([[], input], ([_0, input]) => [_0, input], () => [])), ([_1, input]) => [[_0, _1], input])), ([_0, input]) => [S.GenericReferenceParameterListMapping(_0, context), input]);
exports.GenericReferenceParameterList = GenericReferenceParameterList;
const GenericReference = (input, context = {}) => If(If(index_1.Runtime.Token.Ident(input), ([_0, input]) => If(index_1.Runtime.Token.Const('<', input), ([_1, input]) => If((0, exports.GenericReferenceParameterList)(input, context), ([_2, input]) => If(index_1.Runtime.Token.Const('>', input), ([_3, input]) => [[_0, _1, _2, _3], input])))), ([_0, input]) => [S.GenericReferenceMapping(_0, context), input]);
exports.GenericReference = GenericReference;
const GenericArgumentsList_0 = (input, context, result = []) => If(If(index_1.Runtime.Token.Ident(input), ([_0, input]) => If(index_1.Runtime.Token.Const(',', input), ([_1, input]) => [[_0, _1], input])), ([_0, input]) => (0, exports.GenericArgumentsList_0)(input, context, [...result, _0]), () => [result, input]);
exports.GenericArgumentsList_0 = GenericArgumentsList_0;
const GenericArgumentsList = (input, context = {}) => If(If((0, exports.GenericArgumentsList_0)(input, context), ([_0, input]) => If(If(If(index_1.Runtime.Token.Ident(input), ([_0, input]) => [[_0], input]), ([_0, input]) => [_0, input], () => If([[], input], ([_0, input]) => [_0, input], () => [])), ([_1, input]) => [[_0, _1], input])), ([_0, input]) => [S.GenericArgumentsListMapping(_0, context), input]);
exports.GenericArgumentsList = GenericArgumentsList;
const GenericArguments = (input, context = {}) => If(If(index_1.Runtime.Token.Const('<', input), ([_0, input]) => If((0, exports.GenericArgumentsList)(input, context), ([_1, input]) => If(index_1.Runtime.Token.Const('>', input), ([_2, input]) => [[_0, _1, _2], input]))), ([_0, input]) => [S.GenericArgumentsMapping(_0, context), input]);
exports.GenericArguments = GenericArguments;
const KeywordString = (input, context = {}) => If(index_1.Runtime.Token.Const('string', input), ([_0, input]) => [S.KeywordStringMapping(_0, context), input]);
exports.KeywordString = KeywordString;
const KeywordNumber = (input, context = {}) => If(index_1.Runtime.Token.Const('number', input), ([_0, input]) => [S.KeywordNumberMapping(_0, context), input]);
exports.KeywordNumber = KeywordNumber;
const KeywordBoolean = (input, context = {}) => If(index_1.Runtime.Token.Const('boolean', input), ([_0, input]) => [S.KeywordBooleanMapping(_0, context), input]);
exports.KeywordBoolean = KeywordBoolean;
const KeywordUndefined = (input, context = {}) => If(index_1.Runtime.Token.Const('undefined', input), ([_0, input]) => [S.KeywordUndefinedMapping(_0, context), input]);
exports.KeywordUndefined = KeywordUndefined;
const KeywordNull = (input, context = {}) => If(index_1.Runtime.Token.Const('null', input), ([_0, input]) => [S.KeywordNullMapping(_0, context), input]);
exports.KeywordNull = KeywordNull;
const KeywordInteger = (input, context = {}) => If(index_1.Runtime.Token.Const('integer', input), ([_0, input]) => [S.KeywordIntegerMapping(_0, context), input]);
exports.KeywordInteger = KeywordInteger;
const KeywordBigInt = (input, context = {}) => If(index_1.Runtime.Token.Const('bigint', input), ([_0, input]) => [S.KeywordBigIntMapping(_0, context), input]);
exports.KeywordBigInt = KeywordBigInt;
const KeywordUnknown = (input, context = {}) => If(index_1.Runtime.Token.Const('unknown', input), ([_0, input]) => [S.KeywordUnknownMapping(_0, context), input]);
exports.KeywordUnknown = KeywordUnknown;
const KeywordAny = (input, context = {}) => If(index_1.Runtime.Token.Const('any', input), ([_0, input]) => [S.KeywordAnyMapping(_0, context), input]);
exports.KeywordAny = KeywordAny;
const KeywordNever = (input, context = {}) => If(index_1.Runtime.Token.Const('never', input), ([_0, input]) => [S.KeywordNeverMapping(_0, context), input]);
exports.KeywordNever = KeywordNever;
const KeywordSymbol = (input, context = {}) => If(index_1.Runtime.Token.Const('symbol', input), ([_0, input]) => [S.KeywordSymbolMapping(_0, context), input]);
exports.KeywordSymbol = KeywordSymbol;
const KeywordVoid = (input, context = {}) => If(index_1.Runtime.Token.Const('void', input), ([_0, input]) => [S.KeywordVoidMapping(_0, context), input]);
exports.KeywordVoid = KeywordVoid;
const Keyword = (input, context = {}) => If(If((0, exports.KeywordString)(input, context), ([_0, input]) => [_0, input], () => If((0, exports.KeywordNumber)(input, context), ([_0, input]) => [_0, input], () => If((0, exports.KeywordBoolean)(input, context), ([_0, input]) => [_0, input], () => If((0, exports.KeywordUndefined)(input, context), ([_0, input]) => [_0, input], () => If((0, exports.KeywordNull)(input, context), ([_0, input]) => [_0, input], () => If((0, exports.KeywordInteger)(input, context), ([_0, input]) => [_0, input], () => If((0, exports.KeywordBigInt)(input, context), ([_0, input]) => [_0, input], () => If((0, exports.KeywordUnknown)(input, context), ([_0, input]) => [_0, input], () => If((0, exports.KeywordAny)(input, context), ([_0, input]) => [_0, input], () => If((0, exports.KeywordNever)(input, context), ([_0, input]) => [_0, input], () => If((0, exports.KeywordSymbol)(input, context), ([_0, input]) => [_0, input], () => If((0, exports.KeywordVoid)(input, context), ([_0, input]) => [_0, input], () => [])))))))))))), ([_0, input]) => [S.KeywordMapping(_0, context), input]);
exports.Keyword = Keyword;
const LiteralString = (input, context = {}) => If(index_1.Runtime.Token.String(["'", '"', '`'], input), ([_0, input]) => [S.LiteralStringMapping(_0, context), input]);
exports.LiteralString = LiteralString;
const LiteralNumber = (input, context = {}) => If(index_1.Runtime.Token.Number(input), ([_0, input]) => [S.LiteralNumberMapping(_0, context), input]);
exports.LiteralNumber = LiteralNumber;
const LiteralBoolean = (input, context = {}) => If(If(index_1.Runtime.Token.Const('true', input), ([_0, input]) => [_0, input], () => If(index_1.Runtime.Token.Const('false', input), ([_0, input]) => [_0, input], () => [])), ([_0, input]) => [S.LiteralBooleanMapping(_0, context), input]);
exports.LiteralBoolean = LiteralBoolean;
const Literal = (input, context = {}) => If(If((0, exports.LiteralBoolean)(input, context), ([_0, input]) => [_0, input], () => If((0, exports.LiteralNumber)(input, context), ([_0, input]) => [_0, input], () => If((0, exports.LiteralString)(input, context), ([_0, input]) => [_0, input], () => []))), ([_0, input]) => [S.LiteralMapping(_0, context), input]);
exports.Literal = Literal;
const KeyOf = (input, context = {}) => If(If(If(index_1.Runtime.Token.Const('keyof', input), ([_0, input]) => [[_0], input]), ([_0, input]) => [_0, input], () => If([[], input], ([_0, input]) => [_0, input], () => [])), ([_0, input]) => [S.KeyOfMapping(_0, context), input]);
exports.KeyOf = KeyOf;
const IndexArray_0 = (input, context, result = []) => If(If(If(index_1.Runtime.Token.Const('[', input), ([_0, input]) => If((0, exports.Type)(input, context), ([_1, input]) => If(index_1.Runtime.Token.Const(']', input), ([_2, input]) => [[_0, _1, _2], input]))), ([_0, input]) => [_0, input], () => If(If(index_1.Runtime.Token.Const('[', input), ([_0, input]) => If(index_1.Runtime.Token.Const(']', input), ([_1, input]) => [[_0, _1], input])), ([_0, input]) => [_0, input], () => [])), ([_0, input]) => (0, exports.IndexArray_0)(input, context, [...result, _0]), () => [result, input]);
exports.IndexArray_0 = IndexArray_0;
const IndexArray = (input, context = {}) => If((0, exports.IndexArray_0)(input, context), ([_0, input]) => [S.IndexArrayMapping(_0, context), input]);
exports.IndexArray = IndexArray;
const Extends = (input, context = {}) => If(If(If(index_1.Runtime.Token.Const('extends', input), ([_0, input]) => If((0, exports.Type)(input, context), ([_1, input]) => If(index_1.Runtime.Token.Const('?', input), ([_2, input]) => If((0, exports.Type)(input, context), ([_3, input]) => If(index_1.Runtime.Token.Const(':', input), ([_4, input]) => If((0, exports.Type)(input, context), ([_5, input]) => [[_0, _1, _2, _3, _4, _5], input])))))), ([_0, input]) => [_0, input], () => If([[], input], ([_0, input]) => [_0, input], () => [])), ([_0, input]) => [S.ExtendsMapping(_0, context), input]);
exports.Extends = Extends;
const Base = (input, context = {}) => If(If(If(index_1.Runtime.Token.Const('(', input), ([_0, input]) => If((0, exports.Type)(input, context), ([_1, input]) => If(index_1.Runtime.Token.Const(')', input), ([_2, input]) => [[_0, _1, _2], input]))), ([_0, input]) => [_0, input], () => If((0, exports.Keyword)(input, context), ([_0, input]) => [_0, input], () => If((0, exports._Object)(input, context), ([_0, input]) => [_0, input], () => If((0, exports.Tuple)(input, context), ([_0, input]) => [_0, input], () => If((0, exports.Literal)(input, context), ([_0, input]) => [_0, input], () => If((0, exports.Constructor)(input, context), ([_0, input]) => [_0, input], () => If((0, exports.Function)(input, context), ([_0, input]) => [_0, input], () => If((0, exports.Mapped)(input, context), ([_0, input]) => [_0, input], () => If((0, exports.AsyncIterator)(input, context), ([_0, input]) => [_0, input], () => If((0, exports.Iterator)(input, context), ([_0, input]) => [_0, input], () => If((0, exports.ConstructorParameters)(input, context), ([_0, input]) => [_0, input], () => If((0, exports.FunctionParameters)(input, context), ([_0, input]) => [_0, input], () => If((0, exports.InstanceType)(input, context), ([_0, input]) => [_0, input], () => If((0, exports.ReturnType)(input, context), ([_0, input]) => [_0, input], () => If((0, exports.Argument)(input, context), ([_0, input]) => [_0, input], () => If((0, exports.Awaited)(input, context), ([_0, input]) => [_0, input], () => If((0, exports.Array)(input, context), ([_0, input]) => [_0, input], () => If((0, exports.Record)(input, context), ([_0, input]) => [_0, input], () => If((0, exports.Promise)(input, context), ([_0, input]) => [_0, input], () => If((0, exports.Partial)(input, context), ([_0, input]) => [_0, input], () => If((0, exports.Required)(input, context), ([_0, input]) => [_0, input], () => If((0, exports.Pick)(input, context), ([_0, input]) => [_0, input], () => If((0, exports.Omit)(input, context), ([_0, input]) => [_0, input], () => If((0, exports.Exclude)(input, context), ([_0, input]) => [_0, input], () => If((0, exports.Extract)(input, context), ([_0, input]) => [_0, input], () => If((0, exports.Uppercase)(input, context), ([_0, input]) => [_0, input], () => If((0, exports.Lowercase)(input, context), ([_0, input]) => [_0, input], () => If((0, exports.Capitalize)(input, context), ([_0, input]) => [_0, input], () => If((0, exports.Uncapitalize)(input, context), ([_0, input]) => [_0, input], () => If((0, exports.Date)(input, context), ([_0, input]) => [_0, input], () => If((0, exports.Uint8Array)(input, context), ([_0, input]) => [_0, input], () => If((0, exports.GenericReference)(input, context), ([_0, input]) => [_0, input], () => If((0, exports.Reference)(input, context), ([_0, input]) => [_0, input], () => []))))))))))))))))))))))))))))))))), ([_0, input]) => [S.BaseMapping(_0, context), input]);
exports.Base = Base;
const Factor = (input, context = {}) => If(If((0, exports.KeyOf)(input, context), ([_0, input]) => If((0, exports.Base)(input, context), ([_1, input]) => If((0, exports.IndexArray)(input, context), ([_2, input]) => If((0, exports.Extends)(input, context), ([_3, input]) => [[_0, _1, _2, _3], input])))), ([_0, input]) => [S.FactorMapping(_0, context), input]);
exports.Factor = Factor;
const ExprTermTail = (input, context = {}) => If(If(If(index_1.Runtime.Token.Const('&', input), ([_0, input]) => If((0, exports.Factor)(input, context), ([_1, input]) => If((0, exports.ExprTermTail)(input, context), ([_2, input]) => [[_0, _1, _2], input]))), ([_0, input]) => [_0, input], () => If([[], input], ([_0, input]) => [_0, input], () => [])), ([_0, input]) => [S.ExprTermTailMapping(_0, context), input]);
exports.ExprTermTail = ExprTermTail;
const ExprTerm = (input, context = {}) => If(If((0, exports.Factor)(input, context), ([_0, input]) => If((0, exports.ExprTermTail)(input, context), ([_1, input]) => [[_0, _1], input])), ([_0, input]) => [S.ExprTermMapping(_0, context), input]);
exports.ExprTerm = ExprTerm;
const ExprTail = (input, context = {}) => If(If(If(index_1.Runtime.Token.Const('|', input), ([_0, input]) => If((0, exports.ExprTerm)(input, context), ([_1, input]) => If((0, exports.ExprTail)(input, context), ([_2, input]) => [[_0, _1, _2], input]))), ([_0, input]) => [_0, input], () => If([[], input], ([_0, input]) => [_0, input], () => [])), ([_0, input]) => [S.ExprTailMapping(_0, context), input]);
exports.ExprTail = ExprTail;
const Expr = (input, context = {}) => If(If((0, exports.ExprTerm)(input, context), ([_0, input]) => If((0, exports.ExprTail)(input, context), ([_1, input]) => [[_0, _1], input])), ([_0, input]) => [S.ExprMapping(_0, context), input]);
exports.Expr = Expr;
const Type = (input, context = {}) => If(If(If((0, exports.GenericArguments)(input, context), ([_0, input]) => (0, exports.Expr)(input, _0), () => []), ([_0, input]) => [_0, input], () => If((0, exports.Expr)(input, context), ([_0, input]) => [_0, input], () => [])), ([_0, input]) => [S.TypeMapping(_0, context), input]);
exports.Type = Type;
const PropertyKey = (input, context = {}) => If(If(index_1.Runtime.Token.Ident(input), ([_0, input]) => [_0, input], () => If(index_1.Runtime.Token.String(["'", '"'], input), ([_0, input]) => [_0, input], () => [])), ([_0, input]) => [S.PropertyKeyMapping(_0, context), input]);
exports.PropertyKey = PropertyKey;
const Readonly = (input, context = {}) => If(If(If(index_1.Runtime.Token.Const('readonly', input), ([_0, input]) => [[_0], input]), ([_0, input]) => [_0, input], () => If([[], input], ([_0, input]) => [_0, input], () => [])), ([_0, input]) => [S.ReadonlyMapping(_0, context), input]);
exports.Readonly = Readonly;
const Optional = (input, context = {}) => If(If(If(index_1.Runtime.Token.Const('?', input), ([_0, input]) => [[_0], input]), ([_0, input]) => [_0, input], () => If([[], input], ([_0, input]) => [_0, input], () => [])), ([_0, input]) => [S.OptionalMapping(_0, context), input]);
exports.Optional = Optional;
const Property = (input, context = {}) => If(If((0, exports.Readonly)(input, context), ([_0, input]) => If((0, exports.PropertyKey)(input, context), ([_1, input]) => If((0, exports.Optional)(input, context), ([_2, input]) => If(index_1.Runtime.Token.Const(':', input), ([_3, input]) => If((0, exports.Type)(input, context), ([_4, input]) => [[_0, _1, _2, _3, _4], input]))))), ([_0, input]) => [S.PropertyMapping(_0, context), input]);
exports.Property = Property;
const PropertyDelimiter = (input, context = {}) => If(If(If(index_1.Runtime.Token.Const(',', input), ([_0, input]) => If(index_1.Runtime.Token.Const('\n', input), ([_1, input]) => [[_0, _1], input])), ([_0, input]) => [_0, input], () => If(If(index_1.Runtime.Token.Const(';', input), ([_0, input]) => If(index_1.Runtime.Token.Const('\n', input), ([_1, input]) => [[_0, _1], input])), ([_0, input]) => [_0, input], () => If(If(index_1.Runtime.Token.Const(',', input), ([_0, input]) => [[_0], input]), ([_0, input]) => [_0, input], () => If(If(index_1.Runtime.Token.Const(';', input), ([_0, input]) => [[_0], input]), ([_0, input]) => [_0, input], () => If(If(index_1.Runtime.Token.Const('\n', input), ([_0, input]) => [[_0], input]), ([_0, input]) => [_0, input], () => []))))), ([_0, input]) => [S.PropertyDelimiterMapping(_0, context), input]);
exports.PropertyDelimiter = PropertyDelimiter;
const PropertyList_0 = (input, context, result = []) => If(If((0, exports.Property)(input, context), ([_0, input]) => If((0, exports.PropertyDelimiter)(input, context), ([_1, input]) => [[_0, _1], input])), ([_0, input]) => (0, exports.PropertyList_0)(input, context, [...result, _0]), () => [result, input]);
exports.PropertyList_0 = PropertyList_0;
const PropertyList = (input, context = {}) => If(If((0, exports.PropertyList_0)(input, context), ([_0, input]) => If(If(If((0, exports.Property)(input, context), ([_0, input]) => [[_0], input]), ([_0, input]) => [_0, input], () => If([[], input], ([_0, input]) => [_0, input], () => [])), ([_1, input]) => [[_0, _1], input])), ([_0, input]) => [S.PropertyListMapping(_0, context), input]);
exports.PropertyList = PropertyList;
const _Object = (input, context = {}) => If(If(index_1.Runtime.Token.Const('{', input), ([_0, input]) => If((0, exports.PropertyList)(input, context), ([_1, input]) => If(index_1.Runtime.Token.Const('}', input), ([_2, input]) => [[_0, _1, _2], input]))), ([_0, input]) => [S.ObjectMapping(_0, context), input]);
exports._Object = _Object;
const ElementList_0 = (input, context, result = []) => If(If((0, exports.Type)(input, context), ([_0, input]) => If(index_1.Runtime.Token.Const(',', input), ([_1, input]) => [[_0, _1], input])), ([_0, input]) => (0, exports.ElementList_0)(input, context, [...result, _0]), () => [result, input]);
exports.ElementList_0 = ElementList_0;
const ElementList = (input, context = {}) => If(If((0, exports.ElementList_0)(input, context), ([_0, input]) => If(If(If((0, exports.Type)(input, context), ([_0, input]) => [[_0], input]), ([_0, input]) => [_0, input], () => If([[], input], ([_0, input]) => [_0, input], () => [])), ([_1, input]) => [[_0, _1], input])), ([_0, input]) => [S.ElementListMapping(_0, context), input]);
exports.ElementList = ElementList;
const Tuple = (input, context = {}) => If(If(index_1.Runtime.Token.Const('[', input), ([_0, input]) => If((0, exports.ElementList)(input, context), ([_1, input]) => If(index_1.Runtime.Token.Const(']', input), ([_2, input]) => [[_0, _1, _2], input]))), ([_0, input]) => [S.TupleMapping(_0, context), input]);
exports.Tuple = Tuple;
const Parameter = (input, context = {}) => If(If(index_1.Runtime.Token.Ident(input), ([_0, input]) => If(index_1.Runtime.Token.Const(':', input), ([_1, input]) => If((0, exports.Type)(input, context), ([_2, input]) => [[_0, _1, _2], input]))), ([_0, input]) => [S.ParameterMapping(_0, context), input]);
exports.Parameter = Parameter;
const ParameterList_0 = (input, context, result = []) => If(If((0, exports.Parameter)(input, context), ([_0, input]) => If(index_1.Runtime.Token.Const(',', input), ([_1, input]) => [[_0, _1], input])), ([_0, input]) => (0, exports.ParameterList_0)(input, context, [...result, _0]), () => [result, input]);
exports.ParameterList_0 = ParameterList_0;
const ParameterList = (input, context = {}) => If(If((0, exports.ParameterList_0)(input, context), ([_0, input]) => If(If(If((0, exports.Parameter)(input, context), ([_0, input]) => [[_0], input]), ([_0, input]) => [_0, input], () => If([[], input], ([_0, input]) => [_0, input], () => [])), ([_1, input]) => [[_0, _1], input])), ([_0, input]) => [S.ParameterListMapping(_0, context), input]);
exports.ParameterList = ParameterList;
const Function = (input, context = {}) => If(If(index_1.Runtime.Token.Const('(', input), ([_0, input]) => If((0, exports.ParameterList)(input, context), ([_1, input]) => If(index_1.Runtime.Token.Const(')', input), ([_2, input]) => If(index_1.Runtime.Token.Const('=>', input), ([_3, input]) => If((0, exports.Type)(input, context), ([_4, input]) => [[_0, _1, _2, _3, _4], input]))))), ([_0, input]) => [S.FunctionMapping(_0, context), input]);
exports.Function = Function;
const Constructor = (input, context = {}) => If(If(index_1.Runtime.Token.Const('new', input), ([_0, input]) => If(index_1.Runtime.Token.Const('(', input), ([_1, input]) => If((0, exports.ParameterList)(input, context), ([_2, input]) => If(index_1.Runtime.Token.Const(')', input), ([_3, input]) => If(index_1.Runtime.Token.Const('=>', input), ([_4, input]) => If((0, exports.Type)(input, context), ([_5, input]) => [[_0, _1, _2, _3, _4, _5], input])))))), ([_0, input]) => [S.ConstructorMapping(_0, context), input]);
exports.Constructor = Constructor;
const Mapped = (input, context = {}) => If(If(index_1.Runtime.Token.Const('{', input), ([_0, input]) => If(index_1.Runtime.Token.Const('[', input), ([_1, input]) => If(index_1.Runtime.Token.Ident(input), ([_2, input]) => If(index_1.Runtime.Token.Const('in', input), ([_3, input]) => If((0, exports.Type)(input, context), ([_4, input]) => If(index_1.Runtime.Token.Const(']', input), ([_5, input]) => If(index_1.Runtime.Token.Const(':', input), ([_6, input]) => If((0, exports.Type)(input, context), ([_7, input]) => If(index_1.Runtime.Token.Const('}', input), ([_8, input]) => [[_0, _1, _2, _3, _4, _5, _6, _7, _8], input]))))))))), ([_0, input]) => [S.MappedMapping(_0, context), input]);
exports.Mapped = Mapped;
const AsyncIterator = (input, context = {}) => If(If(index_1.Runtime.Token.Const('AsyncIterator', input), ([_0, input]) => If(index_1.Runtime.Token.Const('<', input), ([_1, input]) => If((0, exports.Type)(input, context), ([_2, input]) => If(index_1.Runtime.Token.Const('>', input), ([_3, input]) => [[_0, _1, _2, _3], input])))), ([_0, input]) => [S.AsyncIteratorMapping(_0, context), input]);
exports.AsyncIterator = AsyncIterator;
const Iterator = (input, context = {}) => If(If(index_1.Runtime.Token.Const('Iterator', input), ([_0, input]) => If(index_1.Runtime.Token.Const('<', input), ([_1, input]) => If((0, exports.Type)(input, context), ([_2, input]) => If(index_1.Runtime.Token.Const('>', input), ([_3, input]) => [[_0, _1, _2, _3], input])))), ([_0, input]) => [S.IteratorMapping(_0, context), input]);
exports.Iterator = Iterator;
const Argument = (input, context = {}) => If(If(index_1.Runtime.Token.Const('Argument', input), ([_0, input]) => If(index_1.Runtime.Token.Const('<', input), ([_1, input]) => If((0, exports.Type)(input, context), ([_2, input]) => If(index_1.Runtime.Token.Const('>', input), ([_3, input]) => [[_0, _1, _2, _3], input])))), ([_0, input]) => [S.ArgumentMapping(_0, context), input]);
exports.Argument = Argument;
const Awaited = (input, context = {}) => If(If(index_1.Runtime.Token.Const('Awaited', input), ([_0, input]) => If(index_1.Runtime.Token.Const('<', input), ([_1, input]) => If((0, exports.Type)(input, context), ([_2, input]) => If(index_1.Runtime.Token.Const('>', input), ([_3, input]) => [[_0, _1, _2, _3], input])))), ([_0, input]) => [S.AwaitedMapping(_0, context), input]);
exports.Awaited = Awaited;
const Array = (input, context = {}) => If(If(index_1.Runtime.Token.Const('Array', input), ([_0, input]) => If(index_1.Runtime.Token.Const('<', input), ([_1, input]) => If((0, exports.Type)(input, context), ([_2, input]) => If(index_1.Runtime.Token.Const('>', input), ([_3, input]) => [[_0, _1, _2, _3], input])))), ([_0, input]) => [S.ArrayMapping(_0, context), input]);
exports.Array = Array;
const Record = (input, context = {}) => If(If(index_1.Runtime.Token.Const('Record', input), ([_0, input]) => If(index_1.Runtime.Token.Const('<', input), ([_1, input]) => If((0, exports.Type)(input, context), ([_2, input]) => If(index_1.Runtime.Token.Const(',', input), ([_3, input]) => If((0, exports.Type)(input, context), ([_4, input]) => If(index_1.Runtime.Token.Const('>', input), ([_5, input]) => [[_0, _1, _2, _3, _4, _5], input])))))), ([_0, input]) => [S.RecordMapping(_0, context), input]);
exports.Record = Record;
const Promise = (input, context = {}) => If(If(index_1.Runtime.Token.Const('Promise', input), ([_0, input]) => If(index_1.Runtime.Token.Const('<', input), ([_1, input]) => If((0, exports.Type)(input, context), ([_2, input]) => If(index_1.Runtime.Token.Const('>', input), ([_3, input]) => [[_0, _1, _2, _3], input])))), ([_0, input]) => [S.PromiseMapping(_0, context), input]);
exports.Promise = Promise;
const ConstructorParameters = (input, context = {}) => If(If(index_1.Runtime.Token.Const('ConstructorParameters', input), ([_0, input]) => If(index_1.Runtime.Token.Const('<', input), ([_1, input]) => If((0, exports.Type)(input, context), ([_2, input]) => If(index_1.Runtime.Token.Const('>', input), ([_3, input]) => [[_0, _1, _2, _3], input])))), ([_0, input]) => [S.ConstructorParametersMapping(_0, context), input]);
exports.ConstructorParameters = ConstructorParameters;
const FunctionParameters = (input, context = {}) => If(If(index_1.Runtime.Token.Const('Parameters', input), ([_0, input]) => If(index_1.Runtime.Token.Const('<', input), ([_1, input]) => If((0, exports.Type)(input, context), ([_2, input]) => If(index_1.Runtime.Token.Const('>', input), ([_3, input]) => [[_0, _1, _2, _3], input])))), ([_0, input]) => [S.FunctionParametersMapping(_0, context), input]);
exports.FunctionParameters = FunctionParameters;
const InstanceType = (input, context = {}) => If(If(index_1.Runtime.Token.Const('InstanceType', input), ([_0, input]) => If(index_1.Runtime.Token.Const('<', input), ([_1, input]) => If((0, exports.Type)(input, context), ([_2, input]) => If(index_1.Runtime.Token.Const('>', input), ([_3, input]) => [[_0, _1, _2, _3], input])))), ([_0, input]) => [S.InstanceTypeMapping(_0, context), input]);
exports.InstanceType = InstanceType;
const ReturnType = (input, context = {}) => If(If(index_1.Runtime.Token.Const('ReturnType', input), ([_0, input]) => If(index_1.Runtime.Token.Const('<', input), ([_1, input]) => If((0, exports.Type)(input, context), ([_2, input]) => If(index_1.Runtime.Token.Const('>', input), ([_3, input]) => [[_0, _1, _2, _3], input])))), ([_0, input]) => [S.ReturnTypeMapping(_0, context), input]);
exports.ReturnType = ReturnType;
const Partial = (input, context = {}) => If(If(index_1.Runtime.Token.Const('Partial', input), ([_0, input]) => If(index_1.Runtime.Token.Const('<', input), ([_1, input]) => If((0, exports.Type)(input, context), ([_2, input]) => If(index_1.Runtime.Token.Const('>', input), ([_3, input]) => [[_0, _1, _2, _3], input])))), ([_0, input]) => [S.PartialMapping(_0, context), input]);
exports.Partial = Partial;
const Required = (input, context = {}) => If(If(index_1.Runtime.Token.Const('Required', input), ([_0, input]) => If(index_1.Runtime.Token.Const('<', input), ([_1, input]) => If((0, exports.Type)(input, context), ([_2, input]) => If(index_1.Runtime.Token.Const('>', input), ([_3, input]) => [[_0, _1, _2, _3], input])))), ([_0, input]) => [S.RequiredMapping(_0, context), input]);
exports.Required = Required;
const Pick = (input, context = {}) => If(If(index_1.Runtime.Token.Const('Pick', input), ([_0, input]) => If(index_1.Runtime.Token.Const('<', input), ([_1, input]) => If((0, exports.Type)(input, context), ([_2, input]) => If(index_1.Runtime.Token.Const(',', input), ([_3, input]) => If((0, exports.Type)(input, context), ([_4, input]) => If(index_1.Runtime.Token.Const('>', input), ([_5, input]) => [[_0, _1, _2, _3, _4, _5], input])))))), ([_0, input]) => [S.PickMapping(_0, context), input]);
exports.Pick = Pick;
const Omit = (input, context = {}) => If(If(index_1.Runtime.Token.Const('Omit', input), ([_0, input]) => If(index_1.Runtime.Token.Const('<', input), ([_1, input]) => If((0, exports.Type)(input, context), ([_2, input]) => If(index_1.Runtime.Token.Const(',', input), ([_3, input]) => If((0, exports.Type)(input, context), ([_4, input]) => If(index_1.Runtime.Token.Const('>', input), ([_5, input]) => [[_0, _1, _2, _3, _4, _5], input])))))), ([_0, input]) => [S.OmitMapping(_0, context), input]);
exports.Omit = Omit;
const Exclude = (input, context = {}) => If(If(index_1.Runtime.Token.Const('Exclude', input), ([_0, input]) => If(index_1.Runtime.Token.Const('<', input), ([_1, input]) => If((0, exports.Type)(input, context), ([_2, input]) => If(index_1.Runtime.Token.Const(',', input), ([_3, input]) => If((0, exports.Type)(input, context), ([_4, input]) => If(index_1.Runtime.Token.Const('>', input), ([_5, input]) => [[_0, _1, _2, _3, _4, _5], input])))))), ([_0, input]) => [S.ExcludeMapping(_0, context), input]);
exports.Exclude = Exclude;
const Extract = (input, context = {}) => If(If(index_1.Runtime.Token.Const('Extract', input), ([_0, input]) => If(index_1.Runtime.Token.Const('<', input), ([_1, input]) => If((0, exports.Type)(input, context), ([_2, input]) => If(index_1.Runtime.Token.Const(',', input), ([_3, input]) => If((0, exports.Type)(input, context), ([_4, input]) => If(index_1.Runtime.Token.Const('>', input), ([_5, input]) => [[_0, _1, _2, _3, _4, _5], input])))))), ([_0, input]) => [S.ExtractMapping(_0, context), input]);
exports.Extract = Extract;
const Uppercase = (input, context = {}) => If(If(index_1.Runtime.Token.Const('Uppercase', input), ([_0, input]) => If(index_1.Runtime.Token.Const('<', input), ([_1, input]) => If((0, exports.Type)(input, context), ([_2, input]) => If(index_1.Runtime.Token.Const('>', input), ([_3, input]) => [[_0, _1, _2, _3], input])))), ([_0, input]) => [S.UppercaseMapping(_0, context), input]);
exports.Uppercase = Uppercase;
const Lowercase = (input, context = {}) => If(If(index_1.Runtime.Token.Const('Lowercase', input), ([_0, input]) => If(index_1.Runtime.Token.Const('<', input), ([_1, input]) => If((0, exports.Type)(input, context), ([_2, input]) => If(index_1.Runtime.Token.Const('>', input), ([_3, input]) => [[_0, _1, _2, _3], input])))), ([_0, input]) => [S.LowercaseMapping(_0, context), input]);
exports.Lowercase = Lowercase;
const Capitalize = (input, context = {}) => If(If(index_1.Runtime.Token.Const('Capitalize', input), ([_0, input]) => If(index_1.Runtime.Token.Const('<', input), ([_1, input]) => If((0, exports.Type)(input, context), ([_2, input]) => If(index_1.Runtime.Token.Const('>', input), ([_3, input]) => [[_0, _1, _2, _3], input])))), ([_0, input]) => [S.CapitalizeMapping(_0, context), input]);
exports.Capitalize = Capitalize;
const Uncapitalize = (input, context = {}) => If(If(index_1.Runtime.Token.Const('Uncapitalize', input), ([_0, input]) => If(index_1.Runtime.Token.Const('<', input), ([_1, input]) => If((0, exports.Type)(input, context), ([_2, input]) => If(index_1.Runtime.Token.Const('>', input), ([_3, input]) => [[_0, _1, _2, _3], input])))), ([_0, input]) => [S.UncapitalizeMapping(_0, context), input]);
exports.Uncapitalize = Uncapitalize;
const Date = (input, context = {}) => If(index_1.Runtime.Token.Const('Date', input), ([_0, input]) => [S.DateMapping(_0, context), input]);
exports.Date = Date;
const Uint8Array = (input, context = {}) => If(index_1.Runtime.Token.Const('Uint8Array', input), ([_0, input]) => [S.Uint8ArrayMapping(_0, context), input]);
exports.Uint8Array = Uint8Array;
const Reference = (input, context = {}) => If(index_1.Runtime.Token.Ident(input), ([_0, input]) => [S.ReferenceMapping(_0, context), input]);
exports.Reference = Reference;
@@ -0,0 +1,12 @@
import * as t from '../type/index';
import { TType } from './parser';
/** `[Experimental]` Parses type expressions into TypeBox types but does not infer */
export declare function NoInfer<Context extends Record<PropertyKey, t.TSchema>, Input extends string>(context: Context, input: Input, options?: t.SchemaOptions): t.TSchema;
/** `[Experimental]` Parses type expressions into TypeBox types but does not infer */
export declare function NoInfer<Input extends string>(input: Input, options?: t.SchemaOptions): t.TSchema;
/** `[Experimental]` Parses type expressions into TypeBox types */
export type TSyntax<Context extends Record<PropertyKey, t.TSchema>, Code extends string> = (TType<Code, Context> extends [infer Type extends t.TSchema, string] ? Type : t.TNever);
/** `[Experimental]` Parses type expressions into TypeBox types */
export declare function Syntax<Context extends Record<PropertyKey, t.TSchema>, Input extends string>(context: Context, input: Input, options?: t.SchemaOptions): TSyntax<Context, Input>;
/** `[Experimental]` Parses type expressions into TypeBox types */
export declare function Syntax<Input extends string>(annotation: Input, options?: t.SchemaOptions): TSyntax<{}, Input>;
@@ -0,0 +1,54 @@
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
var ownKeys = function(o) {
ownKeys = Object.getOwnPropertyNames || function (o) {
var ar = [];
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
return ar;
};
return ownKeys(o);
};
return function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
__setModuleDefault(result, mod);
return result;
};
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.NoInfer = NoInfer;
exports.Syntax = Syntax;
const t = __importStar(require("../type/index"));
const parser_1 = require("./parser");
/** `[Experimental]` Parses type expressions into TypeBox types but does not infer */
// prettier-ignore
function NoInfer(...args) {
const withContext = typeof args[0] === 'string' ? false : true;
const [context, code, options] = withContext ? [args[0], args[1], args[2] || {}] : [{}, args[0], args[1] || {}];
const result = (0, parser_1.Type)(code, context)[0];
return t.KindGuard.IsSchema(result)
? t.CloneType(result, options)
: t.Never(options);
}
/** `[Experimental]` Parses type expressions into TypeBox types */
function Syntax(...args) {
return NoInfer.apply(null, args);
}
@@ -0,0 +1,2 @@
export * from './policy';
export * from './system';
+19
View File
@@ -0,0 +1,19 @@
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __exportStar = (this && this.__exportStar) || function(m, exports) {
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
Object.defineProperty(exports, "__esModule", { value: true });
__exportStar(require("./policy"), exports);
__exportStar(require("./system"), exports);
@@ -0,0 +1,29 @@
export declare namespace TypeSystemPolicy {
/**
* Configures the instantiation behavior of TypeBox types. The `default` option assigns raw JavaScript
* references for embedded types, which may cause side effects if type properties are explicitly updated
* outside the TypeBox type builder. The `clone` option creates copies of any shared types upon creation,
* preventing unintended side effects. The `freeze` option applies `Object.freeze()` to the type, making
* it fully readonly and immutable. Implementations should use `default` whenever possible, as it is the
* fastest way to instantiate types. The default setting is `default`.
*/
let InstanceMode: 'default' | 'clone' | 'freeze';
/** Sets whether TypeBox should assert optional properties using the TypeScript `exactOptionalPropertyTypes` assertion policy. The default is `false` */
let ExactOptionalPropertyTypes: boolean;
/** Sets whether arrays should be treated as a kind of objects. The default is `false` */
let AllowArrayObject: boolean;
/** Sets whether `NaN` or `Infinity` should be treated as valid numeric values. The default is `false` */
let AllowNaN: boolean;
/** Sets whether `null` should validate for void types. The default is `false` */
let AllowNullVoid: boolean;
/** Checks this value using the ExactOptionalPropertyTypes policy */
function IsExactOptionalProperty(value: Record<keyof any, unknown>, key: string): boolean;
/** Checks this value using the AllowArrayObjects policy */
function IsObjectLike(value: unknown): value is Record<keyof any, unknown>;
/** Checks this value as a record using the AllowArrayObjects policy */
function IsRecordLike(value: unknown): value is Record<keyof any, unknown>;
/** Checks this value using the AllowNaN policy */
function IsNumberLike(value: unknown): value is number;
/** Checks this value using the AllowVoidNull policy */
function IsVoidLike(value: unknown): value is void;
}
@@ -0,0 +1,58 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.TypeSystemPolicy = void 0;
const index_1 = require("../value/guard/index");
var TypeSystemPolicy;
(function (TypeSystemPolicy) {
// ------------------------------------------------------------------
// TypeSystemPolicy: Instancing
// ------------------------------------------------------------------
/**
* Configures the instantiation behavior of TypeBox types. The `default` option assigns raw JavaScript
* references for embedded types, which may cause side effects if type properties are explicitly updated
* outside the TypeBox type builder. The `clone` option creates copies of any shared types upon creation,
* preventing unintended side effects. The `freeze` option applies `Object.freeze()` to the type, making
* it fully readonly and immutable. Implementations should use `default` whenever possible, as it is the
* fastest way to instantiate types. The default setting is `default`.
*/
TypeSystemPolicy.InstanceMode = 'default';
// ------------------------------------------------------------------
// TypeSystemPolicy: Checking
// ------------------------------------------------------------------
/** Sets whether TypeBox should assert optional properties using the TypeScript `exactOptionalPropertyTypes` assertion policy. The default is `false` */
TypeSystemPolicy.ExactOptionalPropertyTypes = false;
/** Sets whether arrays should be treated as a kind of objects. The default is `false` */
TypeSystemPolicy.AllowArrayObject = false;
/** Sets whether `NaN` or `Infinity` should be treated as valid numeric values. The default is `false` */
TypeSystemPolicy.AllowNaN = false;
/** Sets whether `null` should validate for void types. The default is `false` */
TypeSystemPolicy.AllowNullVoid = false;
/** Checks this value using the ExactOptionalPropertyTypes policy */
function IsExactOptionalProperty(value, key) {
return TypeSystemPolicy.ExactOptionalPropertyTypes ? key in value : value[key] !== undefined;
}
TypeSystemPolicy.IsExactOptionalProperty = IsExactOptionalProperty;
/** Checks this value using the AllowArrayObjects policy */
function IsObjectLike(value) {
const isObject = (0, index_1.IsObject)(value);
return TypeSystemPolicy.AllowArrayObject ? isObject : isObject && !(0, index_1.IsArray)(value);
}
TypeSystemPolicy.IsObjectLike = IsObjectLike;
/** Checks this value as a record using the AllowArrayObjects policy */
function IsRecordLike(value) {
return IsObjectLike(value) && !(value instanceof Date) && !(value instanceof Uint8Array);
}
TypeSystemPolicy.IsRecordLike = IsRecordLike;
/** Checks this value using the AllowNaN policy */
function IsNumberLike(value) {
return TypeSystemPolicy.AllowNaN ? (0, index_1.IsNumber)(value) : Number.isFinite(value);
}
TypeSystemPolicy.IsNumberLike = IsNumberLike;
/** Checks this value using the AllowVoidNull policy */
function IsVoidLike(value) {
const isUndefined = (0, index_1.IsUndefined)(value);
return TypeSystemPolicy.AllowNullVoid ? isUndefined || value === null : isUndefined;
}
TypeSystemPolicy.IsVoidLike = IsVoidLike;
})(TypeSystemPolicy || (exports.TypeSystemPolicy = TypeSystemPolicy = {}));
@@ -0,0 +1,16 @@
import { type TUnsafe } from '../type/unsafe/index';
import { TypeBoxError } from '../type/error/index';
export declare class TypeSystemDuplicateTypeKind extends TypeBoxError {
constructor(kind: string);
}
export declare class TypeSystemDuplicateFormat extends TypeBoxError {
constructor(kind: string);
}
export type TypeFactoryFunction<Type, Options = Record<PropertyKey, unknown>> = (options?: Partial<Options>) => TUnsafe<Type>;
/** Creates user defined types and formats and provides overrides for value checking behaviours */
export declare namespace TypeSystem {
/** Creates a new type */
function Type<Type, Options = Record<PropertyKey, unknown>>(kind: string, check: (options: Options, value: unknown) => boolean): TypeFactoryFunction<Type, Options>;
/** Creates a new string format */
function Format<F extends string>(format: F, check: (value: string) => boolean): F;
}
@@ -0,0 +1,43 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.TypeSystem = exports.TypeSystemDuplicateFormat = exports.TypeSystemDuplicateTypeKind = void 0;
const index_1 = require("../type/registry/index");
const index_2 = require("../type/unsafe/index");
const index_3 = require("../type/symbols/index");
const index_4 = require("../type/error/index");
// ------------------------------------------------------------------
// Errors
// ------------------------------------------------------------------
class TypeSystemDuplicateTypeKind extends index_4.TypeBoxError {
constructor(kind) {
super(`Duplicate type kind '${kind}' detected`);
}
}
exports.TypeSystemDuplicateTypeKind = TypeSystemDuplicateTypeKind;
class TypeSystemDuplicateFormat extends index_4.TypeBoxError {
constructor(kind) {
super(`Duplicate string format '${kind}' detected`);
}
}
exports.TypeSystemDuplicateFormat = TypeSystemDuplicateFormat;
/** Creates user defined types and formats and provides overrides for value checking behaviours */
var TypeSystem;
(function (TypeSystem) {
/** Creates a new type */
function Type(kind, check) {
if (index_1.TypeRegistry.Has(kind))
throw new TypeSystemDuplicateTypeKind(kind);
index_1.TypeRegistry.Set(kind, check);
return (options = {}) => (0, index_2.Unsafe)({ ...options, [index_3.Kind]: kind });
}
TypeSystem.Type = Type;
/** Creates a new string format */
function Format(format, check) {
if (index_1.FormatRegistry.Has(format))
throw new TypeSystemDuplicateFormat(format);
index_1.FormatRegistry.Set(format, check);
return format;
}
TypeSystem.Format = Format;
})(TypeSystem || (exports.TypeSystem = TypeSystem = {}));
@@ -0,0 +1,8 @@
import type { TSchema, SchemaOptions } from '../schema/index';
import { Kind } from '../symbols/index';
export interface TAny extends TSchema {
[Kind]: 'Any';
static: any;
}
/** `[Json]` Creates an Any type */
export declare function Any(options?: SchemaOptions): TAny;
+10
View File
@@ -0,0 +1,10 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Any = Any;
const index_1 = require("../create/index");
const index_2 = require("../symbols/index");
/** `[Json]` Creates an Any type */
function Any(options) {
return (0, index_1.CreateType)({ [index_2.Kind]: 'Any' }, options);
}

Some files were not shown because too many files have changed in this diff Show More