This commit is contained in:
2026-11-02 12:42:04 +00:00
commit e4e28174bf
5498 changed files with 1735888 additions and 0 deletions

188
node_modules/esrap/src/context.js generated vendored Normal file
View File

@@ -0,0 +1,188 @@
/** @import { BaseNode, Command, Visitors } from './types.js' */
/** @import { Tokens } from './tokens.js' */
export const margin = 0;
export const newline = 1;
export const indent = 2;
export const dedent = 3;
export const space = 4;
export class Context {
#visitors;
#commands;
#tokens;
#has_newline = false;
multiline = false;
/**
*
* @param {Visitors} visitors
* @param {Command[]} commands
* @param {Tokens | null} tokens
*/
constructor(visitors, commands = [], tokens = null) {
this.#visitors = visitors;
this.#commands = commands;
this.#tokens = tokens;
}
indent() {
this.#commands.push(indent);
}
dedent() {
this.#commands.push(dedent);
}
margin() {
this.#commands.push(margin);
}
newline() {
this.#has_newline = true;
this.#commands.push(newline);
}
space() {
this.#commands.push(space);
}
/**
* @param {Context} context
*/
append(context) {
this.#commands.push(context.#commands);
if (this.#has_newline || context.multiline) {
this.multiline = true;
}
}
/**
* Write `content`. If `node` is provided, `content` is mapped to its location. Otherwise, if `tokens`
* were passed to `print` and `content` (ignoring surrounding whitespace) is the next token
* in the source, it is mapped to that token's location.
* @param {string} content
* @param {BaseNode} [node]
*/
write(content, node) {
const value = this.#tokens && content.trim();
const token = value
? this.#tokens?.consume(value, node?.loc?.start, node?.loc?.end)
: undefined;
if (node?.loc) {
this.location(node.loc.start.line, node.loc.start.column);
this.#commands.push(content);
this.location(node.loc.end.line, node.loc.end.column);
} else if (token && value) {
const start = content.indexOf(value);
const end = start + value.length;
if (start > 0) this.#commands.push(content.slice(0, start));
this.location(token.start.line, token.start.column);
this.#commands.push(value);
this.location(token.end.line, token.end.column);
if (end < content.length) this.#commands.push(content.slice(end));
} else {
this.#commands.push(content);
}
if (this.#has_newline) {
this.multiline = true;
}
}
/**
*
* @param {number} line
* @param {number} column
*/
location(line, column) {
this.#commands.push({ type: 'Location', line, column });
}
/**
* @param {{ type: string }} node
*/
visit(node) {
const visitor = this.#visitors[node.type];
if (!visitor) {
let message = `Not implemented: ${node.type}`;
if (node.type.includes('TS')) {
message += ` (consider using 'esrap/languages/ts')`;
}
if (node.type.includes('JSX')) {
message += ` (consider using 'esrap/languages/tsx')`;
}
throw new Error(message);
}
const tokens = this.#tokens;
const previous = tokens?.enter(node);
if (this.#visitors._) {
// @ts-ignore
this.#visitors._(node, this, (node) => visitor(node, this));
} else {
// @ts-ignore
visitor(node, this);
}
if (previous) tokens?.exit(node, previous);
}
empty() {
return !this.#commands.some(has_content);
}
measure() {
return measure(this.#commands);
}
new() {
return new Context(this.#visitors, [], this.#tokens);
}
}
/**
*
* @param {Command[]} commands
* @param {number} [from]
* @param {number} [to]
*/
function measure(commands, from = 0, to = commands.length) {
let total = 0;
for (let i = from; i < to; i += 1) {
const command = commands[i];
if (typeof command === 'string') {
total += command.length;
} else if (Array.isArray(command)) {
total += measure(command);
}
}
return total;
}
/**
* @param {Command} command
*/
function has_content(command) {
if (Array.isArray(command)) {
return command.some(has_content);
}
if (typeof command === 'string') {
return command.length > 0;
}
return false;
}

200
node_modules/esrap/src/index.js generated vendored Normal file
View File

@@ -0,0 +1,200 @@
/** @import { BaseNode, Command, Location, Visitors, PrintOptions } from './types.js' */
import { encode } from '@jridgewell/sourcemap-codec';
import { Context, dedent, indent, margin, newline, space } from './context.js';
import { Tokens } from './tokens.js';
/** @type {(str: string) => string} str */
let btoa = () => {
throw new Error('Unsupported environment: `window.btoa` or `Buffer` should be supported.');
};
if (typeof window !== 'undefined' && typeof window.btoa === 'function') {
btoa = (str) => window.btoa(unescape(encodeURIComponent(str)));
} else if (typeof Buffer === 'function') {
btoa = (str) => Buffer.from(str, 'utf-8').toString('base64');
}
class SourceMap {
version = 3;
/** @type {string[]} */
names = [];
/**
* @param {[number, number, number, number][][]} mappings
* @param {PrintOptions} opts
*/
constructor(mappings, opts) {
this.sources = [opts.sourceMapSource || null];
this.sourcesContent = [opts.sourceMapContent || null];
this.mappings = opts.sourceMapEncodeMappings === false ? mappings : encode(mappings);
}
/**
* Returns a JSON representation suitable for saving as a `*.map` file
*/
toString() {
return JSON.stringify(this);
}
/**
* Returns a base64-encoded JSON representation suitable for inlining at the bottom of a file with `//# sourceMappingURL={...}`
*/
toUrl() {
return 'data:application/json;charset=utf-8;base64,' + btoa(this.toString());
}
}
/**
* @template {BaseNode} [T=BaseNode]
* @param {T} node
* @param {Visitors<T>} visitors
* @param {PrintOptions} opts
* @returns {{ code: string, map: any }} // TODO
*/
export function print(node, visitors, opts = {}) {
/** @type {Command[]} */
const commands = [];
const tokens = opts.tokens ? new Tokens(opts.tokens) : null;
// @ts-ignore some nonsense I don't understand
const context = new Context(visitors, commands, tokens);
context.visit(node);
/** @typedef {[generatedColumn: number, sourceIndex: number, originalLine: number, originalColumn: number]} Segment */
let code = '';
let current_column = 0;
/** @type {Segment[][]} */
let mappings = [];
/** @type {Segment[]} */
let current_line = [];
/** @param {string} str */
function append(str) {
code += str;
for (let i = 0; i < str.length; i += 1) {
if (str[i] === '\n') {
mappings.push(current_line);
current_line = [];
current_column = 0;
} else {
current_column += 1;
}
}
}
let current_newline = '\n';
const indent_str = opts.indent ?? '\t';
let needs_newline = false;
let needs_margin = false;
let needs_space = false;
/** @type {Location[]} */
const pending_locations = [];
/** @param {Location} location */
function add_location(location) {
const prev = current_line[current_line.length - 1];
/** @type {Segment} */
const segment = [
current_column,
0, // source index is always zero
location.line - 1,
location.column
];
if (!prev || prev[0] !== segment[0] || prev[2] !== segment[2] || prev[3] !== segment[3]) {
current_line.push(segment);
}
}
function flush_locations() {
for (const location of pending_locations) {
add_location(location);
}
pending_locations.length = 0;
}
/** @param {Command} command */
function run(command) {
if (Array.isArray(command)) {
for (let i = 0; i < command.length; i += 1) {
run(command[i]);
}
return;
}
if (typeof command === 'number') {
if (command === newline) {
needs_newline = true;
} else if (command === margin) {
needs_margin = true;
} else if (command === space) {
needs_space = true;
} else if (command === indent) {
current_newline += indent_str;
} else if (command === dedent) {
// `slice(0, -0)` would return an empty string, dropping the newline
current_newline = current_newline.slice(0, current_newline.length - indent_str.length);
}
return;
}
if (typeof command === 'string') {
if (needs_newline) {
append(needs_margin ? '\n' + current_newline : current_newline);
} else if (needs_space) {
append(' ');
}
needs_margin = needs_newline = needs_space = false;
flush_locations();
append(command);
return;
}
if (command.type === 'Location') {
// Locations must not flush whitespace, but should follow it if more text is written.
if (needs_newline || needs_space) {
pending_locations.push(command);
} else {
add_location(command);
}
}
}
for (let i = 0; i < commands.length; i += 1) {
run(commands[i]);
}
// Preserve trailing mappings without emitting trailing whitespace.
flush_locations();
mappings.push(current_line);
/** @type {SourceMap} */
let map;
return {
code,
// create sourcemap lazily in case we don't need it
get map() {
return (map ??= new SourceMap(mappings, opts));
}
};
}
// it sucks that we have to export the class rather than just
// re-exporting it via public.d.ts, but otherwise TypeScript
// gets confused about private fields because it is really dumb!
export { Context };

2975
node_modules/esrap/src/languages/ts/index.js generated vendored Normal file

File diff suppressed because it is too large Load Diff

4
node_modules/esrap/src/languages/ts/public.ts generated vendored Normal file
View File

@@ -0,0 +1,4 @@
export type { BaseNode as Node } from '../../types.js';
export type { BaseComment, Comment } from '../types.js';
export { default, EXPRESSIONS_PRECEDENCE } from './index.js';

163
node_modules/esrap/src/languages/tsx/index.js generated vendored Normal file
View File

@@ -0,0 +1,163 @@
/** @import { TSESTree } from '@typescript-eslint/types' */
/** @import { BaseNode, Visitors } from '../../types.js' */
/** @import { TSOptions } from '../types.js' */
import ts from '../ts/index.js';
/**
* @param {TSOptions} [options]
* @returns {Visitors<BaseNode>}
*/
export default (options) => {
/** @type {Visitors<TSESTree.Node>} */
const visitors = {
.../** @type {Visitors<TSESTree.Node>} */ (ts(options)),
TSTypeParameterDeclaration(node, context) {
context.write('<');
for (let i = 0; i < node.params.length; i++) {
if (i > 0) context.write(', ');
context.visit(node.params[i]);
}
// Keep single-parameter declarations unambiguous with JSX.
if (node.params.length === 1) context.write(',');
context.write('>');
},
JSXElement(node, context) {
context.visit(node.openingElement);
if (node.children.length > 0) {
context.indent();
}
for (const child of node.children) {
context.visit(child);
}
if (node.children.length > 0) {
context.dedent();
}
if (node.closingElement) {
context.visit(node.closingElement);
}
},
JSXOpeningElement(node, context) {
context.write('<');
context.visit(node.name);
// explicit type arguments (`<Comp<string> ... />`)
if (node.typeArguments) {
context.visit(node.typeArguments);
}
for (const attribute of node.attributes) {
context.write(' ');
context.visit(attribute);
}
if (node.selfClosing) {
context.write(' /');
}
context.write('>');
},
JSXClosingElement(node, context) {
context.write('</');
context.visit(node.name);
context.write('>');
},
JSXNamespacedName(node, context) {
context.visit(node.namespace);
context.write(':');
context.visit(node.name);
},
JSXIdentifier(node, context) {
context.write(node.name, node);
},
JSXMemberExpression(node, context) {
context.visit(node.object);
context.write('.');
context.visit(node.property);
},
JSXText(node, context) {
// `value` is decoded — re-emitting it would turn `&lt;`, `&gt;`, `&#123;`
// and `&#125;` back into characters that can't appear in JSX text
context.write(node.raw ?? node.value, node);
},
JSXAttribute(node, context) {
context.visit(node.name);
if (node.value) {
context.write('=');
context.visit(node.value);
}
},
JSXEmptyExpression(node, context) {},
JSXFragment(node, context) {
context.visit(node.openingFragment);
if (node.children.length > 0) {
context.indent();
}
for (const child of node.children) {
context.visit(child);
}
if (node.children.length > 0) {
context.dedent();
}
context.visit(node.closingFragment);
},
JSXOpeningFragment(node, context) {
context.write('<>');
},
JSXClosingFragment(node, context) {
context.write('</>');
},
JSXExpressionContainer(node, context) {
context.write('{');
context.visit(node.expression);
context.write('}');
},
JSXSpreadChild(node, context) {
context.write('{...');
context.visit(node.expression);
context.write('}');
},
JSXSpreadAttribute(node, context) {
context.write('{...');
context.visit(node.argument);
context.write('}');
}
};
// Accept compatible ASTs from other parsers at the public boundary.
return /** @type {Visitors<BaseNode>} */ (visitors);
};

4
node_modules/esrap/src/languages/tsx/public.ts generated vendored Normal file
View File

@@ -0,0 +1,4 @@
export type { BaseNode as Node } from '../../types.js';
export type { BaseComment, Comment } from '../types.js';
export { default } from './index.js';

29
node_modules/esrap/src/languages/types.ts generated vendored Normal file
View File

@@ -0,0 +1,29 @@
import type { BaseNode } from '../types.js';
export type TSOptions = {
quotes?: 'double' | 'single';
comments?: Comment[];
getLeadingComments?: (node: BaseNode) => BaseComment[] | undefined;
getTrailingComments?: (node: BaseNode) => BaseComment[] | undefined;
};
interface Position {
line: number;
column: number;
}
// this exists in TSESTree but because of the inanity around enums
// it's easier to do this ourselves
export interface BaseComment {
type: 'Line' | 'Block';
value: string;
start?: number;
end?: number;
}
export interface Comment extends BaseComment {
loc: {
start: Position;
end: Position;
};
}

2
node_modules/esrap/src/public.ts generated vendored Normal file
View File

@@ -0,0 +1,2 @@
export type { PrintOptions, Token, Visitors } from './types.js';
export * from './index.js';

235
node_modules/esrap/src/tokens.js generated vendored Normal file
View File

@@ -0,0 +1,235 @@
/** @import { BaseNode, Token } from './types.js' */
/**
* @typedef {{ line: number, column: number }} Position
* @typedef {{ value: string, start: Position, end: Position, pair: number }} Entry
* @typedef {{ lo: number, hi: number, openers: Opener[] }} Frame
* @typedef {{ value: string, pair: number }} Opener
*/
/** Acorn/Babel token types that don't correspond to anything written verbatim */
const IGNORED = new Set([
'string',
'num',
'bigint',
'decimal',
'regexp',
'template',
'invalidTemplate',
'privateId',
'jsxText',
'eof'
]);
/** ESLint-style token types (espree, typescript-eslint) whose `value` is written verbatim */
const VERBATIM = new Set([
'Punctuator',
'Keyword',
'Identifier',
'Boolean',
'Null',
'JSXIdentifier'
]);
/** @type {Record<string, string>} */
const OPENERS = { ')': '(', ']': '[', '}': '{' };
/**
* The text a parser token stands for, or `null` if it's not something a printer writes as-is.
* Acorn and Babel describe tokens with a `type` object whose `label` is the punctuator (or
* `name` for identifiers and contextual keywords), with operators and words in `value`.
* ESLint-style tokens have a string `type` and the source text in `value`.
* @param {Token} token
* @returns {string | null}
*/
function text(token) {
const { type, value } = token;
if (typeof type === 'object' && type !== null) {
const label = type.label;
if (label === undefined || IGNORED.has(label)) return null;
if (label === 'jsxTagStart') return '<';
if (label === 'jsxTagEnd') return '>';
return typeof value === 'string' ? value : label;
}
if (typeof type === 'string' && VERBATIM.has(type) && typeof value === 'string') {
return value;
}
return null;
}
/**
* @param {Position} a
* @param {Position} b
*/
function compare(a, b) {
return a.line - b.line || a.column - b.column;
}
/**
* Tracks which of the parser's tokens have been written, so that `context.write`
* can map a token to its source location. Each `context.visit` narrows the search to
* the tokens inside the visited node; each written token advances the cursor past it.
*/
export class Tokens {
/** @type {Entry[]} */
#entries = [];
/** @type {Frame} */
#frame = { lo: 0, hi: 0, openers: [] };
/** @param {readonly Token[]} tokens */
constructor(tokens) {
/** @type {Entry[]} */
const entries = [];
for (const token of tokens) {
if (!token.loc) continue;
const value = text(token);
if (value === null) continue;
entries.push({ value, start: token.loc.start, end: token.loc.end, pair: -1 });
}
// parsers that backtrack (e.g. acorn-typescript) can emit tokens more than once, or out
// of order. Keep the last token emitted at each position, and drop any that overlap
entries.sort((a, b) => compare(a.start, b.start));
for (const entry of entries) {
const previous = this.#entries[this.#entries.length - 1];
if (previous && compare(previous.start, entry.start) === 0) {
this.#entries[this.#entries.length - 1] = entry;
} else if (!previous || compare(previous.end, entry.start) <= 0) {
this.#entries.push(entry);
}
}
// pair up brackets, so that a closing bracket can be found from its opening bracket
// regardless of any redundant parentheses or trailing commas in between
/** @type {number[]} */
const stack = [];
for (let i = 0; i < this.#entries.length; i += 1) {
const { value } = this.#entries[i];
if (value === '(' || value === '[' || value === '{' || value === '${') {
stack.push(i);
} else if (value in OPENERS) {
const opener = stack.pop();
if (opener === undefined) continue;
const expected = this.#entries[opener].value;
if (expected === OPENERS[value] || (value === '}' && expected === '${')) {
this.#entries[opener].pair = i;
this.#entries[i].pair = opener;
}
}
}
}
/**
* Bound the search to the tokens within `node`. If `node` has no location, disable
* searching until a descendant with a location is visited
* @param {BaseNode} node
* @returns {Frame} the previous state, to be passed to `exit`
*/
enter(node) {
const previous = this.#frame;
if (node.loc) {
let lo = this.#search(node.loc.start);
const hi = this.#search(node.loc.end);
// if the parent has already written tokens inside this node (e.g. the decorators
// of an exported class, which are printed before `export`), skip them
if (previous.lo > lo && previous.lo < hi) lo = previous.lo;
this.#frame = { lo, hi, openers: [] };
} else {
this.#frame = { lo: 0, hi: 0, openers: [] };
}
return previous;
}
/**
* Restore the state from before `enter`, advancing the cursor past `node`
* @param {BaseNode} node
* @param {Frame} previous
*/
exit(node, previous) {
this.#frame = previous;
if (node.loc) this.skip(node.loc.end);
}
/**
* Advance the cursor past `position`
* @param {Position} position
*/
skip(position) {
this.#frame.lo = Math.max(this.#frame.lo, this.#search(position));
}
/**
* If `value` is the next unwritten token, consume it and return it. A closing
* bracket matches the partner of the opening bracket that was last written
* @param {string} value
* @param {Position} [from] only match tokens starting at or after this position
* @param {Position} [to] only match tokens ending at or before this position
* @returns {Entry | undefined}
*/
consume(value, from, to) {
const frame = this.#frame;
const is_opener = value === '(' || value === '[' || value === '{' || value === '${';
if (value in OPENERS) {
const opener = frame.openers[frame.openers.length - 1];
if (opener && (opener.value === OPENERS[value] || (value === '}' && opener.value === '${'))) {
frame.openers.pop();
const i = opener.pair;
if (i === -1 || i >= frame.hi) return;
frame.lo = Math.max(frame.lo, i + 1);
return this.#entries[i];
}
}
const entry = frame.lo < frame.hi ? this.#entries[frame.lo] : undefined;
const match =
entry !== undefined &&
entry.value === value &&
(!from || compare(entry.start, from) >= 0) &&
(!to || compare(entry.end, to) <= 0);
if (is_opener) {
frame.openers.push({ value, pair: match ? entry.pair : -1 });
}
if (match) {
frame.lo += 1;
return entry;
}
}
/**
* The index of the first token starting at or after `position`
* @param {Position} position
*/
#search(position) {
let lo = 0;
let hi = this.#entries.length;
while (lo < hi) {
const mid = (lo + hi) >> 1;
if (compare(this.#entries[mid].start, position) < 0) lo = mid + 1;
else hi = mid;
}
return lo;
}
}

67
node_modules/esrap/src/types.ts generated vendored Normal file
View File

@@ -0,0 +1,67 @@
import type { Context } from 'esrap';
export type BaseNode = {
type: string;
loc?: null | {
start: { line: number; column: number };
end: { line: number; column: number };
};
};
type NodeOf<T extends string, X> = X extends { type: T } ? X : never;
type SpecialisedVisitors<T extends BaseNode> = {
[K in T['type']]?: Visitor<NodeOf<K, T>>;
};
export type Visitor<T> = (node: T, context: Context) => void;
export type Visitors<T extends BaseNode = BaseNode> = T['type'] extends '_'
? never
: SpecialisedVisitors<T> & { _?: (node: T, context: Context, visit: (node: T) => void) => void };
export { Context };
type TSExpressionWithTypeArguments = {
type: 'TSExpressionWithTypeArguments';
expression: any;
};
export interface Location {
type: 'Location';
line: number;
column: number;
}
export interface IndentChange {
type: 'IndentChange';
offset: number;
}
export type Command = string | number | Location | Command[];
export interface PrintOptions {
sourceMapSource?: string;
sourceMapContent?: string;
sourceMapEncodeMappings?: boolean; // default true
indent?: string; // default tab
/**
* The parser's tokens — e.g. Acorn's `onToken` array, or `ast.tokens` from
* typescript-eslint or espree. When provided, punctuation and keywords
* written by visitors are mapped to their location in the source
*/
tokens?: readonly Token[];
}
/**
* A token produced by a parser. Acorn and Babel tokens have a `type` object
* with a `label`; ESLint-style tokens have a string `type` and a `value`
*/
export interface Token {
type?: string | { label?: string };
value?: unknown;
loc?: null | {
start: { line: number; column: number };
end: { line: number; column: number };
};
}