WIP: bootstrap and partial real Solana watcher implementation

This commit is contained in:
2026-08-16 09:17:45 +00:00
commit dc23412c3f
7232 changed files with 1687637 additions and 0 deletions

View File

@@ -0,0 +1 @@
export { _ as default } from "../esm/_tagged_template_literal_loose.js";

View File

@@ -0,0 +1 @@
{"version":3,"file":"newLineKind.enum.js","sourceRoot":"","sources":["../../src/enums/newLineKind.enum.ts"],"names":[],"mappings":"AAAA,sGAAsG;AAEtG,MAAM,CAAN,IAAY,WAIX;AAJD,WAAY,WAAW;IACnB,6CAAQ,CAAA;IACR,6CAAQ,CAAA;IACR,yCAAM,CAAA;AACV,CAAC,EAJW,WAAW,KAAX,WAAW,QAItB"}

View File

@@ -0,0 +1,8 @@
import type { SourceFile } from 'typescript';
import type { ASTMaps } from './convert';
import type { ParseSettings } from './parseSettings';
import type { TSESTree } from './ts-estree';
export declare function astConverter(ast: SourceFile, parseSettings: ParseSettings, shouldPreserveNodeMaps: boolean): {
astMaps: ASTMaps;
estree: TSESTree.Program;
};

View File

@@ -0,0 +1,234 @@
// Type definitions for pino-pretty 7.0
// Project: https://github.com/pinojs/pino-pretty#readme
// Definitions by: Adam Vigneaux <https://github.com/AdamVig>
// tearwyx <https://github.com/tearwyx>
// Minimum TypeScript Version: 3.0
/// <reference types="node" />
import { Transform } from 'node:stream';
import { OnUnknown } from 'pino-abstract-transport';
// @ts-ignore fall back to any if pino is not available, i.e. when running pino tests
import { DestinationStream, Level } from 'pino';
import * as Colorette from "colorette";
type LogDescriptor = Record<string, unknown>;
declare function PinoPretty(options?: PinoPretty.PrettyOptions): PinoPretty.PrettyStream;
declare namespace PinoPretty {
function colorizerFactory(
useColors?: boolean,
customColors?: [number, string][],
useOnlyCustomProps?: boolean,
): {
(
level?: number | string,
opts?: {
customLevels?: { [level: number]: string };
customLevelNames?: { [name: string]: number };
},
): string,
message: (input: string | number) => string,
greyMessage: (input: string | number) => string,
}
function prettyFactory(options: PrettyOptions): (inputData: any) => string
interface PrettyOptions {
/**
* Hide objects from output (but not error object).
* @default false
*/
hideObject?: boolean;
/**
* Translate the epoch time value into a human readable date and time string. This flag also can set the format
* string to apply when translating the date to human readable format. For a list of available pattern letters
* see the {@link https://www.npmjs.com/package/dateformat|dateformat documentation}.
* - The default format is `yyyy-mm-dd HH:MM:ss.l o` in UTC.
* - Requires a `SYS:` prefix to translate time to the local system's timezone. Use the shortcut `SYS:standard`
* to translate time to `yyyy-mm-dd HH:MM:ss.l o` in system timezone.
* @default false
*/
translateTime?: boolean | string;
/**
* If set to true, it will print the name of the log level as the first field in the log line.
* @default false
*/
levelFirst?: boolean;
/**
* Define the key that contains the level of the log.
* @default "level"
*/
levelKey?: string;
/**
* Output the log level using the specified label.
* @default "levelLabel"
*/
levelLabel?: string;
/**
* The key in the JSON object to use as the highlighted message.
* @default "msg"
*
* Not required when used with pino >= 8.21.0
*/
messageKey?: string;
/**
* Print each log message on a single line (errors will still be multi-line).
* @default false
*/
singleLine?: boolean;
/**
* The key in the JSON object to use for timestamp display.
* @default "time"
*/
timestampKey?: string;
/**
* The minimum log level to include in the output.
* @default "trace"
*/
minimumLevel?: Level;
/**
* Format output of message, e.g. {level} - {pid} will output message: INFO - 1123
* @default false
*
* @example
* ```typescript
* {
* messageFormat: (log, messageKey) => {
* const message = log[messageKey];
* if (log.requestId) return `[${log.requestId}] ${message}`;
* return message;
* }
* }
* ```
*/
messageFormat?: false | string | MessageFormatFunc;
/**
* If set to true, will add color information to the formatted output message.
* @default false
*/
colorize?: boolean;
/**
* If set to false while `colorize` is `true`, will output JSON objects without color.
* @default true
*/
colorizeObjects?: boolean;
/**
* Appends carriage return and line feed, instead of just a line feed, to the formatted log line.
* @default false
*/
crlf?: boolean;
/**
* Define the log keys that are associated with error like objects.
* @default ["err", "error"]
*
* Not required to handle custom errorKey when used with pino >= 8.21.0
*/
errorLikeObjectKeys?: string[];
/**
* When formatting an error object, display this list of properties.
* The list should be a comma separated list of properties.
* @default ""
*/
errorProps?: string;
/**
* Ignore one or several keys.
* Will be overridden by the option include if include is presented.
* @example "time,hostname"
*/
ignore?: string;
/**
* Include one or several keys.
* @example "time,level"
*/
include?: string;
/**
* Makes messaging synchronous.
* @default false
*/
sync?: boolean;
/**
* The file, file descriptor, or stream to write to. Defaults to 1 (stdout).
* @default 1
*/
destination?: string | number | DestinationStream | NodeJS.WritableStream;
/**
* Opens the file with the 'a' flag.
* @default true
*/
append?: boolean;
/**
* Ensure directory for destination file exists.
* @default false
*/
mkdir?: boolean;
/**
* Provides the ability to add a custom prettify function for specific log properties.
* `customPrettifiers` is an object, where keys are log properties that will be prettified
* and value is the prettify function itself.
* For example, if a log line contains a query property, you can specify a prettifier for it:
* @default {}
*
* @example
* ```typescript
* {
* customPrettifiers: {
* query: prettifyQuery
* }
* }
* //...
* const prettifyQuery = value => {
* // do some prettify magic
* }
* ```
*/
customPrettifiers?: Record<string, Prettifier> &
{
level?: Prettifier
};
/**
* Change the level names and values to an user custom preset.
*
* Can be a CSV string in 'level_name:level_value' format or an object.
*
* @example ( CSV ) customLevels: 'info:10,some_level:40'
* @example ( Object ) customLevels: { info: 10, some_level: 40 }
*
* Not required when used with pino >= 8.21.0
*/
customLevels?: string|object;
/**
* Change the level colors to an user custom preset.
*
* Can be a CSV string in 'level_name:color_value' format or an object.
* Also supports 'default' as level_name for fallback color.
*
* @example ( CSV ) customColors: 'info:white,some_level:red'
* @example ( Object ) customColors: { info: 'white', some_level: 'red' }
*/
customColors?: string|object;
/**
* Only use custom levels and colors (if provided); else fallback to default levels and colors.
*
* @default true
*/
useOnlyCustomProps?: boolean;
}
function build(options: PrettyOptions): PrettyStream;
type Prettifier = (inputData: string | object, key: string, log: object, extras: PrettifierExtras) => string;
type PrettifierExtras = {colors: Colorette.Colorette, label: string, labelColorized: string};
type MessageFormatFunc = (log: LogDescriptor, messageKey: string, levelLabel: string, extras: PrettifierExtras) => string;
type PrettyStream = Transform & OnUnknown;
type ColorizerFactory = typeof colorizerFactory;
type PrettyFactory = typeof prettyFactory;
type Build = typeof build;
// @ts-ignore
export const isColorSupported = Colorette.isColorSupported;
export { build, PinoPretty, PrettyOptions, PrettyStream, colorizerFactory, prettyFactory };
}
export = PinoPretty;

View File

@@ -0,0 +1,39 @@
import { afterEach, expect, test } from "vitest";
import * as z from "zod/v4";
import * as core from "zod/v4/core";
// `globalConfig` is attached to `globalThis.__zod_globalConfig` so that a
// single config object is shared across CJS/ESM builds and across multiple
// bundled copies of Zod in a monorepo. This mirrors the existing
// `globalRegistry` -> `globalThis.__zod_globalRegistry` treatment.
//
// See #5789 for the footgun this fixes: users with both CJS and ESM
// instances of Zod loaded had to call `z.config({ jitless: true })`
// twice — once per instance — because each module-scope `globalConfig`
// was a different object. With this change, one call updates state seen
// by every loaded copy.
afterEach(() => {
// Don't leak config mutations into other test files.
delete core.globalConfig.jitless;
});
test("globalConfig is singleton and attached to globalThis", () => {
expect(core.globalConfig).toBe((globalThis as any).__zod_globalConfig);
});
test("z.config writes are observed via globalThis.__zod_globalConfig", () => {
z.config({ jitless: true });
expect((globalThis as any).__zod_globalConfig.jitless).toBe(true);
});
test("pre-set globalThis.__zod_globalConfig is preserved on import", () => {
// Object identity is preserved across reloads of the module: anyone who
// pre-populates `globalThis.__zod_globalConfig` before Zod loads (e.g.
// an inline script before the bundle) keeps that exact object as the
// source of truth. Mutating it directly is equivalent to z.config().
const direct = (globalThis as any).__zod_globalConfig;
direct.jitless = true;
expect(core.globalConfig.jitless).toBe(true);
expect(z.config()).toBe(core.globalConfig);
});

View File

@@ -0,0 +1,70 @@
import * as assert from 'node:assert/strict';
import v1 from './v1.js';
import v3 from './v3.js';
import v4 from './v4.js';
import v5 from './v5.js';
import v6 from './v6.js';
import v7 from './v7.js';
function usage() {
console.log('Usage:');
console.log(' uuid');
console.log(' uuid v1');
console.log(' uuid v3 <name> <namespace uuid>');
console.log(' uuid v4');
console.log(' uuid v5 <name> <namespace uuid>');
console.log(' uuid v6');
console.log(' uuid v7');
console.log(' uuid --help');
console.log('\nNote: <namespace uuid> may be "URL" or "DNS" to use the corresponding UUIDs defined by RFC9562');
}
const args = process.argv.slice(2);
if (args.indexOf('--help') >= 0) {
usage();
process.exit(0);
}
const version = args.shift() || 'v4';
switch (version) {
case 'v1':
console.log(v1());
break;
case 'v3': {
const name = args.shift();
let namespace = args.shift();
assert.ok(name != null, 'v3 name not specified');
assert.ok(namespace != null, 'v3 namespace not specified');
if (namespace === 'URL') {
namespace = v3.URL;
}
if (namespace === 'DNS') {
namespace = v3.DNS;
}
console.log(v3(name, namespace));
break;
}
case 'v4':
console.log(v4());
break;
case 'v5': {
const name = args.shift();
let namespace = args.shift();
assert.ok(name != null, 'v5 name not specified');
assert.ok(namespace != null, 'v5 namespace not specified');
if (namespace === 'URL') {
namespace = v5.URL;
}
if (namespace === 'DNS') {
namespace = v5.DNS;
}
console.log(v5(name, namespace));
break;
}
case 'v6':
console.log(v6());
break;
case 'v7':
console.log(v7());
break;
default:
usage();
process.exit(1);
}

View File

@@ -0,0 +1,184 @@
import _typeof from "./typeof.js";
function applyDecs2203Factory() {
function createAddInitializerMethod(e, t) {
return function (r) {
!function (e) {
if (e.v) throw Error("attempted to call addInitializer after decoration was finished");
}(t), assertCallable(r, "An initializer"), e.push(r);
};
}
function memberDec(e, t, r, a, n, i, s, o) {
var c;
switch (n) {
case 1:
c = "accessor";
break;
case 2:
c = "method";
break;
case 3:
c = "getter";
break;
case 4:
c = "setter";
break;
default:
c = "field";
}
var l,
u,
f = {
kind: c,
name: s ? "#" + t : t,
"static": i,
"private": s
},
p = {
v: !1
};
0 !== n && (f.addInitializer = createAddInitializerMethod(a, p)), 0 === n ? s ? (l = r.get, u = r.set) : (l = function l() {
return this[t];
}, u = function u(e) {
this[t] = e;
}) : 2 === n ? l = function l() {
return r.value;
} : (1 !== n && 3 !== n || (l = function l() {
return r.get.call(this);
}), 1 !== n && 4 !== n || (u = function u(e) {
r.set.call(this, e);
})), f.access = l && u ? {
get: l,
set: u
} : l ? {
get: l
} : {
set: u
};
try {
return e(o, f);
} finally {
p.v = !0;
}
}
function assertCallable(e, t) {
if ("function" != typeof e) throw new TypeError(t + " must be a function");
}
function assertValidReturnValue(e, t) {
var r = _typeof(t);
if (1 === e) {
if ("object" !== r || null === t) throw new TypeError("accessor decorators must return an object with get, set, or init properties or void 0");
void 0 !== t.get && assertCallable(t.get, "accessor.get"), void 0 !== t.set && assertCallable(t.set, "accessor.set"), void 0 !== t.init && assertCallable(t.init, "accessor.init");
} else if ("function" !== r) throw new TypeError((0 === e ? "field" : 10 === e ? "class" : "method") + " decorators must return a function or void 0");
}
function applyMemberDec(e, t, r, a, n, i, s, o) {
var c,
l,
u,
f,
p,
d,
h = r[0];
if (s ? c = 0 === n || 1 === n ? {
get: r[3],
set: r[4]
} : 3 === n ? {
get: r[3]
} : 4 === n ? {
set: r[3]
} : {
value: r[3]
} : 0 !== n && (c = Object.getOwnPropertyDescriptor(t, a)), 1 === n ? u = {
get: c.get,
set: c.set
} : 2 === n ? u = c.value : 3 === n ? u = c.get : 4 === n && (u = c.set), "function" == typeof h) void 0 !== (f = memberDec(h, a, c, o, n, i, s, u)) && (assertValidReturnValue(n, f), 0 === n ? l = f : 1 === n ? (l = f.init, p = f.get || u.get, d = f.set || u.set, u = {
get: p,
set: d
}) : u = f);else for (var v = h.length - 1; v >= 0; v--) {
var g;
void 0 !== (f = memberDec(h[v], a, c, o, n, i, s, u)) && (assertValidReturnValue(n, f), 0 === n ? g = f : 1 === n ? (g = f.init, p = f.get || u.get, d = f.set || u.set, u = {
get: p,
set: d
}) : u = f, void 0 !== g && (void 0 === l ? l = g : "function" == typeof l ? l = [l, g] : l.push(g)));
}
if (0 === n || 1 === n) {
if (void 0 === l) l = function l(e, t) {
return t;
};else if ("function" != typeof l) {
var y = l;
l = function l(e, t) {
for (var r = t, a = 0; a < y.length; a++) r = y[a].call(e, r);
return r;
};
} else {
var m = l;
l = function l(e, t) {
return m.call(e, t);
};
}
e.push(l);
}
0 !== n && (1 === n ? (c.get = u.get, c.set = u.set) : 2 === n ? c.value = u : 3 === n ? c.get = u : 4 === n && (c.set = u), s ? 1 === n ? (e.push(function (e, t) {
return u.get.call(e, t);
}), e.push(function (e, t) {
return u.set.call(e, t);
})) : 2 === n ? e.push(u) : e.push(function (e, t) {
return u.call(e, t);
}) : Object.defineProperty(t, a, c));
}
function pushInitializers(e, t) {
t && e.push(function (e) {
for (var r = 0; r < t.length; r++) t[r].call(e);
return e;
});
}
return function (e, t, r) {
var a = [];
return function (e, t, r) {
for (var a, n, i = new Map(), s = new Map(), o = 0; o < r.length; o++) {
var c = r[o];
if (Array.isArray(c)) {
var l,
u,
f = c[1],
p = c[2],
d = c.length > 3,
h = f >= 5;
if (h ? (l = t, 0 != (f -= 5) && (u = n = n || [])) : (l = t.prototype, 0 !== f && (u = a = a || [])), 0 !== f && !d) {
var v = h ? s : i,
g = v.get(p) || 0;
if (!0 === g || 3 === g && 4 !== f || 4 === g && 3 !== f) throw Error("Attempted to decorate a public method/accessor that has the same name as a previously decorated public method/accessor. This is not currently supported by the decorators plugin. Property name was: " + p);
!g && f > 2 ? v.set(p, f) : v.set(p, !0);
}
applyMemberDec(e, l, c, p, f, h, d, u);
}
}
pushInitializers(e, a), pushInitializers(e, n);
}(a, e, t), function (e, t, r) {
if (r.length > 0) {
for (var a = [], n = t, i = t.name, s = r.length - 1; s >= 0; s--) {
var o = {
v: !1
};
try {
var c = r[s](n, {
kind: "class",
name: i,
addInitializer: createAddInitializerMethod(a, o)
});
} finally {
o.v = !0;
}
void 0 !== c && (assertValidReturnValue(10, c), n = c);
}
e.push(n, function () {
for (var e = 0; e < a.length; e++) a[e].call(n);
});
}
}(a, e, r), a;
};
}
var applyDecs2203Impl;
function applyDecs2203(e, t, r) {
return (applyDecs2203Impl = applyDecs2203Impl || applyDecs2203Factory())(e, t, r);
}
export { applyDecs2203 as default };

View File

@@ -0,0 +1,17 @@
import type { TSESTree } from '@typescript-eslint/types';
import type { ScopeManager } from '../ScopeManager';
import type { ImplicitLibVariableOptions } from '../variable';
import type { Scope } from './Scope';
import { ScopeBase } from './ScopeBase';
import { ScopeType } from './ScopeType';
export declare class GlobalScope extends ScopeBase<ScopeType.global, TSESTree.Program,
/**
* The global scope has no parent.
*/
null> {
private readonly implicit;
constructor(scopeManager: ScopeManager, block: GlobalScope['block']);
addVariables(names: string[]): void;
close(scopeManager: ScopeManager): Scope | null;
defineImplicitVariable(name: string, options: ImplicitLibVariableOptions): void;
}

View File

@@ -0,0 +1,105 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const utils_1 = require("@typescript-eslint/utils");
const util_1 = require("../util");
const getESLintCoreRule_1 = require("../util/getESLintCoreRule");
const baseRule = (0, getESLintCoreRule_1.getESLintCoreRule)('init-declarations');
exports.default = (0, util_1.createRule)({
name: 'init-declarations',
meta: {
type: 'suggestion',
// defaultOptions, -- base rule does not use defaultOptions
docs: {
description: 'Require or disallow initialization in variable declarations',
extendsBaseRule: true,
frozen: true,
},
hasSuggestions: baseRule.meta.hasSuggestions,
messages: baseRule.meta.messages,
schema: baseRule.meta.schema,
},
defaultOptions: ['always'],
create(context, [mode]) {
// Make a custom context to adjust the loc of reports where the base
// rule's behavior is a bit too aggressive with TS-specific syntax (namely,
// type annotations).
function getBaseContextOverride() {
const reportOverride = descriptor => {
if ('node' in descriptor && descriptor.loc == null) {
const { node, ...rest } = descriptor;
// We only want to special case the report loc when reporting on
// variables declarations that are not initialized. Declarations that
// _are_ initialized get reported by the base rule due to a setting to
// prohibit initializing variables entirely, in which case underlining
// the whole node including the type annotation and initializer is
// appropriate.
if (node.type === utils_1.AST_NODE_TYPES.VariableDeclarator &&
node.init == null) {
context.report({
...rest,
loc: getReportLoc(node),
});
return;
}
}
context.report(descriptor);
};
// `return { ...context, report: reportOverride }` isn't safe because the
// `context` object has some getters that need to be preserved.
//
// `return new Proxy(context, ...)` doesn't work because `context` has
// non-configurable properties that throw when constructing a Proxy.
//
// So, we'll just use Proxy on a dummy object and use the `get` trap to
// proxy `context`'s properties.
return new Proxy({}, {
get: (target, prop, receiver) => prop === 'report'
? reportOverride
: Reflect.get(context, prop, receiver),
});
}
const rules = baseRule.create(getBaseContextOverride());
return {
'VariableDeclaration:exit'(node) {
if (mode === 'always') {
if (node.declare) {
return;
}
if (isAncestorNamespaceDeclared(node)) {
return;
}
}
rules['VariableDeclaration:exit'](node);
},
};
function isAncestorNamespaceDeclared(node) {
let ancestor = node.parent;
while (ancestor) {
if (ancestor.type === utils_1.AST_NODE_TYPES.TSModuleDeclaration &&
ancestor.declare) {
return true;
}
ancestor = ancestor.parent;
}
return false;
}
},
});
/**
* When reporting an uninitialized variable declarator, get the loc excluding
* the type annotation.
*/
function getReportLoc(node) {
const start = structuredClone(node.loc.start);
const end = {
line: node.loc.start.line,
// `if (id.type === AST_NODE_TYPES.Identifier)` is a condition for
// reporting in the base rule (as opposed to things like destructuring
// assignment), so the type assertion should always be valid.
column: node.loc.start.column + node.id.name.length,
};
return {
start,
end,
};
}

View File

@@ -0,0 +1,49 @@
/**
* @fileoverview Helpers for severity values (e.g. normalizing different types).
* @author Bryan Mishkin
*/
"use strict";
/**
* Convert severity value of different types to a string.
* @param {string|number} severity severity value
* @throws error if severity is invalid
* @returns {string} severity string
*/
function normalizeSeverityToString(severity) {
if ([2, "2", "error"].includes(severity)) {
return "error";
}
if ([1, "1", "warn"].includes(severity)) {
return "warn";
}
if ([0, "0", "off"].includes(severity)) {
return "off";
}
throw new Error(`Invalid severity value: ${severity}`);
}
/**
* Convert severity value of different types to a number.
* @param {string|number} severity severity value
* @throws error if severity is invalid
* @returns {number} severity number
*/
function normalizeSeverityToNumber(severity) {
if ([2, "2", "error"].includes(severity)) {
return 2;
}
if ([1, "1", "warn"].includes(severity)) {
return 1;
}
if ([0, "0", "off"].includes(severity)) {
return 0;
}
throw new Error(`Invalid severity value: ${severity}`);
}
module.exports = {
normalizeSeverityToString,
normalizeSeverityToNumber,
};

View File

@@ -0,0 +1,237 @@
/**
* @fileoverview Rule to require parens in arrow function arguments.
* @author Jxck
* @deprecated in ESLint v8.53.0
*/
"use strict";
//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------
const astUtils = require("./utils/ast-utils");
//------------------------------------------------------------------------------
// Helpers
//------------------------------------------------------------------------------
/**
* Determines if the given arrow function has block body.
* @param {ASTNode} node `ArrowFunctionExpression` node.
* @returns {boolean} `true` if the function has block body.
*/
function hasBlockBody(node) {
return node.body.type === "BlockStatement";
}
//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------
/** @type {import('../types').Rule.RuleModule} */
module.exports = {
meta: {
deprecated: {
message: "Formatting rules are being moved out of ESLint core.",
url: "https://eslint.org/blog/2023/10/deprecating-formatting-rules/",
deprecatedSince: "8.53.0",
availableUntil: "11.0.0",
replacedBy: [
{
message:
"ESLint Stylistic now maintains deprecated stylistic core rules.",
url: "https://eslint.style/guide/migration",
plugin: {
name: "@stylistic/eslint-plugin",
url: "https://eslint.style",
},
rule: {
name: "arrow-parens",
url: "https://eslint.style/rules/arrow-parens",
},
},
],
},
type: "layout",
docs: {
description: "Require parentheses around arrow function arguments",
recommended: false,
url: "https://eslint.org/docs/latest/rules/arrow-parens",
},
fixable: "code",
schema: [
{
enum: ["always", "as-needed"],
},
{
type: "object",
properties: {
requireForBlockBody: {
type: "boolean",
default: false,
},
},
additionalProperties: false,
},
],
messages: {
unexpectedParens:
"Unexpected parentheses around single function argument.",
expectedParens:
"Expected parentheses around arrow function argument.",
unexpectedParensInline:
"Unexpected parentheses around single function argument having a body with no curly braces.",
expectedParensBlock:
"Expected parentheses around arrow function argument having a body with curly braces.",
},
},
create(context) {
const asNeeded = context.options[0] === "as-needed";
const requireForBlockBody =
asNeeded &&
context.options[1] &&
context.options[1].requireForBlockBody === true;
const sourceCode = context.sourceCode;
/**
* Finds opening paren of parameters for the given arrow function, if it exists.
* It is assumed that the given arrow function has exactly one parameter.
* @param {ASTNode} node `ArrowFunctionExpression` node.
* @returns {Token|null} the opening paren, or `null` if the given arrow function doesn't have parens of parameters.
*/
function findOpeningParenOfParams(node) {
const tokenBeforeParams = sourceCode.getTokenBefore(node.params[0]);
if (
tokenBeforeParams &&
astUtils.isOpeningParenToken(tokenBeforeParams) &&
node.range[0] <= tokenBeforeParams.range[0]
) {
return tokenBeforeParams;
}
return null;
}
/**
* Finds closing paren of parameters for the given arrow function.
* It is assumed that the given arrow function has parens of parameters and that it has exactly one parameter.
* @param {ASTNode} node `ArrowFunctionExpression` node.
* @returns {Token} the closing paren of parameters.
*/
function getClosingParenOfParams(node) {
return sourceCode.getTokenAfter(
node.params[0],
astUtils.isClosingParenToken,
);
}
/**
* Determines whether the given arrow function has comments inside parens of parameters.
* It is assumed that the given arrow function has parens of parameters.
* @param {ASTNode} node `ArrowFunctionExpression` node.
* @param {Token} openingParen Opening paren of parameters.
* @returns {boolean} `true` if the function has at least one comment inside of parens of parameters.
*/
function hasCommentsInParensOfParams(node, openingParen) {
return sourceCode.commentsExistBetween(
openingParen,
getClosingParenOfParams(node),
);
}
/**
* Determines whether the given arrow function has unexpected tokens before opening paren of parameters,
* in which case it will be assumed that the existing parens of parameters are necessary.
* Only tokens within the range of the arrow function (tokens that are part of the arrow function) are taken into account.
* Example: <T>(a) => b
* @param {ASTNode} node `ArrowFunctionExpression` node.
* @param {Token} openingParen Opening paren of parameters.
* @returns {boolean} `true` if the function has at least one unexpected token.
*/
function hasUnexpectedTokensBeforeOpeningParen(node, openingParen) {
const expectedCount = node.async ? 1 : 0;
return (
sourceCode.getFirstToken(node, { skip: expectedCount }) !==
openingParen
);
}
return {
"ArrowFunctionExpression[params.length=1]"(node) {
const shouldHaveParens =
!asNeeded || (requireForBlockBody && hasBlockBody(node));
const openingParen = findOpeningParenOfParams(node);
const hasParens = openingParen !== null;
const [param] = node.params;
if (shouldHaveParens && !hasParens) {
context.report({
node,
messageId: requireForBlockBody
? "expectedParensBlock"
: "expectedParens",
loc: param.loc,
*fix(fixer) {
yield fixer.insertTextBefore(param, "(");
yield fixer.insertTextAfter(param, ")");
},
});
}
if (
!shouldHaveParens &&
hasParens &&
param.type === "Identifier" &&
!param.typeAnnotation &&
!node.returnType &&
!hasCommentsInParensOfParams(node, openingParen) &&
!hasUnexpectedTokensBeforeOpeningParen(node, openingParen)
) {
context.report({
node,
messageId: requireForBlockBody
? "unexpectedParensInline"
: "unexpectedParens",
loc: param.loc,
*fix(fixer) {
const tokenBeforeOpeningParen =
sourceCode.getTokenBefore(openingParen);
const closingParen = getClosingParenOfParams(node);
if (
tokenBeforeOpeningParen &&
tokenBeforeOpeningParen.range[1] ===
openingParen.range[0] &&
!astUtils.canTokensBeAdjacent(
tokenBeforeOpeningParen,
sourceCode.getFirstToken(param),
)
) {
yield fixer.insertTextBefore(openingParen, " ");
}
// remove parens, whitespace inside parens, and possible trailing comma
yield fixer.removeRange([
openingParen.range[0],
param.range[0],
]);
yield fixer.removeRange([
param.range[1],
closingParen.range[1],
]);
},
});
}
},
};
},
};

View File

@@ -0,0 +1,46 @@
import { expect, expectTypeOf, test } from "vitest";
import * as z from "zod/v3";
test("test", () => {
expect(true).toBe(true);
});
test("test2", () => {
expect(() => z.string().parse(234)).toThrowErrorMatchingInlineSnapshot(`
[ZodError: [
{
"code": "invalid_type",
"expected": "string",
"received": "number",
"path": [],
"message": "Expected string, received number"
}
]]
`);
});
test("async validation", async () => {
const testTuple = z
.tuple([z.string().refine(async () => true), z.number().refine(async () => true)])
.refine(async () => true);
expectTypeOf<typeof testTuple._output>().toEqualTypeOf<[string, number]>();
const val = await testTuple.parseAsync(["asdf", 1234]);
expect(val).toEqual(val);
const r1 = await testTuple.safeParseAsync(["asdf", "asdf"]);
expect(r1.success).toEqual(false);
expect(r1.error!).toMatchInlineSnapshot(`
[ZodError: [
{
"code": "invalid_type",
"expected": "number",
"received": "string",
"path": [
1
],
"message": "Expected number, received string"
}
]]
`);
});

View File

@@ -0,0 +1,2 @@
import type { LibDefinition } from '../variable';
export declare const es2024_collection: LibDefinition;

View File

@@ -0,0 +1,8 @@
global.process = { __proto__: process, pid: 123456 }
Date.now = function () { return 1459875739796 }
require('node:os').hostname = function () { return 'abcdefghijklmnopqr' }
const pino = require(require.resolve('./../../'))
const logger = pino({}, pino.destination(1))
logger.info('hello')
logger.info('world')
process.exit(0)

View File

@@ -0,0 +1 @@
export { _ as default } from "../esm/_skip_first_generator_next.js";

View File

@@ -0,0 +1,10 @@
/**
* @fileoverview exports for browsers
* @author 唯然<weiran.zsd@outlook.com>
*/
"use strict";
const { Linter } = require("./linter/linter");
module.exports = { Linter };

View File

@@ -0,0 +1,154 @@
import { Module } from "node:module";
import { MessageChannel } from "node:worker_threads";
import { fileURLToPath } from "node:url";
//#region ../../node_modules/.pnpm/fresh-import@0.2.1/node_modules/fresh-import/dist/index.js
const instanceId = Math.random().toString(36).slice(2);
const relativeImportRE = /^\.{1,2}(?:\/|\\)/;
function escapeRegExp(value) {
return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}
/**
* The tracking query name `fresh-import-<instance>`, where `<instance>` is a
* random value unique to this loaded module instance. Any two instances (even
* two copies of the same build loaded into the same process) get distinct
* names, so each hook only recognizes the imports it tagged itself.
*/
function buildQueryName() {
return `fresh-import-${instanceId}`;
}
/**
* Build the regex that matches the tracking query `?<name>=<id>,<context>`
* (or the `&<name>=...` form).
*/
function buildQueryRE(queryName) {
return new RegExp(`(?:\\?|&)${escapeRegExp(queryName)}=(\\d+),([^&]+)(?:&|$)`);
}
/**
* Build the tracking query `?<name>=<id>,<context>` that `collect` appends to
* the entry specifier. `id` cache-busts the import (a distinct URL forces a
* fresh evaluation) and `context` tags the import graph so the resolve hook can
* attribute resolved dependencies back to the originating collect.
*/
function formatTrackingQuery(queryName, id, context) {
return `?${queryName}=${id},${context}`;
}
/**
* Shared body of the resolve hook for both the on-thread and off-thread
* importers. Given an already-resolved `result`, decides whether it is a tracked
* relative file dependency; if so, reports it via `onDependency` and tags the
* URL so the query propagates to its own dependencies.
*
* The sync/async difference between the two hooks lives entirely in the caller
* (which awaits `nextResolve` or not); this function performs no I/O. `result`
* is mutated in place and returned.
*/
function trackResolved(specifier, context, result, queryName, queryRE, onDependency) {
const isRelativeImport = relativeImportRE.test(specifier);
if (result.format === "builtin" || !isRelativeImport) return result;
if (!context.parentURL || queryRE.test(result.url) || !result.url.startsWith("file:")) return result;
const m = queryRE.exec(context.parentURL);
if (m) {
const [, id, contextFile] = m;
onDependency(contextFile, result.url);
result.url = result.url.replace(/(\?)|$/, (_n, n1) => `?${queryName}=${id},${contextFile}${n1 === "?" ? "&" : ""}`);
}
return result;
}
var loader_default = "data:text/javascript,Math.random().toString(36).slice(2);%0Aconst relativeImportRE = /^\\.{1,2}(%3F:\\/|\\\\)/;%0Afunction escapeRegExp(value) {%0A%09return value.replace(/[.*+%3F^${}()|[\\]\\\\]/g, \"\\\\$&\");%0A}%0A/**%0A* Build the regex that matches the tracking query `%3F<name>=<id>,<context>`%0A* (or the `&<name>=...` form).%0A*/%0Afunction buildQueryRE(queryName) {%0A%09return new RegExp(`(%3F:\\\\%3F|&)${escapeRegExp(queryName)}=(\\\\d+),([^&]+)(%3F:&|$)`);%0A}%0A/**%0A* Shared body of the resolve hook for both the on-thread and off-thread%0A* importers. Given an already-resolved `result`, decides whether it is a tracked%0A* relative file dependency; if so, reports it via `onDependency` and tags the%0A* URL so the query propagates to its own dependencies.%0A*%0A* The sync/async difference between the two hooks lives entirely in the caller%0A* (which awaits `nextResolve` or not); this function performs no I/O. `result`%0A* is mutated in place and returned.%0A*/%0Afunction trackResolved(specifier, context, result, queryName, queryRE, onDependency) {%0A%09const isRelativeImport = relativeImportRE.test(specifier);%0A%09if (result.format === \"builtin\" || !isRelativeImport) return result;%0A%09if (!context.parentURL || queryRE.test(result.url) || !result.url.startsWith(\"file:\")) return result;%0A%09const m = queryRE.exec(context.parentURL);%0A%09if (m) {%0A%09%09const [, id, contextFile] = m;%0A%09%09onDependency(contextFile, result.url);%0A%09%09result.url = result.url.replace(/(\\%3F)|$/, (_n, n1) => `%3F${queryName}=${id},${contextFile}${n1 === \"%3F\" %3F \"&\" : \"\"}`);%0A%09}%0A%09return result;%0A}%0A//%23endregion%0A//%23region src/off-thread/loader.ts%0Alet port;%0Alet queryName;%0Alet queryRE;%0Aconst initialize = async (data) => {%0A%09port = data.port;%0A%09queryName = data.queryName;%0A%09queryRE = buildQueryRE(queryName);%0A};%0Aconst resolve = async (specifier, context, nextResolve) => {%0A%09return trackResolved(specifier, context, await nextResolve(specifier, context), queryName, queryRE, (ctx, url) => {%0A%09%09port.postMessage({%0A%09%09%09context: ctx,%0A%09%09%09url%0A%09%09});%0A%09});%0A};%0A//%23endregion%0Aexport { initialize, resolve };%0A";
let nextId$1 = 0;
/**
* Off-thread importer: registers an ESM loader in a worker thread via
* `Module.register` and receives tracked dependencies over a `MessagePort`.
* Used on Node versions without `Module.registerHooks`.
*/
function createOffThreadImporter() {
const queryName = buildQueryName();
const { port1, port2 } = new MessageChannel();
Module.register(loader_default, {
data: {
port: port2,
queryName
},
transferList: [port2]
});
port1.unref();
return { async collect(specifier) {
const id = nextId$1++;
const depsList = /* @__PURE__ */ new Set();
const onMessage = (e) => {
if (e.context === specifier) depsList.add(e.url);
};
port1.on("message", onMessage);
port1.unref();
try {
const result = await import(specifier + formatTrackingQuery(queryName, id, specifier));
await new Promise((resolve) => setImmediate(resolve));
return {
result,
dependencies: [...depsList].filter((url) => url.startsWith("file:")).map((url) => fileURLToPath(url))
};
} finally {
port1.off("message", onMessage);
}
} };
}
let nextId = 0;
/**
* On-thread importer: registers synchronous resolution hooks via
* `Module.registerHooks` (Node 22.15+/23.5+).
*/
function createOnThreadImporter() {
const registry = /* @__PURE__ */ new Map();
const queryName = buildQueryName();
const queryRE = buildQueryRE(queryName);
const resolve = (specifier, context, nextResolve) => {
return trackResolved(specifier, context, nextResolve(specifier, context), queryName, queryRE, (ctx, url) => {
registry.get(ctx)?.add(url);
});
};
Module.registerHooks({ resolve });
return { async collect(specifier) {
const id = nextId++;
const depsList = /* @__PURE__ */ new Set();
registry.set(specifier, depsList);
try {
return {
result: await import(specifier + formatTrackingQuery(queryName, id, specifier)),
dependencies: [...depsList].filter((url) => url.startsWith("file:")).map((url) => fileURLToPath(url))
};
} finally {
registry.delete(specifier);
}
} };
}
/**
* Create the importer best suited to the current runtime, or `undefined` if it
* provides neither module-hook API.
*/
function createImporter() {
if (Module.registerHooks) return createOnThreadImporter();
if (Module.register) return createOffThreadImporter();
}
let importer;
let initialized = false;
/**
* Import an ESM entry in its own fresh module graph (separate from Node's module
* cache and from other concurrent imports) and report the dependency files it
* pulled in.
*
* Each call re-evaluates the entry in a fresh graph; concurrent calls stay
* isolated from one another. Only statically-imported relative dependencies are
* tracked, not dynamic imports.
*
* Returns `undefined` on runtimes that provide neither `Module.registerHooks`
* nor `Module.register`.
*/
function freshImport(specifier) {
if (!initialized) {
importer = createImporter();
initialized = true;
}
return importer?.collect(specifier);
}
//#endregion
export { freshImport };

View File

@@ -0,0 +1,19 @@
'use strict'
const { parentPort, workerData } = require('worker_threads')
const { Writable } = require('node:stream')
module.exports = (options) => {
const myTransportStream = new Writable({
autoDestroy: true,
write (chunk, enc, cb) {
parentPort.postMessage({
code: 'EVENT',
name: 'workerData',
args: [workerData]
})
cb()
}
})
return myTransportStream
}

View File

@@ -0,0 +1,2 @@
import type { LibDefinition } from '../variable';
export declare const esnext_full: LibDefinition;

View File

@@ -0,0 +1,307 @@
import { readdir, readdirSync, realpath, realpathSync, stat, statSync } from "fs";
import { isAbsolute, posix, resolve } from "path";
import { fileURLToPath } from "url";
import { fdir } from "fdir";
import picomatch from "picomatch";
//#region src/utils.ts
const isReadonlyArray = Array.isArray;
const BACKSLASHES = /\\/g;
const DRIVE_RELATIVE_PATH = /^[A-Za-z]:$/;
const isWin = process.platform === "win32";
const ONLY_PARENT_DIRECTORIES = /^(\/?\.\.)+$/;
function getPartialMatcher(patterns, options = {}) {
const patternsCount = patterns.length;
const patternsParts = Array(patternsCount);
const matchers = Array(patternsCount);
let i, j;
for (i = 0; i < patternsCount; i++) {
const parts = splitPattern(patterns[i]);
patternsParts[i] = parts;
const partsCount = parts.length;
const partMatchers = Array(partsCount);
for (j = 0; j < partsCount; j++) partMatchers[j] = picomatch(parts[j], options);
matchers[i] = partMatchers;
}
return (input) => {
const inputParts = input.split("/");
if (inputParts[0] === ".." && ONLY_PARENT_DIRECTORIES.test(input)) return true;
for (i = 0; i < patternsCount; i++) {
const patternParts = patternsParts[i];
const matcher = matchers[i];
const inputPatternCount = inputParts.length;
const minParts = Math.min(inputPatternCount, patternParts.length);
j = 0;
while (j < minParts) {
const part = patternParts[j];
if (part.includes("/")) return true;
if (!matcher[j](inputParts[j])) break;
if (!options.noglobstar && part === "**") return true;
j++;
}
if (j === inputPatternCount) return true;
}
return false;
};
}
/* node:coverage ignore next 2 */
const WIN32_ROOT_DIR = /^[A-Z]:\/$/i;
const isRoot = isWin ? (p) => WIN32_ROOT_DIR.test(p) : (p) => p === "/";
function buildFormat(cwd, root, absolute) {
if (cwd === root || root.startsWith(`${cwd}/`)) {
if (absolute) {
const start = cwd.length + +!isRoot(cwd);
return (p, isDir) => p.slice(start, isDir ? -1 : void 0) || ".";
}
const prefix = root.slice(cwd.length + 1);
if (prefix) return (p, isDir) => {
if (p === ".") return prefix;
const result = `${prefix}/${p}`;
return isDir ? result.slice(0, -1) : result;
};
return (p, isDir) => isDir && p !== "." ? p.slice(0, -1) : p;
}
if (absolute) return (p) => posix.relative(cwd, p) || ".";
return (p) => posix.relative(cwd, `${root}/${p}`) || ".";
}
function buildRelative(cwd, root) {
if (root.startsWith(`${cwd}/`)) {
const prefix = root.slice(cwd.length + 1);
return (p) => `${prefix}/${p}`;
}
return (p) => {
const result = posix.relative(cwd, `${root}/${p}`);
return p[p.length - 1] === "/" && result !== "" ? `${result}/` : result || ".";
};
}
function ensureNonDriveRelativePath(path) {
return path.replace(DRIVE_RELATIVE_PATH, (match) => `${match}/`);
}
const splitPatternOptions = { parts: true };
function splitPattern(path) {
var _result$parts;
const result = picomatch.scan(path, splitPatternOptions);
return ((_result$parts = result.parts) === null || _result$parts === void 0 ? void 0 : _result$parts.length) ? result.parts : [path];
}
const ESCAPED_WIN32_BACKSLASHES = /\\(?![()[\]{}!+@])/g;
function convertPosixPathToPattern(path) {
return escapePosixPath(path);
}
function convertWin32PathToPattern(path) {
return escapeWin32Path(path).replace(ESCAPED_WIN32_BACKSLASHES, "/");
}
/**
* Converts a path to a pattern depending on the platform.
* Identical to {@link escapePath} on POSIX systems.
* @see {@link https://superchupu.dev/tinyglobby/documentation#convertPathToPattern}
*/
/* node:coverage ignore next 3 */
const convertPathToPattern = isWin ? convertWin32PathToPattern : convertPosixPathToPattern;
const POSIX_UNESCAPED_GLOB_SYMBOLS = /(?<!\\)([()[\]{}*?|]|^!|[!+@](?=\()|\\(?![()[\]{}!*+?@|]))/g;
const WIN32_UNESCAPED_GLOB_SYMBOLS = /(?<!\\)([()[\]{}]|^!|[!+@](?=\())/g;
const escapePosixPath = (path) => path.replace(POSIX_UNESCAPED_GLOB_SYMBOLS, "\\$&");
const escapeWin32Path = (path) => path.replace(WIN32_UNESCAPED_GLOB_SYMBOLS, "\\$&");
/**
* Escapes a path's special characters depending on the platform.
* @see {@link https://superchupu.dev/tinyglobby/documentation#escapePath}
*/
/* node:coverage ignore next */
const escapePath = isWin ? escapeWin32Path : escapePosixPath;
/**
* Checks if a pattern has dynamic parts.
*
* Has a few minor differences with [`fast-glob`](https://github.com/mrmlnc/fast-glob) for better accuracy:
*
* - Doesn't necessarily return `false` on patterns that include `\`.
* - Returns `true` if the pattern includes parentheses, regardless of them representing one single pattern or not.
* - Returns `true` for unfinished glob extensions i.e. `(h`, `+(h`.
* - Returns `true` for unfinished brace expansions as long as they include `,` or `..`.
*
* @see {@link https://superchupu.dev/tinyglobby/documentation#isDynamicPattern}
*/
function isDynamicPattern(pattern, options) {
if ((options === null || options === void 0 ? void 0 : options.caseSensitiveMatch) === false) return true;
const scan = picomatch.scan(pattern);
return scan.isGlob || scan.negated;
}
function log(...tasks) {
console.log(`[tinyglobby ${(/* @__PURE__ */ new Date()).toLocaleTimeString("es")}]`, ...tasks);
}
function ensureStringArray(value) {
return typeof value === "string" ? [value] : value !== null && value !== void 0 ? value : [];
}
//#endregion
//#region src/patterns.ts
const PARENT_DIRECTORY = /^(\/?\.\.)+/;
const ESCAPING_BACKSLASHES = /\\(?=[()[\]{}!*+?@|])/g;
function normalizePattern(pattern, opts, props, isIgnore) {
var _PARENT_DIRECTORY$exe;
const cwd = opts.cwd;
let result = pattern;
if (pattern[pattern.length - 1] === "/") result = pattern.slice(0, -1);
if (result[result.length - 1] !== "*" && opts.expandDirectories) result += "/**";
const escapedCwd = escapePath(cwd);
result = isAbsolute(result.replace(ESCAPING_BACKSLASHES, "")) ? posix.relative(escapedCwd, result) : posix.normalize(result);
const parentDir = (_PARENT_DIRECTORY$exe = PARENT_DIRECTORY.exec(result)) === null || _PARENT_DIRECTORY$exe === void 0 ? void 0 : _PARENT_DIRECTORY$exe[0];
const parts = splitPattern(result);
if (parentDir) {
const n = (parentDir.length + 1) / 3;
let i = 0;
const cwdParts = escapedCwd.split("/");
while (i < n && parts[i + n] === cwdParts[cwdParts.length + i - n]) {
result = result.slice(0, (n - i - 1) * 3) + result.slice((n - i) * 3 + parts[i + n].length + 1) || ".";
i++;
}
const potentialRoot = posix.join(cwd, parentDir.slice(i * 3));
if (potentialRoot[0] !== "." && props.root.length > potentialRoot.length) {
props.root = ensureNonDriveRelativePath(potentialRoot);
props.depthOffset = -n + i;
}
}
if (!isIgnore && props.depthOffset >= 0) {
var _props$commonPath;
(_props$commonPath = props.commonPath) !== null && _props$commonPath !== void 0 || (props.commonPath = parts);
const newCommonPath = [];
const length = Math.min(props.commonPath.length, parts.length);
for (let i = 0; i < length; i++) {
const part = parts[i];
if (part === "**" && !parts[i + 1]) {
newCommonPath.pop();
break;
}
if (i === parts.length - 1 || part !== props.commonPath[i] || isDynamicPattern(part)) break;
newCommonPath.push(part);
}
props.depthOffset = newCommonPath.length;
props.commonPath = newCommonPath;
props.root = ensureNonDriveRelativePath(newCommonPath.length > 0 ? posix.join(cwd, ...newCommonPath) : cwd);
}
return result;
}
function processPatterns(options, patterns, props) {
const matchPatterns = [];
const ignorePatterns = [];
for (const pattern of options.ignore) {
if (!pattern) continue;
if (pattern[0] !== "!" || pattern[1] === "(") ignorePatterns.push(normalizePattern(pattern, options, props, true));
}
for (const pattern of patterns) {
if (!pattern) continue;
if (pattern[0] !== "!" || pattern[1] === "(") matchPatterns.push(normalizePattern(pattern, options, props, false));
else if (pattern[1] !== "!" || pattern[2] === "(") ignorePatterns.push(normalizePattern(pattern.slice(1), options, props, true));
}
return {
match: matchPatterns,
ignore: ignorePatterns
};
}
//#endregion
//#region src/crawler.ts
function buildCrawler(options, patterns) {
const cwd = options.cwd;
const props = {
root: cwd,
depthOffset: 0
};
const processed = processPatterns(options, patterns, props);
if (options.debug) log("internal processing patterns:", processed);
const { absolute, caseSensitiveMatch, debug, dot, followSymbolicLinks, onlyDirectories } = options;
const root = props.root.replace(BACKSLASHES, "");
const matchOptions = {
dot,
nobrace: options.braceExpansion === false,
nocase: !caseSensitiveMatch,
noextglob: options.extglob === false,
noglobstar: options.globstar === false,
posix: true
};
const matcher = picomatch(processed.match, matchOptions);
const ignore = picomatch(processed.ignore, matchOptions);
const partialMatcher = getPartialMatcher(processed.match, matchOptions);
const format = buildFormat(cwd, root, absolute);
const excludeFormatter = absolute ? format : buildFormat(cwd, root, true);
const excludePredicate = (_, p) => {
const relativePath = excludeFormatter(p, true);
return relativePath !== "." && !partialMatcher(relativePath) || ignore(relativePath);
};
let maxDepth;
if (options.deep !== void 0) maxDepth = Math.round(options.deep - props.depthOffset);
const crawler = new fdir({
filters: [debug ? (p, isDirectory) => {
const path = format(p, isDirectory);
const matches = matcher(path) && !ignore(path);
if (matches) log(`matched ${path}`);
return matches;
} : (p, isDirectory) => {
const path = format(p, isDirectory);
return matcher(path) && !ignore(path);
}],
exclude: debug ? (_, p) => {
const skipped = excludePredicate(_, p);
log(`${skipped ? "skipped" : "crawling"} ${p}`);
return skipped;
} : excludePredicate,
fs: options.fs,
pathSeparator: "/",
relativePaths: !absolute,
resolvePaths: absolute,
includeBasePath: absolute,
resolveSymlinks: followSymbolicLinks,
excludeSymlinks: !followSymbolicLinks,
excludeFiles: onlyDirectories,
includeDirs: onlyDirectories || !options.onlyFiles,
maxDepth,
signal: options.signal
}).crawl(root);
if (options.debug) log("internal properties:", {
...props,
root
});
return [crawler, cwd !== root && !absolute && buildRelative(cwd, root)];
}
//#endregion
//#region src/index.ts
function formatPaths(paths, mapper) {
if (mapper) for (let i = paths.length - 1; i >= 0; i--) paths[i] = mapper(paths[i]);
return paths;
}
const defaultOptions = {
caseSensitiveMatch: true,
debug: !!process.env.TINYGLOBBY_DEBUG,
expandDirectories: true,
followSymbolicLinks: true,
onlyFiles: true
};
function getOptions(options) {
const opts = Object.assign({}, options);
for (const key in defaultOptions) if (opts[key] === void 0) Object.assign(opts, { [key]: defaultOptions[key] });
opts.cwd = (opts.cwd instanceof URL ? fileURLToPath(opts.cwd) : resolve(opts.cwd || process.cwd())).replace(BACKSLASHES, "/");
opts.ignore = ensureStringArray(opts.ignore);
opts.fs && (opts.fs = {
readdir: opts.fs.readdir || readdir,
readdirSync: opts.fs.readdirSync || readdirSync,
realpath: opts.fs.realpath || realpath,
realpathSync: opts.fs.realpathSync || realpathSync,
stat: opts.fs.stat || stat,
statSync: opts.fs.statSync || statSync
});
if (opts.debug) log("globbing with options:", opts);
return opts;
}
function getCrawler(globInput, inputOptions = {}) {
var _ref;
if (globInput && (inputOptions === null || inputOptions === void 0 ? void 0 : inputOptions.patterns)) throw new Error("Cannot pass patterns as both an argument and an option");
const isModern = isReadonlyArray(globInput) || typeof globInput === "string";
const patterns = ensureStringArray((_ref = isModern ? globInput : globInput.patterns) !== null && _ref !== void 0 ? _ref : "**/*");
const options = getOptions(isModern ? inputOptions : globInput);
return patterns.length > 0 ? buildCrawler(options, patterns) : [];
}
async function glob(globInput, options) {
const [crawler, relative] = getCrawler(globInput, options);
return crawler ? formatPaths(await crawler.withPromise(), relative) : [];
}
function globSync(globInput, options) {
const [crawler, relative] = getCrawler(globInput, options);
return crawler ? formatPaths(crawler.sync(), relative) : [];
}
//#endregion
export { convertPathToPattern, escapePath, glob, globSync, isDynamicPattern };

View File

@@ -0,0 +1,485 @@
/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
this file except in compliance with the License. You may obtain a copy of the
License at http://www.apache.org/licenses/LICENSE-2.0
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABILITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/// <reference lib="es2015.symbol.wellknown" />
/// <reference lib="es2020.intl" />
/// <reference lib="es2025.intl" />
declare namespace Temporal {
type CalendarLike = PlainDate | PlainDateTime | PlainMonthDay | PlainYearMonth | ZonedDateTime | string;
type DurationLike = Duration | DurationLikeObject | string;
type InstantLike = Instant | ZonedDateTime | string;
type PlainDateLike = PlainDate | ZonedDateTime | PlainDateTime | DateLikeObject | string;
type PlainDateTimeLike = PlainDateTime | ZonedDateTime | PlainDate | DateTimeLikeObject | string;
type PlainMonthDayLike = PlainMonthDay | DateLikeObject | string;
type PlainTimeLike = PlainTime | PlainDateTime | ZonedDateTime | TimeLikeObject | string;
type PlainYearMonthLike = PlainYearMonth | YearMonthLikeObject | string;
type TimeZoneLike = ZonedDateTime | string;
type ZonedDateTimeLike = ZonedDateTime | ZonedDateTimeLikeObject | string;
type PartialTemporalLike<T extends object> = {
[P in Exclude<keyof T, "calendar" | "timeZone">]?: T[P] | undefined;
};
interface DateLikeObject {
year?: number | undefined;
era?: string | undefined;
eraYear?: number | undefined;
month?: number | undefined;
monthCode?: string | undefined;
day: number;
calendar?: string | undefined;
}
interface DateTimeLikeObject extends DateLikeObject, TimeLikeObject {}
interface DurationLikeObject {
years?: number | undefined;
months?: number | undefined;
weeks?: number | undefined;
days?: number | undefined;
hours?: number | undefined;
minutes?: number | undefined;
seconds?: number | undefined;
milliseconds?: number | undefined;
microseconds?: number | undefined;
nanoseconds?: number | undefined;
}
interface TimeLikeObject {
hour?: number | undefined;
minute?: number | undefined;
second?: number | undefined;
millisecond?: number | undefined;
microsecond?: number | undefined;
nanosecond?: number | undefined;
}
interface YearMonthLikeObject extends Omit<DateLikeObject, "day"> {}
interface ZonedDateTimeLikeObject extends DateTimeLikeObject {
timeZone: TimeZoneLike;
offset?: string | undefined;
}
type DateUnit = "year" | "month" | "week" | "day";
type TimeUnit = "hour" | "minute" | "second" | "millisecond" | "microsecond" | "nanosecond";
type PluralizeUnit<T extends DateUnit | TimeUnit> =
| T
| {
year: "years";
month: "months";
week: "weeks";
day: "days";
hour: "hours";
minute: "minutes";
second: "seconds";
millisecond: "milliseconds";
microsecond: "microseconds";
nanosecond: "nanoseconds";
}[T];
interface DisambiguationOptions {
disambiguation?: "compatible" | "earlier" | "later" | "reject" | undefined;
}
interface OverflowOptions {
overflow?: "constrain" | "reject" | undefined;
}
interface TransitionOptions {
direction: "next" | "previous";
}
interface RoundingOptions<Units extends DateUnit | TimeUnit> {
smallestUnit?: PluralizeUnit<Units> | undefined;
roundingIncrement?: number | undefined;
roundingMode?: "ceil" | "floor" | "expand" | "trunc" | "halfCeil" | "halfFloor" | "halfExpand" | "halfTrunc" | "halfEven" | undefined;
}
interface RoundingOptionsWithLargestUnit<Units extends DateUnit | TimeUnit> extends RoundingOptions<Units> {
largestUnit?: "auto" | PluralizeUnit<Units> | undefined;
}
interface ToStringRoundingOptions<Units extends DateUnit | TimeUnit> extends Pick<RoundingOptions<Units>, "smallestUnit" | "roundingMode"> {}
interface ToStringRoundingOptionsWithFractionalSeconds<Units extends DateUnit | TimeUnit> extends ToStringRoundingOptions<Units> {
fractionalSecondDigits?: "auto" | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | undefined;
}
namespace Now {
function timeZoneId(): string;
function instant(): Instant;
function plainDateTimeISO(timeZone?: TimeZoneLike): PlainDateTime;
function zonedDateTimeISO(timeZone?: TimeZoneLike): ZonedDateTime;
function plainDateISO(timeZone?: TimeZoneLike): PlainDate;
function plainTimeISO(timeZone?: TimeZoneLike): PlainTime;
}
interface PlainDateToStringOptions {
calendarName?: "auto" | "always" | "never" | "critical" | undefined;
}
interface PlainDateToZonedDateTimeOptions {
plainTime?: PlainTimeLike | undefined;
timeZone: TimeZoneLike;
}
interface PlainDate {
readonly calendarId: string;
readonly era: string | undefined;
readonly eraYear: number | undefined;
readonly year: number;
readonly month: number;
readonly monthCode: string;
readonly day: number;
readonly dayOfWeek: number;
readonly dayOfYear: number;
readonly weekOfYear: number | undefined;
readonly yearOfWeek: number | undefined;
readonly daysInWeek: number;
readonly daysInMonth: number;
readonly daysInYear: number;
readonly monthsInYear: number;
readonly inLeapYear: boolean;
toPlainYearMonth(): PlainYearMonth;
toPlainMonthDay(): PlainMonthDay;
add(duration: DurationLike, options?: OverflowOptions): PlainDate;
subtract(duration: DurationLike, options?: OverflowOptions): PlainDate;
with(dateLike: PartialTemporalLike<DateLikeObject>, options?: OverflowOptions): PlainDate;
withCalendar(calendarLike: CalendarLike): PlainDate;
until(other: PlainDateLike, options?: RoundingOptionsWithLargestUnit<DateUnit>): Duration;
since(other: PlainDateLike, options?: RoundingOptionsWithLargestUnit<DateUnit>): Duration;
equals(other: PlainDateLike): boolean;
toPlainDateTime(time?: PlainTimeLike): PlainDateTime;
toZonedDateTime(timeZone: TimeZoneLike): ZonedDateTime;
toZonedDateTime(item: PlainDateToZonedDateTimeOptions): ZonedDateTime;
toString(options?: PlainDateToStringOptions): string;
toLocaleString(locales?: Intl.LocalesArgument, options?: Intl.DateTimeFormatOptions): string;
toJSON(): string;
valueOf(): never;
readonly [Symbol.toStringTag]: "Temporal.PlainDate";
}
interface PlainDateConstructor {
new (isoYear: number, isoMonth: number, isoDay: number, calendar?: string): PlainDate;
readonly prototype: PlainDate;
from(item: PlainDateLike, options?: OverflowOptions): PlainDate;
compare(one: PlainDateLike, two: PlainDateLike): number;
}
var PlainDate: PlainDateConstructor;
interface PlainTimeToStringOptions extends ToStringRoundingOptionsWithFractionalSeconds<Exclude<TimeUnit, "hour">> {}
interface PlainTime {
readonly hour: number;
readonly minute: number;
readonly second: number;
readonly millisecond: number;
readonly microsecond: number;
readonly nanosecond: number;
add(duration: DurationLike): PlainTime;
subtract(duration: DurationLike): PlainTime;
with(timeLike: PartialTemporalLike<TimeLikeObject>, options?: OverflowOptions): PlainTime;
until(other: PlainTimeLike, options?: RoundingOptionsWithLargestUnit<TimeUnit>): Duration;
since(other: PlainTimeLike, options?: RoundingOptionsWithLargestUnit<TimeUnit>): Duration;
equals(other: PlainTimeLike): boolean;
round(roundTo: PluralizeUnit<TimeUnit>): PlainTime;
round(roundTo: RoundingOptions<TimeUnit>): PlainTime;
toString(options?: PlainTimeToStringOptions): string;
toLocaleString(locales?: Intl.LocalesArgument, options?: Intl.DateTimeFormatOptions): string;
toJSON(): string;
valueOf(): never;
readonly [Symbol.toStringTag]: "Temporal.PlainTime";
}
interface PlainTimeConstructor {
new (hour?: number, minute?: number, second?: number, millisecond?: number, microsecond?: number, nanosecond?: number): PlainTime;
readonly prototype: PlainTime;
from(item: PlainTimeLike, options?: OverflowOptions): PlainTime;
compare(one: PlainTimeLike, two: PlainTimeLike): number;
}
var PlainTime: PlainTimeConstructor;
interface PlainDateTimeToStringOptions extends PlainDateToStringOptions, PlainTimeToStringOptions {}
interface PlainDateTime {
readonly calendarId: string;
readonly era: string | undefined;
readonly eraYear: number | undefined;
readonly year: number;
readonly month: number;
readonly monthCode: string;
readonly day: number;
readonly hour: number;
readonly minute: number;
readonly second: number;
readonly millisecond: number;
readonly microsecond: number;
readonly nanosecond: number;
readonly dayOfWeek: number;
readonly dayOfYear: number;
readonly weekOfYear: number | undefined;
readonly yearOfWeek: number | undefined;
readonly daysInWeek: number;
readonly daysInMonth: number;
readonly daysInYear: number;
readonly monthsInYear: number;
readonly inLeapYear: boolean;
with(dateTimeLike: PartialTemporalLike<DateTimeLikeObject>, options?: OverflowOptions): PlainDateTime;
withPlainTime(plainTime?: PlainTimeLike): PlainDateTime;
withCalendar(calendar: CalendarLike): PlainDateTime;
add(duration: DurationLike, options?: OverflowOptions): PlainDateTime;
subtract(duration: DurationLike, options?: OverflowOptions): PlainDateTime;
until(other: PlainDateTimeLike, options?: RoundingOptionsWithLargestUnit<DateUnit | TimeUnit>): Duration;
since(other: PlainDateTimeLike, options?: RoundingOptionsWithLargestUnit<DateUnit | TimeUnit>): Duration;
round(roundTo: PluralizeUnit<"day" | TimeUnit>): PlainDateTime;
round(roundTo: RoundingOptions<"day" | TimeUnit>): PlainDateTime;
equals(other: PlainDateTimeLike): boolean;
toString(options?: PlainDateTimeToStringOptions): string;
toLocaleString(locales?: Intl.LocalesArgument, options?: Intl.DateTimeFormatOptions): string;
toJSON(): string;
valueOf(): never;
toZonedDateTime(timeZone: TimeZoneLike, options?: DisambiguationOptions): ZonedDateTime;
toPlainDate(): PlainDate;
toPlainTime(): PlainTime;
readonly [Symbol.toStringTag]: "Temporal.PlainDateTime";
}
interface PlainDateTimeConstructor {
new (isoYear: number, isoMonth: number, isoDay: number, hour?: number, minute?: number, second?: number, millisecond?: number, microsecond?: number, nanosecond?: number, calendar?: string): PlainDateTime;
readonly prototype: PlainDateTime;
from(item: PlainDateTimeLike, options?: OverflowOptions): PlainDateTime;
compare(one: PlainDateTimeLike, two: PlainDateTimeLike): number;
}
var PlainDateTime: PlainDateTimeConstructor;
interface ZonedDateTimeToStringOptions extends PlainDateTimeToStringOptions {
offset?: "auto" | "never" | undefined;
timeZoneName?: "auto" | "never" | "critical" | undefined;
}
interface ZonedDateTimeFromOptions extends OverflowOptions, DisambiguationOptions {
offset?: "use" | "ignore" | "prefer" | "reject" | undefined;
}
interface ZonedDateTime {
readonly calendarId: string;
readonly timeZoneId: string;
readonly era: string | undefined;
readonly eraYear: number | undefined;
readonly year: number;
readonly month: number;
readonly monthCode: string;
readonly day: number;
readonly hour: number;
readonly minute: number;
readonly second: number;
readonly millisecond: number;
readonly microsecond: number;
readonly nanosecond: number;
readonly epochMilliseconds: number;
readonly epochNanoseconds: bigint;
readonly dayOfWeek: number;
readonly dayOfYear: number;
readonly weekOfYear: number | undefined;
readonly yearOfWeek: number | undefined;
readonly hoursInDay: number;
readonly daysInWeek: number;
readonly daysInMonth: number;
readonly daysInYear: number;
readonly monthsInYear: number;
readonly inLeapYear: boolean;
readonly offsetNanoseconds: number;
readonly offset: string;
with(zonedDateTimeLike: PartialTemporalLike<ZonedDateTimeLikeObject>, options?: ZonedDateTimeFromOptions): ZonedDateTime;
withPlainTime(plainTime?: PlainTimeLike): ZonedDateTime;
withTimeZone(timeZone: TimeZoneLike): ZonedDateTime;
withCalendar(calendar: CalendarLike): ZonedDateTime;
add(duration: DurationLike, options?: OverflowOptions): ZonedDateTime;
subtract(duration: DurationLike, options?: OverflowOptions): ZonedDateTime;
until(other: ZonedDateTimeLike, options?: RoundingOptionsWithLargestUnit<DateUnit | TimeUnit>): Duration;
since(other: ZonedDateTimeLike, options?: RoundingOptionsWithLargestUnit<DateUnit | TimeUnit>): Duration;
round(roundTo: PluralizeUnit<"day" | TimeUnit>): ZonedDateTime;
round(roundTo: RoundingOptions<"day" | TimeUnit>): ZonedDateTime;
equals(other: ZonedDateTimeLike): boolean;
toString(options?: ZonedDateTimeToStringOptions): string;
toLocaleString(locales?: Intl.LocalesArgument, options?: Intl.DateTimeFormatOptions): string;
toJSON(): string;
valueOf(): never;
startOfDay(): ZonedDateTime;
getTimeZoneTransition(direction: "next" | "previous"): ZonedDateTime | null;
getTimeZoneTransition(direction: TransitionOptions): ZonedDateTime | null;
toInstant(): Instant;
toPlainDate(): PlainDate;
toPlainTime(): PlainTime;
toPlainDateTime(): PlainDateTime;
readonly [Symbol.toStringTag]: "Temporal.ZonedDateTime";
}
interface ZonedDateTimeConstructor {
new (epochNanoseconds: bigint, timeZone: string, calendar?: string): ZonedDateTime;
readonly prototype: ZonedDateTime;
from(item: ZonedDateTimeLike, options?: ZonedDateTimeFromOptions): ZonedDateTime;
compare(one: ZonedDateTimeLike, two: ZonedDateTimeLike): number;
}
var ZonedDateTime: ZonedDateTimeConstructor;
interface DurationRelativeToOptions {
relativeTo?: ZonedDateTimeLike | PlainDateLike | undefined;
}
interface DurationRoundingOptions extends DurationRelativeToOptions, RoundingOptionsWithLargestUnit<DateUnit | TimeUnit> {}
interface DurationToStringOptions extends ToStringRoundingOptionsWithFractionalSeconds<Exclude<TimeUnit, "hour" | "minute">> {}
interface DurationTotalOptions extends DurationRelativeToOptions {
unit: PluralizeUnit<DateUnit | TimeUnit>;
}
interface Duration {
readonly years: number;
readonly months: number;
readonly weeks: number;
readonly days: number;
readonly hours: number;
readonly minutes: number;
readonly seconds: number;
readonly milliseconds: number;
readonly microseconds: number;
readonly nanoseconds: number;
readonly sign: number;
readonly blank: boolean;
with(durationLike: PartialTemporalLike<DurationLikeObject>): Duration;
negated(): Duration;
abs(): Duration;
add(other: DurationLike): Duration;
subtract(other: DurationLike): Duration;
round(roundTo: PluralizeUnit<"day" | TimeUnit>): Duration;
round(roundTo: DurationRoundingOptions): Duration;
total(totalOf: PluralizeUnit<"day" | TimeUnit>): number;
total(totalOf: DurationTotalOptions): number;
toString(options?: DurationToStringOptions): string;
toLocaleString(locales?: Intl.LocalesArgument, options?: Intl.DurationFormatOptions): string;
toJSON(): string;
valueOf(): never;
readonly [Symbol.toStringTag]: "Temporal.Duration";
}
interface DurationConstructor {
new (years?: number, months?: number, weeks?: number, days?: number, hours?: number, minutes?: number, seconds?: number, milliseconds?: number, microseconds?: number, nanoseconds?: number): Duration;
readonly prototype: Duration;
from(item: DurationLike): Duration;
compare(one: DurationLike, two: DurationLike, options?: DurationRelativeToOptions): number;
}
var Duration: DurationConstructor;
interface InstantToStringOptions extends PlainTimeToStringOptions {
timeZone?: TimeZoneLike | undefined;
}
interface Instant {
readonly epochMilliseconds: number;
readonly epochNanoseconds: bigint;
add(duration: DurationLike): Instant;
subtract(duration: DurationLike): Instant;
until(other: InstantLike, options?: RoundingOptionsWithLargestUnit<TimeUnit>): Duration;
since(other: InstantLike, options?: RoundingOptionsWithLargestUnit<TimeUnit>): Duration;
round(roundTo: PluralizeUnit<TimeUnit>): Instant;
round(roundTo: RoundingOptions<TimeUnit>): Instant;
equals(other: InstantLike): boolean;
toString(options?: InstantToStringOptions): string;
toLocaleString(locales?: Intl.LocalesArgument, options?: Intl.DateTimeFormatOptions): string;
toJSON(): string;
valueOf(): never;
toZonedDateTimeISO(timeZone: TimeZoneLike): ZonedDateTime;
readonly [Symbol.toStringTag]: "Temporal.Instant";
}
interface InstantConstructor {
new (epochNanoseconds: bigint): Instant;
readonly prototype: Instant;
from(item: InstantLike): Instant;
fromEpochMilliseconds(epochMilliseconds: number): Instant;
fromEpochNanoseconds(epochNanoseconds: bigint): Instant;
compare(one: InstantLike, two: InstantLike): number;
}
var Instant: InstantConstructor;
interface PlainYearMonthToPlainDateOptions {
day: number;
}
interface PlainYearMonth {
readonly calendarId: string;
readonly era: string | undefined;
readonly eraYear: number | undefined;
readonly year: number;
readonly month: number;
readonly monthCode: string;
readonly daysInYear: number;
readonly daysInMonth: number;
readonly monthsInYear: number;
readonly inLeapYear: boolean;
with(yearMonthLike: PartialTemporalLike<YearMonthLikeObject>, options?: OverflowOptions): PlainYearMonth;
add(duration: DurationLike, options?: OverflowOptions): PlainYearMonth;
subtract(duration: DurationLike, options?: OverflowOptions): PlainYearMonth;
until(other: PlainYearMonthLike, options?: RoundingOptionsWithLargestUnit<"year" | "month">): Duration;
since(other: PlainYearMonthLike, options?: RoundingOptionsWithLargestUnit<"year" | "month">): Duration;
equals(other: PlainYearMonthLike): boolean;
toString(options?: PlainDateToStringOptions): string;
toLocaleString(locales?: Intl.LocalesArgument, options?: Intl.DateTimeFormatOptions): string;
toJSON(): string;
valueOf(): never;
toPlainDate(item: PlainYearMonthToPlainDateOptions): PlainDate;
readonly [Symbol.toStringTag]: "Temporal.PlainYearMonth";
}
interface PlainYearMonthConstructor {
new (isoYear: number, isoMonth: number, calendar?: string, referenceISODay?: number): PlainYearMonth;
readonly prototype: PlainYearMonth;
from(item: PlainYearMonthLike, options?: OverflowOptions): PlainYearMonth;
compare(one: PlainYearMonthLike, two: PlainYearMonthLike): number;
}
var PlainYearMonth: PlainYearMonthConstructor;
interface PlainMonthDayToPlainDateOptions {
era?: string | undefined;
eraYear?: number | undefined;
year?: number | undefined;
}
interface PlainMonthDay {
readonly calendarId: string;
readonly monthCode: string;
readonly day: number;
with(monthDayLike: PartialTemporalLike<DateLikeObject>, options?: OverflowOptions): PlainMonthDay;
equals(other: PlainMonthDayLike): boolean;
toString(options?: PlainDateToStringOptions): string;
toLocaleString(locales?: Intl.LocalesArgument, options?: Intl.DateTimeFormatOptions): string;
toJSON(): string;
valueOf(): never;
toPlainDate(item: PlainMonthDayToPlainDateOptions): PlainDate;
readonly [Symbol.toStringTag]: "Temporal.PlainMonthDay";
}
interface PlainMonthDayConstructor {
new (isoMonth: number, isoDay: number, calendar?: string, referenceISOYear?: number): PlainMonthDay;
readonly prototype: PlainMonthDay;
from(item: PlainMonthDayLike, options?: OverflowOptions): PlainMonthDay;
}
var PlainMonthDay: PlainMonthDayConstructor;
}

View File

@@ -0,0 +1,114 @@
import Document from './document.js'
import LazyResult from './lazy-result.js'
import NoWorkResult from './no-work-result.js'
import {
AcceptedPlugin,
Plugin,
ProcessOptions,
TransformCallback,
Transformer
} from './postcss.js'
import Result from './result.js'
import Root from './root.js'
declare namespace Processor {
export { Processor_ as default }
}
/**
* Contains plugins to process CSS. Create one `Processor` instance,
* initialize its plugins, and then use that instance on numerous CSS files.
*
* ```js
* const processor = postcss([autoprefixer, postcssNested])
* processor.process(css1).then(result => console.log(result.css))
* processor.process(css2).then(result => console.log(result.css))
* ```
*/
declare class Processor_ {
/**
* Plugins added to this processor.
*
* ```js
* const processor = postcss([autoprefixer, postcssNested])
* processor.plugins.length //=> 2
* ```
*/
plugins: (Plugin | TransformCallback | Transformer)[]
/**
* Current PostCSS version.
*
* ```js
* if (result.processor.version.split('.')[0] !== '6') {
* throw new Error('This plugin works only with PostCSS 6')
* }
* ```
*/
version: string
/**
* @param plugins PostCSS plugins
*/
constructor(plugins?: readonly AcceptedPlugin[])
/**
* Parses source CSS and returns a `LazyResult` Promise proxy.
* Because some plugins can be asynchronous it doesnt make
* any transformations. Transformations will be applied
* in the `LazyResult` methods.
*
* ```js
* processor.process(css, { from: 'a.css', to: 'a.out.css' })
* .then(result => {
* console.log(result.css)
* })
* ```
*
* @param css String with input CSS or any object with a `toString()` method,
* like a Buffer. Optionally, send a `Result` instance
* and the processor will take the `Root` from it.
* @param opts Options.
* @return Promise proxy.
*/
process(
css: { toString(): string } | LazyResult | Result | Root | string
): LazyResult | NoWorkResult
process<RootNode extends Document | Root = Root>(
css: { toString(): string } | LazyResult | Result | Root | string,
options: ProcessOptions<RootNode>
): LazyResult<RootNode>
/**
* Adds a plugin to be used as a CSS processor.
*
* PostCSS plugin can be in 4 formats:
* * A plugin in `Plugin` format.
* * A plugin creator function with `pluginCreator.postcss = true`.
* PostCSS will call this function without argument to get plugin.
* * A function. PostCSS will pass the function a {@link Root}
* as the first argument and current `Result` instance
* as the second.
* * Another `Processor` instance. PostCSS will copy plugins
* from that instance into this one.
*
* Plugins can also be added by passing them as arguments when creating
* a `postcss` instance (see [`postcss(plugins)`]).
*
* Asynchronous plugins should return a `Promise` instance.
*
* ```js
* const processor = postcss()
* .use(autoprefixer)
* .use(postcssNested)
* ```
*
* @param plugin PostCSS plugin or `Processor` with plugins.
* @return Current processor to make methods chain.
*/
use(plugin: AcceptedPlugin): this
}
declare class Processor extends Processor_ {}
export = Processor

View File

@@ -0,0 +1,210 @@
"use strict";
/* --------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
* ------------------------------------------------------------------------------------------ */
Object.defineProperty(exports, "__esModule", { value: true });
exports.PromiseImpl = exports.QueueMicrotaskImpl = void 0;
const api_1 = require("../common/api");
class MessageBuffer extends api_1.AbstractMessageBuffer {
static emptyBuffer = new Uint8Array(0);
asciiDecoder;
constructor(encoding = 'utf-8') {
super(encoding);
this.asciiDecoder = new TextDecoder('ascii');
}
emptyBuffer() {
return MessageBuffer.emptyBuffer;
}
fromString(value, _encoding) {
return (new TextEncoder()).encode(value);
}
toString(value, encoding) {
if (encoding === 'ascii') {
return this.asciiDecoder.decode(value);
}
else {
return (new TextDecoder(encoding)).decode(value);
}
}
asNative(buffer, length) {
if (length === undefined) {
return buffer;
}
else {
return buffer.slice(0, length);
}
}
allocNative(length) {
return new Uint8Array(length);
}
}
class ReadableStreamWrapper {
socket;
_onData;
_messageListener;
constructor(socket) {
this.socket = socket;
this._onData = new api_1.Emitter();
this._messageListener = (event) => {
const blob = event.data;
blob.arrayBuffer().then((buffer) => {
this._onData.fire(new Uint8Array(buffer));
}, () => {
(0, api_1.RAL)().console.error(`Converting blob to array buffer failed.`);
});
};
this.socket.addEventListener('message', this._messageListener);
}
onClose(listener) {
this.socket.addEventListener('close', listener);
return api_1.Disposable.create(() => this.socket.removeEventListener('close', listener));
}
onError(listener) {
this.socket.addEventListener('error', listener);
return api_1.Disposable.create(() => this.socket.removeEventListener('error', listener));
}
onEnd(listener) {
this.socket.addEventListener('end', listener);
return api_1.Disposable.create(() => this.socket.removeEventListener('end', listener));
}
onData(listener) {
return this._onData.event(listener);
}
}
class WritableStreamWrapper {
socket;
constructor(socket) {
this.socket = socket;
}
onClose(listener) {
this.socket.addEventListener('close', listener);
return api_1.Disposable.create(() => this.socket.removeEventListener('close', listener));
}
onError(listener) {
this.socket.addEventListener('error', listener);
return api_1.Disposable.create(() => this.socket.removeEventListener('error', listener));
}
onEnd(listener) {
this.socket.addEventListener('end', listener);
return api_1.Disposable.create(() => this.socket.removeEventListener('end', listener));
}
write(data, encoding) {
if (typeof data === 'string') {
if (encoding !== undefined && encoding !== 'utf-8') {
throw new Error(`In a Browser environments only utf-8 text encoding is supported. But got encoding: ${encoding}`);
}
this.socket.send(data);
}
else {
if (data.buffer instanceof ArrayBuffer) {
this.socket.send(data.buffer);
}
else {
// We can't send a shared array buffer directly, so we need to
// create a copy of it.
this.socket.send(new Uint8Array(data.buffer).slice().buffer);
}
}
return Promise.resolve();
}
end() {
this.socket.close();
}
}
class QueueMicrotaskImpl {
isDisposed;
constructor(callback, ...args) {
this.isDisposed = false;
queueMicrotask(() => {
if (!this.isDisposed) {
callback(...args);
}
});
}
dispose() {
this.isDisposed = true;
}
}
exports.QueueMicrotaskImpl = QueueMicrotaskImpl;
class PromiseImpl {
isDisposed;
constructor(callback, ...args) {
this.isDisposed = false;
Promise.resolve().then(() => {
if (!this.isDisposed) {
callback(...args);
}
}, () => {
});
}
dispose() {
this.isDisposed = true;
}
}
exports.PromiseImpl = PromiseImpl;
const _textEncoder = new TextEncoder();
const _ril = Object.freeze({
messageBuffer: Object.freeze({
create: (encoding) => new MessageBuffer(encoding)
}),
applicationJson: Object.freeze({
encoder: Object.freeze({
name: 'application/json',
encode: (msg, options) => {
if (options.charset !== 'utf-8') {
throw new Error(`In a Browser environments only utf-8 text encoding is supported. But got encoding: ${options.charset}`);
}
return Promise.resolve(_textEncoder.encode(JSON.stringify(msg, undefined, 0)));
}
}),
decoder: Object.freeze({
name: 'application/json',
decode: (buffer, options) => {
if (!(buffer instanceof Uint8Array)) {
throw new Error(`In a Browser environments only Uint8Arrays are supported.`);
}
return Promise.resolve(JSON.parse(new TextDecoder(options.charset).decode(buffer)));
}
})
}),
stream: Object.freeze({
asReadableStream: (socket) => new ReadableStreamWrapper(socket),
asWritableStream: (socket) => new WritableStreamWrapper(socket)
}),
console: console,
timer: Object.freeze({
setTimeout(callback, ms, ...args) {
const handle = setTimeout(callback, ms, ...args);
return { dispose: () => clearTimeout(handle) };
},
setImmediate(callback, ...args) {
// Browser don't have setImmediate and setTimeout with 0 delay of 0 can cause problems
// in webviews and similar environments due to throttling.
if (typeof globalThis.queueMicrotask === 'function') {
return new QueueMicrotaskImpl(callback, ...args);
}
else if (Promise !== undefined) {
return new PromiseImpl(callback, ...args);
}
else {
const handle = setTimeout(callback, 0, ...args);
return { dispose: () => clearTimeout(handle) };
}
},
setInterval(callback, ms, ...args) {
const handle = setInterval(callback, ms, ...args);
return { dispose: () => clearInterval(handle) };
},
})
});
function RIL() {
return _ril;
}
(function (RIL) {
function install() {
api_1.RAL.install(_ril);
}
RIL.install = install;
})(RIL || (RIL = {}));
exports.default = RIL;

View File

@@ -0,0 +1,49 @@
'use strict'
module.exports = prettifyError
const joinLinesWithIndentation = require('./join-lines-with-indentation')
/**
* @typedef {object} PrettifyErrorParams
* @property {string} keyName The key assigned to this error in the log object.
* @property {string} lines The STRINGIFIED error. If the error field has a
* custom prettifier, that should be pre-applied as well.
* @property {string} ident The indentation sequence to use.
* @property {string} eol The EOL sequence to use.
*/
/**
* Prettifies an error string into a multi-line format.
*
* @param {PrettifyErrorParams} input
*
* @returns {string}
*/
function prettifyError ({ keyName, lines, eol, ident }) {
let result = ''
const joinedLines = joinLinesWithIndentation({ input: lines, ident, eol })
const splitLines = `${ident}${keyName}: ${joinedLines}${eol}`.split(eol)
for (let j = 0; j < splitLines.length; j += 1) {
if (j !== 0) result += eol
const line = splitLines[j]
if (/^\s*"stack"/.test(line)) {
const matches = /^(\s*"stack":)\s*(".*"),?$/.exec(line)
/* istanbul ignore else */
if (matches && matches.length === 3) {
const indentSize = /^\s*/.exec(line)[0].length + 4
const indentation = ' '.repeat(indentSize)
const stackMessage = matches[2]
result += matches[1] + eol + indentation + JSON.parse(stackMessage).replace(/\n/g, eol + indentation)
} else {
result += line
}
} else {
result += line
}
}
return result
}

View File

@@ -0,0 +1,169 @@
import { SocketOptions, Socket, TlsOptions } from 'cloudflare:sockets'
import { EventEmitter } from 'events'
/**
* Wrapper around the Cloudflare built-in socket that can be used by the `Connection`.
*/
export class CloudflareSocket extends EventEmitter {
writable = false
destroyed = false
private _upgrading = false
private _upgraded = false
private _cfSocket: Socket | null = null
private _cfWriter: WritableStreamDefaultWriter | null = null
private _cfReader: ReadableStreamDefaultReader | null = null
constructor(readonly ssl: boolean) {
super()
}
setNoDelay() {
return this
}
setKeepAlive() {
return this
}
ref() {
return this
}
unref() {
return this
}
async connect(port: number, host: string, connectListener?: (...args: unknown[]) => void) {
try {
log('connecting')
if (connectListener) this.once('connect', connectListener)
const options: SocketOptions = this.ssl ? { secureTransport: 'starttls' } : {}
const mod = await import('cloudflare:sockets')
const connect = mod.connect
this._cfSocket = connect(`${host}:${port}`, options)
this._cfWriter = this._cfSocket.writable.getWriter()
this._addClosedHandler()
this._cfReader = this._cfSocket.readable.getReader()
if (this.ssl) {
this._listenOnce().catch((e) => this.emit('error', e))
} else {
this._listen().catch((e) => this.emit('error', e))
}
await this._cfWriter!.ready
log('socket ready')
this.writable = true
this.emit('connect')
return this
} catch (e) {
this.emit('error', e)
}
}
async _listen() {
// eslint-disable-next-line no-constant-condition
while (true) {
log('awaiting receive from CF socket')
const { done, value } = await this._cfReader!.read()
log('CF socket received:', done, value)
if (done) {
log('done')
break
}
this.emit('data', Buffer.from(value))
}
}
async _listenOnce() {
log('awaiting first receive from CF socket')
const { done, value } = await this._cfReader!.read()
log('First CF socket received:', done, value)
this.emit('data', Buffer.from(value))
}
write(
data: Uint8Array | string,
encoding: BufferEncoding = 'utf8',
callback: (...args: unknown[]) => void = () => {}
) {
if (data.length === 0) return callback()
if (typeof data === 'string') data = Buffer.from(data, encoding)
log('sending data direct:', data)
this._cfWriter!.write(data).then(
() => {
log('data sent')
callback()
},
(err) => {
log('send error', err)
callback(err)
}
)
return true
}
end(data = Buffer.alloc(0), encoding: BufferEncoding = 'utf8', callback: (...args: unknown[]) => void = () => {}) {
log('ending CF socket')
this.write(data, encoding, (err) => {
this._cfSocket!.close()
if (callback) callback(err)
})
return this
}
destroy(reason: string) {
log('destroying CF socket', reason)
this.destroyed = true
return this.end()
}
startTls(options: TlsOptions) {
if (this._upgraded) {
// Don't try to upgrade again.
this.emit('error', 'Cannot call `startTls()` more than once on a socket')
return
}
this._cfWriter!.releaseLock()
this._cfReader!.releaseLock()
this._upgrading = true
this._cfSocket = this._cfSocket!.startTls(options)
this._cfWriter = this._cfSocket.writable.getWriter()
this._cfReader = this._cfSocket.readable.getReader()
this._addClosedHandler()
this._listen().catch((e) => this.emit('error', e))
}
_addClosedHandler() {
this._cfSocket!.closed.then(() => {
if (!this._upgrading) {
log('CF socket closed')
this._cfSocket = null
this.emit('close')
} else {
this._upgrading = false
this._upgraded = true
}
}).catch((e) => this.emit('error', e))
}
}
const debug = false
function dump(data: unknown) {
if (data instanceof Uint8Array || data instanceof ArrayBuffer) {
// workaround https://github.com/microsoft/TypeScript/issues/63447
const buf = data instanceof Uint8Array ? Buffer.from(data) : Buffer.from(data)
const hex = buf.toString('hex')
const str = new TextDecoder().decode(data)
return `\n>>> STR: "${str.replace(/\n/g, '\\n')}"\n>>> HEX: ${hex}\n`
} else {
return data
}
}
function log(...args: unknown[]) {
debug && console.log(...args.map(dump))
}

View File

@@ -0,0 +1,151 @@
/**
* @fileoverview Rule to enforce placing object properties on separate lines.
* @author Vitor Balocco
* @deprecated in ESLint v8.53.0
*/
"use strict";
//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------
/** @type {import('../types').Rule.RuleModule} */
module.exports = {
meta: {
deprecated: {
message: "Formatting rules are being moved out of ESLint core.",
url: "https://eslint.org/blog/2023/10/deprecating-formatting-rules/",
deprecatedSince: "8.53.0",
availableUntil: "11.0.0",
replacedBy: [
{
message:
"ESLint Stylistic now maintains deprecated stylistic core rules.",
url: "https://eslint.style/guide/migration",
plugin: {
name: "@stylistic/eslint-plugin",
url: "https://eslint.style",
},
rule: {
name: "object-property-newline",
url: "https://eslint.style/rules/object-property-newline",
},
},
],
},
type: "layout",
docs: {
description: "Enforce placing object properties on separate lines",
recommended: false,
url: "https://eslint.org/docs/latest/rules/object-property-newline",
},
schema: [
{
type: "object",
properties: {
allowAllPropertiesOnSameLine: {
type: "boolean",
default: false,
},
allowMultiplePropertiesPerLine: {
// Deprecated
type: "boolean",
default: false,
},
},
additionalProperties: false,
},
],
fixable: "whitespace",
messages: {
propertiesOnNewlineAll:
"Object properties must go on a new line if they aren't all on the same line.",
propertiesOnNewline: "Object properties must go on a new line.",
},
},
create(context) {
const allowSameLine =
context.options[0] &&
(context.options[0].allowAllPropertiesOnSameLine ||
context.options[0]
.allowMultiplePropertiesPerLine); /* Deprecated */
const messageId = allowSameLine
? "propertiesOnNewlineAll"
: "propertiesOnNewline";
const sourceCode = context.sourceCode;
return {
ObjectExpression(node) {
if (allowSameLine) {
if (node.properties.length > 1) {
const firstTokenOfFirstProperty =
sourceCode.getFirstToken(node.properties[0]);
const lastTokenOfLastProperty = sourceCode.getLastToken(
node.properties.at(-1),
);
if (
firstTokenOfFirstProperty.loc.end.line ===
lastTokenOfLastProperty.loc.start.line
) {
// All keys and values are on the same line
return;
}
}
}
for (let i = 1; i < node.properties.length; i++) {
const lastTokenOfPreviousProperty = sourceCode.getLastToken(
node.properties[i - 1],
);
const firstTokenOfCurrentProperty =
sourceCode.getFirstToken(node.properties[i]);
if (
lastTokenOfPreviousProperty.loc.end.line ===
firstTokenOfCurrentProperty.loc.start.line
) {
context.report({
node,
loc: firstTokenOfCurrentProperty.loc,
messageId,
fix(fixer) {
const comma = sourceCode.getTokenBefore(
firstTokenOfCurrentProperty,
);
const rangeAfterComma = [
comma.range[1],
firstTokenOfCurrentProperty.range[0],
];
// Don't perform a fix if there are any comments between the comma and the next property.
if (
sourceCode.text
.slice(
rangeAfterComma[0],
rangeAfterComma[1],
)
.trim()
) {
return null;
}
return fixer.replaceTextRange(
rangeAfterComma,
"\n",
);
},
});
}
}
},
};
},
};