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,35 @@
{
"keys-while": {
"name": "keys-while",
"browser": "Mobile Safari 9.0.0 (iOS 9.2.0)",
"suite": "iter",
"hz": 22809.567212345646,
"success": true,
"fastest": false,
"rme": 0.027252985712392003,
"rhz": 0.974024526377425,
"sampleSize": 160
},
"keys-for": {
"name": "keys-for",
"browser": "Mobile Safari 9.0.0 (iOS 9.2.0)",
"suite": "iter",
"hz": 23417.857142857163,
"success": true,
"fastest": true,
"rme": 0.019752086707305883,
"rhz": 1,
"sampleSize": 166
},
"incr-for": {
"name": "incr-for",
"browser": "Mobile Safari 9.0.0 (iOS 9.2.0)",
"suite": "iter",
"hz": 13528.47751268248,
"success": true,
"fastest": false,
"rme": 0.022810499348243016,
"rhz": 0.5776992074959725,
"sampleSize": 170
}
}

View File

@@ -0,0 +1,11 @@
import type { JSDocComment, JSDocTag } from "./ast.generated.ts";
import { type Node, type NodeArray, SyntaxKind } from "./ast.ts";
/** Get all JSDoc tags related to a node, including those on parent nodes. */
export declare function getJSDocTags(node: Node): readonly JSDocTag[];
/** Gets all JSDoc tags that match a specified predicate */
export declare function getAllJSDocTags<T extends JSDocTag>(node: Node, predicate: (tag: JSDocTag) => tag is T): readonly T[];
/** Gets all JSDoc tags of a specified kind */
export declare function getAllJSDocTagsOfKind(node: Node, kind: SyntaxKind): readonly JSDocTag[];
/** Gets the text of a jsdoc comment, flattening links to their text. */
export declare function getTextOfJSDocComment(comment?: string | NodeArray<JSDocComment>): string | undefined;
//# sourceMappingURL=jsdoc.d.ts.map

View File

@@ -0,0 +1,13 @@
export * as core from "../core/index.cjs";
export * from "./parse.cjs";
export * from "./schemas.cjs";
export * from "./checks.cjs";
export type { infer, output, input } from "../core/index.cjs";
export type { JSONType } from "../core/util.cjs";
export { globalRegistry, registry, config, $output, $input, $brand, clone, regexes, treeifyError, prettifyError, formatError, flattenError, TimePrecision, util, NEVER, } from "../core/index.cjs";
export { toJSONSchema } from "../core/json-schema-processors.cjs";
export * as locales from "../locales/index.cjs";
/** A special constant with type `never` */
export * as iso from "./iso.cjs";
export { ZodMiniISODateTime, ZodMiniISODate, ZodMiniISOTime, ZodMiniISODuration, } from "./iso.cjs";
export * as coerce from "./coerce.cjs";

View File

@@ -0,0 +1,4 @@
{
"main": "../../cjs/_class_extract_field_descriptor.cjs",
"module": "../../esm/_class_extract_field_descriptor.js"
}

View File

@@ -0,0 +1,24 @@
{
"name": "pg-int8",
"version": "1.0.1",
"description": "64-bit big-endian signed integer-to-string conversion",
"bugs": "https://github.com/charmander/pg-int8/issues",
"license": "ISC",
"files": [
"index.js"
],
"repository": {
"type": "git",
"url": "https://github.com/charmander/pg-int8"
},
"scripts": {
"test": "tap test"
},
"devDependencies": {
"@charmander/eslint-config-base": "1.0.2",
"tap": "10.7.3"
},
"engines": {
"node": ">=4.0.0"
}
}

View File

@@ -0,0 +1,21 @@
import { expect, expectTypeOf, test } from "vitest";
import * as z from "zod/v4";
const schema = z.nan();
test("passing validations", () => {
schema.parse(Number.NaN);
schema.parse(Number("Not a number"));
expectTypeOf<typeof schema._output>().toEqualTypeOf<number>();
});
test("failing validations", () => {
expect(() => schema.parse(5)).toThrow();
expect(() => schema.parse("John")).toThrow();
expect(() => schema.parse(true)).toThrow();
expect(() => schema.parse(null)).toThrow();
expect(() => schema.parse(undefined)).toThrow();
expect(() => schema.parse({})).toThrow();
expect(() => schema.parse([])).toThrow();
});

View File

@@ -0,0 +1,113 @@
import * as util from "../core/util.js";
const error = () => {
const Sizable = {
string: { unit: "characters", verb: "to have" },
file: { unit: "bytes", verb: "to have" },
array: { unit: "items", verb: "to have" },
set: { unit: "items", verb: "to have" },
map: { unit: "entries", verb: "to have" },
};
function getSizing(origin) {
return Sizable[origin] ?? null;
}
const FormatDictionary = {
regex: "input",
email: "email address",
url: "URL",
emoji: "emoji",
uuid: "UUID",
uuidv4: "UUIDv4",
uuidv6: "UUIDv6",
nanoid: "nanoid",
guid: "GUID",
cuid: "cuid",
cuid2: "cuid2",
ulid: "ULID",
xid: "XID",
ksuid: "KSUID",
datetime: "ISO datetime",
date: "ISO date",
time: "ISO time",
duration: "ISO duration",
ipv4: "IPv4 address",
ipv6: "IPv6 address",
mac: "MAC address",
cidrv4: "IPv4 range",
cidrv6: "IPv6 range",
base64: "base64-encoded string",
base64url: "base64url-encoded string",
json_string: "JSON string",
e164: "E.164 number",
jwt: "JWT",
template_literal: "input",
};
// type names: missing keys = do not translate (use raw value via ?? fallback)
const TypeDictionary = {
// Compatibility: "nan" -> "NaN" for display
nan: "NaN",
// All other type names omitted - they fall back to raw values via ?? operator
};
return (issue) => {
switch (issue.code) {
case "invalid_type": {
const expected = TypeDictionary[issue.expected] ?? issue.expected;
const receivedType = util.parsedType(issue.input);
const received = TypeDictionary[receivedType] ?? receivedType;
return `Invalid input: expected ${expected}, received ${received}`;
}
case "invalid_value":
if (issue.values.length === 1)
return `Invalid input: expected ${util.stringifyPrimitive(issue.values[0])}`;
return `Invalid option: expected one of ${util.joinValues(issue.values, "|")}`;
case "too_big": {
const adj = issue.inclusive ? "<=" : "<";
const sizing = getSizing(issue.origin);
if (sizing)
return `Too big: expected ${issue.origin ?? "value"} to have ${adj}${issue.maximum.toString()} ${sizing.unit ?? "elements"}`;
return `Too big: expected ${issue.origin ?? "value"} to be ${adj}${issue.maximum.toString()}`;
}
case "too_small": {
const adj = issue.inclusive ? ">=" : ">";
const sizing = getSizing(issue.origin);
if (sizing) {
return `Too small: expected ${issue.origin} to have ${adj}${issue.minimum.toString()} ${sizing.unit}`;
}
return `Too small: expected ${issue.origin} to be ${adj}${issue.minimum.toString()}`;
}
case "invalid_format": {
const _issue = issue;
if (_issue.format === "starts_with") {
return `Invalid string: must start with "${_issue.prefix}"`;
}
if (_issue.format === "ends_with")
return `Invalid string: must end with "${_issue.suffix}"`;
if (_issue.format === "includes")
return `Invalid string: must include "${_issue.includes}"`;
if (_issue.format === "regex")
return `Invalid string: must match pattern ${_issue.pattern}`;
return `Invalid ${FormatDictionary[_issue.format] ?? issue.format}`;
}
case "not_multiple_of":
return `Invalid number: must be a multiple of ${issue.divisor}`;
case "unrecognized_keys":
return `Unrecognized key${issue.keys.length > 1 ? "s" : ""}: ${util.joinValues(issue.keys, ", ")}`;
case "invalid_key":
return `Invalid key in ${issue.origin}`;
case "invalid_union":
if (issue.options && Array.isArray(issue.options) && issue.options.length > 0) {
const opts = issue.options.map((o) => `'${o}'`).join(" | ");
return `Invalid discriminator value. Expected ${opts}`;
}
return "Invalid input";
case "invalid_element":
return `Invalid value in ${issue.origin}`;
default:
return `Invalid input`;
}
};
};
export default function () {
return {
localeError: error(),
};
}

View File

@@ -0,0 +1 @@
{"version":3,"file":"refinements.d.ts","sourceRoot":"","sources":["../../src/structs/refinements.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,cAAc,CAAA;AAG9C;;GAEG;AAEH,wBAAgB,KAAK,CACnB,CAAC,SAAS,MAAM,GAAG,GAAG,EAAE,GAAG,GAAG,CAAC,GAAG,EAAE,GAAG,CAAC,GAAG,GAAG,CAAC,GAAG,CAAC,EACnD,CAAC,SAAS,GAAG,EACb,MAAM,EAAE,MAAM,CAAC,CAAC,EAAE,CAAC,CAAC,GAAG,MAAM,CAAC,CAAC,EAAE,CAAC,CAAC,CAQpC;AAUD;;GAEG;AAEH,wBAAgB,GAAG,CAAC,CAAC,SAAS,MAAM,GAAG,IAAI,EAAE,CAAC,SAAS,GAAG,EACxD,MAAM,EAAE,MAAM,CAAC,CAAC,EAAE,CAAC,CAAC,EACpB,SAAS,EAAE,CAAC,EACZ,OAAO,GAAE;IACP,SAAS,CAAC,EAAE,OAAO,CAAA;CACf,GACL,MAAM,CAAC,CAAC,EAAE,CAAC,CAAC,CAUd;AAED;;GAEG;AAEH,wBAAgB,GAAG,CAAC,CAAC,SAAS,MAAM,GAAG,IAAI,EAAE,CAAC,SAAS,GAAG,EACxD,MAAM,EAAE,MAAM,CAAC,CAAC,EAAE,CAAC,CAAC,EACpB,SAAS,EAAE,CAAC,EACZ,OAAO,GAAE;IACP,SAAS,CAAC,EAAE,OAAO,CAAA;CACf,GACL,MAAM,CAAC,CAAC,EAAE,CAAC,CAAC,CAUd;AAED;;GAEG;AAEH,wBAAgB,QAAQ,CACtB,CAAC,SAAS,MAAM,GAAG,GAAG,EAAE,GAAG,GAAG,CAAC,GAAG,EAAE,GAAG,CAAC,GAAG,GAAG,CAAC,GAAG,CAAC,EACnD,CAAC,SAAS,GAAG,EACb,MAAM,EAAE,MAAM,CAAC,CAAC,EAAE,CAAC,CAAC,GAAG,MAAM,CAAC,CAAC,EAAE,CAAC,CAAC,CAOpC;AAED;;GAEG;AAEH,wBAAgB,OAAO,CAAC,CAAC,SAAS,MAAM,EAAE,CAAC,SAAS,GAAG,EACrD,MAAM,EAAE,MAAM,CAAC,CAAC,EAAE,CAAC,CAAC,EACpB,MAAM,EAAE,MAAM,GACb,MAAM,CAAC,CAAC,EAAE,CAAC,CAAC,CAOd;AAED;;GAEG;AAEH,wBAAgB,IAAI,CAClB,CAAC,SAAS,MAAM,GAAG,MAAM,GAAG,IAAI,GAAG,GAAG,EAAE,GAAG,GAAG,CAAC,GAAG,EAAE,GAAG,CAAC,GAAG,GAAG,CAAC,GAAG,CAAC,EACnE,CAAC,SAAS,GAAG,EACb,MAAM,EAAE,MAAM,CAAC,CAAC,EAAE,CAAC,CAAC,EAAE,GAAG,EAAE,MAAM,EAAE,GAAG,GAAE,MAAY,GAAG,MAAM,CAAC,CAAC,EAAE,CAAC,CAAC,CAwBpE;AAED;;;;;;GAMG;AAEH,wBAAgB,MAAM,CAAC,CAAC,EAAE,CAAC,EACzB,MAAM,EAAE,MAAM,CAAC,CAAC,EAAE,CAAC,CAAC,EACpB,IAAI,EAAE,MAAM,EACZ,OAAO,EAAE,OAAO,CAAC,CAAC,CAAC,GAClB,MAAM,CAAC,CAAC,EAAE,CAAC,CAAC,CAad"}

View File

@@ -0,0 +1,13 @@
"use strict";
// THIS CODE WAS AUTOMATICALLY GENERATED
// DO NOT EDIT THIS CODE BY HAND
// RUN THE FOLLOWING COMMAND FROM THE WORKSPACE ROOT TO REGENERATE:
// npx nx generate-lib repo
Object.defineProperty(exports, "__esModule", { value: true });
exports.esnext_date = void 0;
const base_config_1 = require("./base-config");
const esnext_temporal_1 = require("./esnext.temporal");
exports.esnext_date = {
libs: [esnext_temporal_1.esnext_temporal],
variables: [['Date', base_config_1.TYPE]],
};

View File

@@ -0,0 +1,83 @@
// import type { StandardSchemaV1 } from "@standard-schema/spec";
// @ts-ignore TS6133
import { expect, test } from "vitest";
import * as z from "zod/v3";
import { util } from "../helpers/util.js";
import type { StandardSchemaV1 } from "../standard-schema.js";
test("assignability", () => {
const _s1: StandardSchemaV1 = z.string();
const _s2: StandardSchemaV1<string> = z.string();
const _s3: StandardSchemaV1<string, string> = z.string();
const _s4: StandardSchemaV1<unknown, string> = z.string();
[_s1, _s2, _s3, _s4];
});
test("type inference", () => {
const stringToNumber = z.string().transform((x) => x.length);
type input = StandardSchemaV1.InferInput<typeof stringToNumber>;
util.assertEqual<input, string>(true);
type output = StandardSchemaV1.InferOutput<typeof stringToNumber>;
util.assertEqual<output, number>(true);
});
test("valid parse", () => {
const schema = z.string();
const result = schema["~standard"].validate("hello");
if (result instanceof Promise) {
throw new Error("Expected sync result");
}
expect(result.issues).toEqual(undefined);
if (result.issues) {
throw new Error("Expected no issues");
} else {
expect(result.value).toEqual("hello");
}
});
test("invalid parse", () => {
const schema = z.string();
const result = schema["~standard"].validate(1234);
if (result instanceof Promise) {
throw new Error("Expected sync result");
}
expect(result.issues).toBeDefined();
if (!result.issues) {
throw new Error("Expected issues");
}
expect(result.issues.length).toEqual(1);
expect(result.issues[0].path).toEqual([]);
});
test("valid parse async", async () => {
const schema = z.string().refine(async () => true);
const _result = schema["~standard"].validate("hello");
if (_result instanceof Promise) {
const result = await _result;
expect(result.issues).toEqual(undefined);
if (result.issues) {
throw new Error("Expected no issues");
} else {
expect(result.value).toEqual("hello");
}
} else {
throw new Error("Expected async result");
}
});
test("invalid parse async", async () => {
const schema = z.string().refine(async () => false);
const _result = schema["~standard"].validate("hello");
if (_result instanceof Promise) {
const result = await _result;
expect(result.issues).toBeDefined();
if (!result.issues) {
throw new Error("Expected issues");
}
expect(result.issues.length).toEqual(1);
expect(result.issues[0].path).toEqual([]);
} else {
throw new Error("Expected async result");
}
});

View File

@@ -0,0 +1,87 @@
import { FixedSizeCodec, FixedSizeDecoder, FixedSizeEncoder } from '@solana/codecs-core';
import { NumberCodecConfig } from './common';
/**
* Returns an encoder for 64-bit floating-point numbers (`f64`).
*
* This encoder serializes `f64` values using 8 bytes.
* Floating-point values may lose precision when encoded.
*
* For more details, see {@link getF64Codec}.
*
* @param config - Optional configuration to specify endianness (little by default).
* @returns A `FixedSizeEncoder<number, 8>` for encoding `f64` values.
*
* @example
* Encoding an `f64` value.
* ```ts
* const encoder = getF64Encoder();
* const bytes = encoder.encode(-1.5); // 0x000000000000f8bf
* ```
*
* @see {@link getF64Codec}
*/
export declare const getF64Encoder: (config?: NumberCodecConfig) => FixedSizeEncoder<bigint | number, 8>;
/**
* Returns a decoder for 64-bit floating-point numbers (`f64`).
*
* This decoder deserializes `f64` values from 8 bytes.
* Some precision may be lost during decoding due to floating-point representation.
*
* For more details, see {@link getF64Codec}.
*
* @param config - Optional configuration to specify endianness (little by default).
* @returns A `FixedSizeDecoder<number, 8>` for decoding `f64` values.
*
* @example
* Decoding an `f64` value.
* ```ts
* const decoder = getF64Decoder();
* const value = decoder.decode(new Uint8Array([0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf8, 0xbf])); // -1.5
* ```
*
* @see {@link getF64Codec}
*/
export declare const getF64Decoder: (config?: NumberCodecConfig) => FixedSizeDecoder<number, 8>;
/**
* Returns a codec for encoding and decoding 64-bit floating-point numbers (`f64`).
*
* This codec serializes `f64` values using 8 bytes.
* Due to the IEEE 754 floating-point representation, some precision loss may occur.
*
* @param config - Optional configuration to specify endianness (little by default).
* @returns A `FixedSizeCodec<number, number, 8>` for encoding and decoding `f64` values.
*
* @example
* Encoding and decoding an `f64` value.
* ```ts
* const codec = getF64Codec();
* const bytes = codec.encode(-1.5); // 0x000000000000f8bf
* const value = codec.decode(bytes); // -1.5
* ```
*
* @example
* Using big-endian encoding.
* ```ts
* const codec = getF64Codec({ endian: Endian.Big });
* const bytes = codec.encode(-1.5); // 0xbff8000000000000
* ```
*
* @remarks
* `f64` values follow the IEEE 754 double-precision floating-point standard.
* Precision loss may still occur but is significantly lower than `f32`.
*
* - If you need smaller floating-point values, consider using {@link getF32Codec}.
* - If you need integer values, consider using {@link getI64Codec} or {@link getU64Codec}.
*
* Separate {@link getF64Encoder} and {@link getF64Decoder} functions are available.
*
* ```ts
* const bytes = getF64Encoder().encode(-1.5);
* const value = getF64Decoder().decode(bytes);
* ```
*
* @see {@link getF64Encoder}
* @see {@link getF64Decoder}
*/
export declare const getF64Codec: (config?: NumberCodecConfig) => FixedSizeCodec<bigint | number, number, 8>;
//# sourceMappingURL=f64.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;GAaG;AACH,MAAM,IAAI,KAAK,CAAC,6EAA6E,CAAC,CAAC"}

View File

@@ -0,0 +1,365 @@
/**
* @fileoverview disallow assignments that can lead to race conditions due to usage of `await` or `yield`
* @author Teddy Katz
* @author Toru Nagashima
*/
"use strict";
/**
* Make the map from identifiers to each reference.
* @param {escope.Scope} scope The scope to get references.
* @param {Map<Identifier, escope.Reference>} [outReferenceMap] The map from identifier nodes to each reference object.
* @returns {Map<Identifier, escope.Reference>} `referenceMap`.
*/
function createReferenceMap(scope, outReferenceMap = new Map()) {
for (const reference of scope.references) {
if (reference.resolved === null) {
continue;
}
outReferenceMap.set(reference.identifier, reference);
}
for (const childScope of scope.childScopes) {
if (childScope.type !== "function") {
createReferenceMap(childScope, outReferenceMap);
}
}
return outReferenceMap;
}
/**
* Get `reference.writeExpr` of a given reference.
* If it's the read reference of MemberExpression in LHS, returns RHS in order to address `a.b = await a`
* @param {escope.Reference} reference The reference to get.
* @returns {Expression|null} The `reference.writeExpr`.
*/
function getWriteExpr(reference) {
if (reference.writeExpr) {
return reference.writeExpr;
}
let node = reference.identifier;
while (node) {
const t = node.parent.type;
if (t === "AssignmentExpression" && node.parent.left === node) {
return node.parent.right;
}
if (t === "MemberExpression" && node.parent.object === node) {
node = node.parent;
continue;
}
break;
}
return null;
}
/**
* Checks if an expression is a variable that can only be observed within the given function.
* @param {Variable|null} variable The variable to check
* @param {boolean} isMemberAccess If `true` then this is a member access.
* @returns {boolean} `true` if the variable is local to the given function, and is never referenced in a closure.
*/
function isLocalVariableWithoutEscape(variable, isMemberAccess) {
if (!variable) {
return false; // A global variable which was not defined.
}
// If the reference is a property access and the variable is a parameter, it handles the variable is not local.
if (isMemberAccess && variable.defs.some(d => d.type === "Parameter")) {
return false;
}
const functionScope = variable.scope.variableScope;
return variable.references.every(
reference => reference.from.variableScope === functionScope,
);
}
/**
* Represents segment information.
*/
class SegmentInfo {
constructor() {
this.info = new WeakMap();
}
/**
* Initialize the segment information.
* @param {PathSegment} segment The segment to initialize.
* @returns {void}
*/
initialize(segment) {
const outdatedReadVariables = new Set();
const freshReadVariables = new Set();
for (const prevSegment of segment.prevSegments) {
const info = this.info.get(prevSegment);
if (info) {
info.outdatedReadVariables.forEach(
Set.prototype.add,
outdatedReadVariables,
);
info.freshReadVariables.forEach(
Set.prototype.add,
freshReadVariables,
);
}
}
this.info.set(segment, { outdatedReadVariables, freshReadVariables });
}
/**
* Mark a given variable as read on given segments.
* @param {PathSegment[]} segments The segments that it read the variable on.
* @param {Variable} variable The variable to be read.
* @returns {void}
*/
markAsRead(segments, variable) {
for (const segment of segments) {
const info = this.info.get(segment);
if (info) {
info.freshReadVariables.add(variable);
// If a variable is freshly read again, then it's no more out-dated.
info.outdatedReadVariables.delete(variable);
}
}
}
/**
* Move `freshReadVariables` to `outdatedReadVariables`.
* @param {PathSegment[]} segments The segments to process.
* @returns {void}
*/
makeOutdated(segments) {
for (const segment of segments) {
const info = this.info.get(segment);
if (info) {
info.freshReadVariables.forEach(
Set.prototype.add,
info.outdatedReadVariables,
);
info.freshReadVariables.clear();
}
}
}
/**
* Check if a given variable is outdated on the current segments.
* @param {PathSegment[]} segments The current segments.
* @param {Variable} variable The variable to check.
* @returns {boolean} `true` if the variable is outdated on the segments.
*/
isOutdated(segments, variable) {
for (const segment of segments) {
const info = this.info.get(segment);
if (info && info.outdatedReadVariables.has(variable)) {
return true;
}
}
return false;
}
}
//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------
/** @type {import('../types').Rule.RuleModule} */
module.exports = {
meta: {
type: "problem",
defaultOptions: [
{
allowProperties: false,
},
],
docs: {
description:
"Disallow assignments that can lead to race conditions due to usage of `await` or `yield`",
recommended: false,
url: "https://eslint.org/docs/latest/rules/require-atomic-updates",
},
fixable: null,
schema: [
{
type: "object",
properties: {
allowProperties: {
type: "boolean",
},
},
additionalProperties: false,
},
],
messages: {
nonAtomicUpdate:
"Possible race condition: `{{value}}` might be reassigned based on an outdated value of `{{value}}`.",
nonAtomicObjectUpdate:
"Possible race condition: `{{value}}` might be assigned based on an outdated state of `{{object}}`.",
},
},
create(context) {
const [{ allowProperties }] = context.options;
const sourceCode = context.sourceCode;
const assignmentReferences = new Map();
const segmentInfo = new SegmentInfo();
let stack = null;
return {
onCodePathStart(codePath, node) {
const scope = sourceCode.getScope(node);
const shouldVerify =
scope.type === "function" &&
(scope.block.async || scope.block.generator);
stack = {
upper: stack,
codePath,
referenceMap: shouldVerify
? createReferenceMap(scope)
: null,
currentSegments: new Set(),
};
},
onCodePathEnd() {
stack = stack.upper;
},
// Initialize the segment information.
onCodePathSegmentStart(segment) {
segmentInfo.initialize(segment);
stack.currentSegments.add(segment);
},
onUnreachableCodePathSegmentStart(segment) {
stack.currentSegments.add(segment);
},
onUnreachableCodePathSegmentEnd(segment) {
stack.currentSegments.delete(segment);
},
onCodePathSegmentEnd(segment) {
stack.currentSegments.delete(segment);
},
// Handle references to prepare verification.
Identifier(node) {
const { referenceMap } = stack;
const reference = referenceMap && referenceMap.get(node);
// Ignore if this is not a valid variable reference.
if (!reference) {
return;
}
const variable = reference.resolved;
const writeExpr = getWriteExpr(reference);
const isMemberAccess =
reference.identifier.parent.type === "MemberExpression";
// Add a fresh read variable.
if (
reference.isRead() &&
!(writeExpr && writeExpr.parent.operator === "=")
) {
segmentInfo.markAsRead(stack.currentSegments, variable);
}
/*
* Register the variable to verify after ESLint traversed the `writeExpr` node
* if this reference is an assignment to a variable which is referred from other closure.
*/
if (
writeExpr &&
writeExpr.parent.right === writeExpr && // ← exclude variable declarations.
!isLocalVariableWithoutEscape(variable, isMemberAccess)
) {
let refs = assignmentReferences.get(writeExpr);
if (!refs) {
refs = [];
assignmentReferences.set(writeExpr, refs);
}
refs.push(reference);
}
},
/*
* Verify assignments.
* If the reference exists in `outdatedReadVariables` list, report it.
*/
":expression:exit"(node) {
// referenceMap exists if this is in a resumable function scope.
if (!stack.referenceMap) {
return;
}
// Mark the read variables on this code path as outdated.
if (
node.type === "AwaitExpression" ||
node.type === "YieldExpression"
) {
segmentInfo.makeOutdated(stack.currentSegments);
}
// Verify.
const references = assignmentReferences.get(node);
if (references) {
assignmentReferences.delete(node);
for (const reference of references) {
const variable = reference.resolved;
if (
segmentInfo.isOutdated(
stack.currentSegments,
variable,
)
) {
if (node.parent.left === reference.identifier) {
context.report({
node: node.parent,
messageId: "nonAtomicUpdate",
data: {
value: variable.name,
},
});
} else if (!allowProperties) {
context.report({
node: node.parent,
messageId: "nonAtomicObjectUpdate",
data: {
value: sourceCode.getText(
node.parent.left,
),
object: variable.name,
},
});
}
}
}
}
},
};
},
};

View File

@@ -0,0 +1,11 @@
Copyright 2008 Fair Oaks Labs, Inc.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

View File

@@ -0,0 +1,41 @@
'use strict';
const {Transform} = require('stream');
const defaultInitial = 0;
const defaultReducer = (acc, value) => value;
class Scan extends Transform {
constructor(options) {
super(Object.assign({}, options, {writableObjectMode: true, readableObjectMode: true}));
this._accumulator = defaultInitial;
this._reducer = defaultReducer;
if (options) {
'initial' in options && (this._accumulator = options.initial);
'reducer' in options && (this._reducer = options.reducer);
}
}
_transform(chunk, encoding, callback) {
const result = this._reducer.call(this, this._accumulator, chunk);
if (result && typeof result.then == 'function') {
result.then(
value => {
this._accumulator = value;
this.push(this._accumulator);
callback(null);
},
error => callback(error)
);
} else {
this._accumulator = result;
this.push(this._accumulator);
callback(null);
}
}
static make(reducer, initial) {
return new Scan(typeof reducer == 'object' ? reducer : {reducer, initial});
}
}
Scan.make.Constructor = Scan;
module.exports = Scan.make;

View File

@@ -0,0 +1,5 @@
export type MessageIds = 'preferExpectErrorComment';
declare const _default: import("@typescript-eslint/utils/ts-eslint").RuleModule<"preferExpectErrorComment", [], import("../../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener> & {
name: string;
};
export default _default;

View File

@@ -0,0 +1,404 @@
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
var ownKeys = function(o) {
ownKeys = Object.getOwnPropertyNames || function (o) {
var ar = [];
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
return ar;
};
return ownKeys(o);
};
return function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
__setModuleDefault(result, mod);
return result;
};
})();
Object.defineProperty(exports, "__esModule", { value: true });
const utils_1 = require("@typescript-eslint/utils");
const tsutils = __importStar(require("ts-api-utils"));
const ts = __importStar(require("typescript"));
const util_1 = require("../util");
exports.default = (0, util_1.createRule)({
name: 'no-deprecated',
meta: {
type: 'problem',
docs: {
description: 'Disallow using code marked as `@deprecated`',
recommended: 'strict',
requiresTypeChecking: true,
},
messages: {
deprecated: `\`{{name}}\` is deprecated.`,
deprecatedWithReason: `\`{{name}}\` is deprecated. {{reason}}`,
},
schema: [
{
type: 'object',
additionalProperties: false,
properties: {
allow: {
...util_1.typeOrValueSpecifiersSchema,
description: 'Type specifiers that can be allowed.',
},
},
},
],
},
defaultOptions: [
{
allow: [],
},
],
create(context, [options]) {
const { jsDocParsingMode } = context.languageOptions.parserOptions;
const allow = options.allow;
if (jsDocParsingMode === 'none' || jsDocParsingMode === 'type-info') {
throw new Error(`Cannot be used with jsDocParsingMode: '${jsDocParsingMode}'.`);
}
const services = (0, util_1.getParserServices)(context);
const checker = services.program.getTypeChecker();
// Deprecated jsdoc tags can be added on some symbol alias, e.g.
//
// export { /** @deprecated */ foo }
//
// When we import foo, its symbol is an alias of the exported foo (the one
// with the deprecated tag), which is itself an alias of the original foo.
// Therefore, we carefully go through the chain of aliases and check each
// immediate alias for deprecated tags
function searchForDeprecationInAliasesChain(symbol, checkDeprecationsOfAliasedSymbol) {
if (!symbol || !tsutils.isSymbolFlagSet(symbol, ts.SymbolFlags.Alias)) {
return checkDeprecationsOfAliasedSymbol
? getJsDocDeprecation(symbol)
: undefined;
}
const targetSymbol = checker.getAliasedSymbol(symbol);
while (tsutils.isSymbolFlagSet(symbol, ts.SymbolFlags.Alias)) {
const reason = getJsDocDeprecation(symbol);
if (reason != null) {
return reason;
}
const immediateAliasedSymbol = symbol.getDeclarations() && checker.getImmediateAliasedSymbol(symbol);
if (!immediateAliasedSymbol) {
break;
}
symbol = immediateAliasedSymbol;
if (checkDeprecationsOfAliasedSymbol && symbol === targetSymbol) {
return getJsDocDeprecation(symbol);
}
}
return undefined;
}
function isDeclaration(node) {
const { parent } = node;
switch (parent.type) {
case utils_1.AST_NODE_TYPES.ArrayPattern:
return parent.elements.includes(node);
case utils_1.AST_NODE_TYPES.ClassExpression:
case utils_1.AST_NODE_TYPES.ClassDeclaration:
case utils_1.AST_NODE_TYPES.VariableDeclarator:
case utils_1.AST_NODE_TYPES.TSEnumMember:
return parent.id === node;
case utils_1.AST_NODE_TYPES.MethodDefinition:
case utils_1.AST_NODE_TYPES.PropertyDefinition:
case utils_1.AST_NODE_TYPES.AccessorProperty:
return parent.key === node;
case utils_1.AST_NODE_TYPES.Property:
// foo in "const { foo } = bar" will be processed twice, as parent.key
// and parent.value. The second is treated as a declaration.
if (parent.value === node) {
// const { foo: bar } = baz; -- bar IS a declaration.
// const baz = { foo: bar }; -- bar IS NOT a declaration.
return parent.parent.type === utils_1.AST_NODE_TYPES.ObjectPattern;
}
// const { foo: bar } = baz; -- foo IS NOT a declaration.
// const baz = { foo: bar }; -- foo IS a declaration.
return parent.parent.type === utils_1.AST_NODE_TYPES.ObjectExpression;
case utils_1.AST_NODE_TYPES.AssignmentPattern:
// foo in "const { foo = "" } = bar" will be processed twice, as parent.parent.key
// and parent.left. The second is treated as a declaration.
return parent.left === node;
case utils_1.AST_NODE_TYPES.ArrowFunctionExpression:
case utils_1.AST_NODE_TYPES.FunctionDeclaration:
case utils_1.AST_NODE_TYPES.FunctionExpression:
case utils_1.AST_NODE_TYPES.TSDeclareFunction:
case utils_1.AST_NODE_TYPES.TSEmptyBodyFunctionExpression:
case utils_1.AST_NODE_TYPES.TSEnumDeclaration:
case utils_1.AST_NODE_TYPES.TSInterfaceDeclaration:
case utils_1.AST_NODE_TYPES.TSMethodSignature:
case utils_1.AST_NODE_TYPES.TSModuleDeclaration:
case utils_1.AST_NODE_TYPES.TSParameterProperty:
case utils_1.AST_NODE_TYPES.TSPropertySignature:
case utils_1.AST_NODE_TYPES.TSTypeAliasDeclaration:
case utils_1.AST_NODE_TYPES.TSTypeParameter:
return true;
// treat `export import Bar = Foo;` (and `import Foo = require('...')`) as declarations
case utils_1.AST_NODE_TYPES.TSImportEqualsDeclaration:
return parent.id === node;
default:
return false;
}
}
function isInsideImport(node) {
let current = node;
while (true) {
switch (current.type) {
case utils_1.AST_NODE_TYPES.ImportDeclaration:
return true;
case utils_1.AST_NODE_TYPES.ArrowFunctionExpression:
case utils_1.AST_NODE_TYPES.ExportAllDeclaration:
case utils_1.AST_NODE_TYPES.ExportNamedDeclaration:
case utils_1.AST_NODE_TYPES.BlockStatement:
case utils_1.AST_NODE_TYPES.ClassDeclaration:
case utils_1.AST_NODE_TYPES.TSInterfaceDeclaration:
case utils_1.AST_NODE_TYPES.FunctionDeclaration:
case utils_1.AST_NODE_TYPES.FunctionExpression:
case utils_1.AST_NODE_TYPES.Program:
case utils_1.AST_NODE_TYPES.TSUnionType:
case utils_1.AST_NODE_TYPES.VariableDeclarator:
return false;
default:
current = current.parent;
}
}
}
function getJsDocDeprecation(symbol) {
let jsDocTags;
try {
jsDocTags = symbol?.getJsDocTags(checker);
}
catch {
// workaround for https://github.com/microsoft/TypeScript/issues/60024
return;
}
const tag = jsDocTags?.find(tag => tag.name === 'deprecated');
if (!tag) {
return undefined;
}
const displayParts = tag.text;
return displayParts ? ts.displayPartsToString(displayParts) : '';
}
function isNodeCalleeOfParent(node) {
switch (node.parent?.type) {
case utils_1.AST_NODE_TYPES.NewExpression:
case utils_1.AST_NODE_TYPES.CallExpression:
return node.parent.callee === node;
case utils_1.AST_NODE_TYPES.TaggedTemplateExpression:
return node.parent.tag === node;
case utils_1.AST_NODE_TYPES.JSXOpeningElement:
return node.parent.name === node;
default:
return false;
}
}
function getCallLikeNode(node) {
let callee = node;
while (callee.parent?.type === utils_1.AST_NODE_TYPES.MemberExpression &&
callee.parent.property === callee) {
callee = callee.parent;
}
return isNodeCalleeOfParent(callee) ? callee : undefined;
}
function getCallLikeDeprecation(node) {
const tsNode = services.esTreeNodeToTSNodeMap.get(node.parent);
// If the node is a direct function call, we look for its signature.
const signature = (0, util_1.nullThrows)(checker.getResolvedSignature(tsNode), 'Expected call like node to have signature');
const symbol = services.getSymbolAtLocation(node);
const aliasedSymbol = symbol != null && tsutils.isSymbolFlagSet(symbol, ts.SymbolFlags.Alias)
? checker.getAliasedSymbol(symbol)
: symbol;
const symbolDeclarationKind = aliasedSymbol?.declarations?.[0].kind;
// Properties with function-like types have "deprecated" jsdoc
// on their symbols, not on their signatures:
//
// interface Props {
// /** @deprecated */
// property: () => 'foo'
// ^symbol^ ^signature^
// }
if (symbolDeclarationKind !== ts.SyntaxKind.MethodDeclaration &&
symbolDeclarationKind !== ts.SyntaxKind.FunctionDeclaration &&
symbolDeclarationKind !== ts.SyntaxKind.MethodSignature) {
return (searchForDeprecationInAliasesChain(symbol, true) ??
getJsDocDeprecation(signature) ??
getJsDocDeprecation(aliasedSymbol));
}
return (searchForDeprecationInAliasesChain(symbol,
// Here we're working with a function declaration or method.
// Both can have 1 or more overloads, each overload creates one
// ts.Declaration which is placed in symbol.declarations.
//
// Imagine the following code:
//
// function foo(): void
// /** @deprecated Some Reason */
// function foo(arg: string): void
// function foo(arg?: string): void {}
//
// foo() // <- foo is our symbol
//
// If we call getJsDocDeprecation(checker.getAliasedSymbol(symbol)),
// we get 'Some Reason', but after all, we are calling foo with
// a signature that is not deprecated!
// It works this way because symbol.getJsDocTags returns tags from
// all symbol declarations combined into one array. And AFAIK there is
// no publicly exported TS function that can tell us if a particular
// declaration is deprecated or not.
//
// So, in case of function and method declarations, we don't check original
// aliased symbol, but rely on the getJsDocDeprecation(signature) call below.
false) ?? getJsDocDeprecation(signature));
}
function getJSXAttributeDeprecation(openingElement, propertyName) {
const contextualType = (0, util_1.nullThrows)(services.getContextualType(openingElement.name), 'Expected JSX opening element name to have contextualType');
const symbol = contextualType.getProperty(propertyName);
return getJsDocDeprecation(symbol);
}
function getDeprecationReason(node) {
const callLikeNode = getCallLikeNode(node);
if (callLikeNode) {
return getCallLikeDeprecation(callLikeNode);
}
if (node.parent.type === utils_1.AST_NODE_TYPES.JSXAttribute &&
node.type !== utils_1.AST_NODE_TYPES.Super) {
return getJSXAttributeDeprecation(node.parent.parent, node.name);
}
if (node.parent.type === utils_1.AST_NODE_TYPES.Property &&
node.type !== utils_1.AST_NODE_TYPES.Super) {
const property = services
.getTypeAtLocation(node.parent.parent)
.getProperty(node.name);
const propertySymbol = services.getSymbolAtLocation(node);
const valueSymbol = checker.getShorthandAssignmentValueSymbol(propertySymbol?.valueDeclaration);
return (searchForDeprecationInAliasesChain(propertySymbol, true) ??
getJsDocDeprecation(property) ??
getJsDocDeprecation(propertySymbol) ??
getJsDocDeprecation(valueSymbol));
}
return searchForDeprecationInAliasesChain(services.getSymbolAtLocation(node), true);
}
function checkIdentifier(node) {
if (isDeclaration(node) || isInsideImport(node)) {
return;
}
const reason = getDeprecationReason(node);
if (reason == null) {
return;
}
const type = services.getTypeAtLocation(node);
if ((0, util_1.typeMatchesSomeSpecifier)(type, allow, services.program) ||
(0, util_1.valueMatchesSomeSpecifier)(node, allow, services.program, type)) {
return;
}
const name = getReportedNodeName(node);
context.report({
...(reason
? {
messageId: 'deprecatedWithReason',
data: { name, reason },
}
: {
messageId: 'deprecated',
data: { name },
}),
node,
});
}
function checkMemberExpression(node) {
if (!node.computed) {
return;
}
const propertyType = services.getTypeAtLocation(node.property);
if (propertyType.isLiteral()) {
const objectType = services.getTypeAtLocation(node.object);
const propertyName = propertyType.isStringLiteral()
? propertyType.value
: // eslint-disable-next-line @typescript-eslint/no-base-to-string
String(propertyType.value);
const property = objectType.getProperty(propertyName);
const reason = getJsDocDeprecation(property);
if (reason == null) {
return;
}
if ((0, util_1.typeMatchesSomeSpecifier)(objectType, allow, services.program)) {
return;
}
context.report({
...(reason
? {
messageId: 'deprecatedWithReason',
data: { name: propertyName, reason },
}
: {
messageId: 'deprecated',
data: { name: propertyName },
}),
node: node.property,
});
}
}
return {
Identifier(node) {
const { parent } = node;
if (parent.type === utils_1.AST_NODE_TYPES.ExportNamedDeclaration ||
parent.type === utils_1.AST_NODE_TYPES.ExportAllDeclaration) {
return;
}
// Computed identifier expressions are handled by checkMemberExpression
if (parent.type === utils_1.AST_NODE_TYPES.MemberExpression &&
parent.computed &&
parent.property === node) {
return;
}
if (parent.type === utils_1.AST_NODE_TYPES.ExportSpecifier) {
// only deal with the alias (exported) side, not the local binding
if (parent.exported !== node) {
return;
}
const symbol = services.getSymbolAtLocation(node);
const aliasDeprecation = getJsDocDeprecation(symbol);
if (aliasDeprecation != null) {
return;
}
}
// whether it's a plain identifier or the exported alias
checkIdentifier(node);
},
JSXIdentifier(node) {
if (node.parent.type !== utils_1.AST_NODE_TYPES.JSXClosingElement) {
checkIdentifier(node);
}
},
MemberExpression: checkMemberExpression,
PrivateIdentifier: checkIdentifier,
Super: checkIdentifier,
};
},
});
function getReportedNodeName(node) {
if (node.type === utils_1.AST_NODE_TYPES.Super) {
return 'super';
}
if (node.type === utils_1.AST_NODE_TYPES.PrivateIdentifier) {
return `#${node.name}`;
}
return node.name;
}

View File

@@ -0,0 +1,18 @@
[
{
"name": "html",
"description": "Outputs results to HTML. The `html` formatter is useful for visual presentation in the browser."
},
{
"name": "json-with-metadata",
"description": "Outputs JSON-serialized results. The `json-with-metadata` provides the same linting results as the [`json`](#json) formatter with additional metadata about the rules applied. The linting results are included in the `results` property and the rules metadata is included in the `metadata` property.\n\nAlternatively, you can use the [ESLint Node.js API](../../integrate/nodejs-api) to programmatically use ESLint."
},
{
"name": "json",
"description": "Outputs JSON-serialized results. The `json` formatter is useful when you want to programmatically work with the CLI's linting results.\n\nAlternatively, you can use the [ESLint Node.js API](../../integrate/nodejs-api) to programmatically use ESLint."
},
{
"name": "stylish",
"description": "Human-readable output format. This is the default formatter."
}
]

View File

@@ -0,0 +1,20 @@
Copyright (c) 2009 cloudhead
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

View File

@@ -0,0 +1,172 @@
/**
* Represents the name of an AI coding agent.
*/
type AgentName = (string & {}) | "cursor" | "claude" | "devin" | "replit" | "gemini" | "codex" | "auggie" | "opencode" | "kiro" | "goose" | "pi" | "junie";
/**
* Provides information about an AI coding agent.
*/
type AgentInfo = {
/**
* The name of the AI coding agent. See {@link AgentName} for possible values.
*/
name?: AgentName;
};
/**
* Detects the current AI coding agent from environment variables.
*
* Supported agents: `cursor`, `claude`, `devin`, `replit`, `gemini`, `codex`, `auggie`, `opencode`, `kiro`, `goose`, `pi`, `junie`
*
* You can also set the `AI_AGENT` environment variable to explicitly specify the agent name.
*/
declare function detectAgent(): AgentInfo;
/**
* The detected agent information for the current execution context.
* This value is evaluated once at module initialisation.
*/
declare const agentInfo: AgentInfo;
/**
* Name of the detected agent.
*/
declare const agent: AgentName | undefined;
/**
* A boolean flag indicating whether the current environment is running inside an AI coding agent.
*/
declare const isAgent: boolean;
/**
* Runtime-agnostic reference to environment variables.
*
* Resolves to `globalThis.process.env` when available, otherwise an empty object.
*/
declare const env: Record<string, string | undefined>;
/**
* Runtime-agnostic reference to the `process` global.
*
* Resolves to `globalThis.process` when available, otherwise a minimal shim containing only `env`.
*/
declare const process: Partial<typeof globalThis.process>;
/**
* Current value of the `NODE_ENV` environment variable (or static value if replaced during build).
*
* If `NODE_ENV` is not set, this will be undefined.
*/
declare const nodeENV: string | undefined;
/** Value of process.platform */
declare const platform: string;
/** Detect if `CI` environment variable is set or a provider CI detected */
declare const isCI: boolean;
/** Detect if stdout.TTY is available */
declare const hasTTY: boolean;
/** Detect if global `window` object is available */
declare const hasWindow: boolean;
/** Detect if `DEBUG` environment variable is set */
declare const isDebug: boolean;
/** Detect if `NODE_ENV` environment variable is `test` or `TEST` environment variable is set */
declare const isTest: boolean;
/** Detect if `NODE_ENV` or `MODE` environment variable is `production` */
declare const isProduction: boolean;
/** Detect if `NODE_ENV` environment variable is `dev` or `development`, or if `MODE` environment variable is `development` */
declare const isDevelopment: boolean;
/** Detect if MINIMAL environment variable is set, running in CI or test or TTY is unavailable */
declare const isMinimal: boolean;
/** Detect if process.platform is Windows */
declare const isWindows: boolean;
/** Detect if process.platform is Linux */
declare const isLinux: boolean;
/** Detect if process.platform is macOS (darwin kernel) */
declare const isMacOS: boolean;
/** Detect if terminal color output is supported based on `NO_COLOR`, `FORCE_COLOR`, TTY, and CI environment */
declare const isColorSupported: boolean;
/** Node.js version string (e.g. `"20.11.0"`), or `null` if not running in Node.js */
declare const nodeVersion: string | null;
/** Node.js major version number (e.g. `20`), or `null` if not running in Node.js */
declare const nodeMajorVersion: number | null;
/**
* Represents the name of a CI/CD or Deployment provider.
*/
type ProviderName = (string & {}) | "appveyor" | "aws_amplify" | "azure_pipelines" | "azure_static" | "appcircle" | "bamboo" | "bitbucket" | "bitrise" | "buddy" | "buildkite" | "circle" | "cirrus" | "cloudflare_pages" | "cloudflare_workers" | "google_cloudrun" | "google_cloudrun_job" | "codebuild" | "codefresh" | "drone" | "drone" | "dsari" | "github_actions" | "gitlab" | "gocd" | "layerci" | "hudson" | "jenkins" | "magnum" | "netlify" | "nevercode" | "render" | "sail" | "semaphore" | "screwdriver" | "shippable" | "solano" | "strider" | "teamcity" | "travis" | "vercel" | "appcenter" | "codesandbox" | "stackblitz" | "stormkit" | "cleavr" | "zeabur" | "codesphere" | "railway" | "deno-deploy" | "firebase_app_hosting" | "edgeone_pages";
/**
* Provides information about a CI/CD or Deployment provider, including its name and possibly other metadata.
*/
type ProviderInfo = {
/**
* The name of the CI/CD or Deployment provider. See {@link ProviderName} for possible values.
*/
name: ProviderName;
/**
* If is set to `true`, the environment is recognised as a CI/CD provider.
*/
ci?: boolean;
/**
* Arbitrary metadata associated with the provider.
*/
[meta: string]: any;
};
/**
* Detects the current CI/CD or Deployment provider from environment variables.
*/
declare function detectProvider(): ProviderInfo;
/**
* The detected provider information for the current execution context.
* This value is evaluated once at module initialisation.
*/
declare const providerInfo: ProviderInfo;
/**
* Name of the detected provider, defaults to an empty string if no provider is detected.
*/
declare const provider: ProviderName;
/**
* Represents the name of a JavaScript runtime.
*
* @see https://runtime-keys.proposal.wintercg.org/
*/
type RuntimeName = (string & {}) | "workerd" | "deno" | "netlify" | "node" | "bun" | "edge-light" | "fastly";
type RuntimeInfo = {
/**
* The name of the detected runtime.
*/
name: RuntimeName;
};
/**
* Indicates if running in Node.js or a Node.js compatible runtime.
*
* **Note:** When running code in Bun and Deno with Node.js compatibility mode, `isNode` flag will be also `true`, indicating running in a Node.js compatible runtime.
*
* Use `runtime === "node"` if you need strict check for Node.js runtime.
*/
declare const isNode: boolean;
/**
* Indicates if running in Bun runtime.
*/
declare const isBun: boolean;
/**
* Indicates if running in Deno runtime.
*/
declare const isDeno: boolean;
/**
* Indicates if running in Fastly runtime.
*/
declare const isFastly: boolean;
/**
* Indicates if running in Netlify runtime.
*/
declare const isNetlify: boolean;
/**
* Indicates if running in EdgeLight (Vercel Edge) runtime.
*/
declare const isEdgeLight: boolean;
/**
* Indicates if running in Cloudflare Workers runtime.
*
* https://developers.cloudflare.com/workers/runtime-apis/web-standards/#navigatoruseragent
*/
declare const isWorkerd: boolean;
/**
* Contains information about the detected runtime, if any.
*/
declare const runtimeInfo: RuntimeInfo | undefined;
/**
* A convenience constant that returns the name of the detected runtime,
* defaults to an empty string if no runtime is detected.
*/
declare const runtime: RuntimeName;
export { type AgentInfo, type AgentName, type ProviderInfo, type ProviderName, type RuntimeInfo, type RuntimeName, agent, agentInfo, detectAgent, detectProvider, env, hasTTY, hasWindow, isAgent, isBun, isCI, isColorSupported, isDebug, isDeno, isDevelopment, isEdgeLight, isFastly, isLinux, isMacOS, isMinimal, isNetlify, isNode, isProduction, isTest, isWindows, isWorkerd, nodeENV, nodeMajorVersion, nodeVersion, platform, process, provider, providerInfo, runtime, runtimeInfo };

View File

@@ -0,0 +1,70 @@
import { expect, test } from "vitest";
import * as z from "zod/v3";
const crazySchema = z.object({
tuple: z.tuple([
z.string().nullable().optional(),
z.number().nullable().optional(),
z.boolean().nullable().optional(),
z.null().nullable().optional(),
z.undefined().nullable().optional(),
z.literal("1234").nullable().optional(),
]),
merged: z
.object({
k1: z.string().optional(),
})
.merge(z.object({ k1: z.string().nullable(), k2: z.number() })),
union: z.array(z.union([z.literal("asdf"), z.literal(12)])).nonempty(),
array: z.array(z.number()),
// sumTransformer: z.transformer(z.array(z.number()), z.number(), (arg) => {
// return arg.reduce((a, b) => a + b, 0);
// }),
sumMinLength: z.array(z.number()).refine((arg) => arg.length > 5),
intersection: z.intersection(z.object({ p1: z.string().optional() }), z.object({ p1: z.number().optional() })),
enum: z.intersection(z.enum(["zero", "one"]), z.enum(["one", "two"])),
nonstrict: z.object({ points: z.number() }).nonstrict(),
numProm: z.promise(z.number()),
lenfun: z.function(z.tuple([z.string()]), z.boolean()),
});
// const asyncCrazySchema = crazySchema.extend({
// // async_transform: z.transformer(
// // z.array(z.number()),
// // z.number(),
// // async (arg) => {
// // return arg.reduce((a, b) => a + b, 0);
// // }
// // ),
// async_refine: z.array(z.number()).refine(async (arg) => arg.length > 5),
// });
test("parse", () => {
const input = {
tuple: ["asdf", 1234, true, null, undefined, "1234"],
merged: { k1: "asdf", k2: 12 },
union: ["asdf", 12, "asdf", 12, "asdf", 12],
array: [12, 15, 16],
// sumTransformer: [12, 15, 16],
sumMinLength: [12, 15, 16, 98, 24, 63],
intersection: {},
enum: "one",
nonstrict: { points: 1234 },
numProm: Promise.resolve(12),
lenfun: (x: string) => x.length,
};
const result = crazySchema.parse(input);
// Verify the parsed result structure
expect(result.tuple).toEqual(input.tuple);
expect(result.merged).toEqual(input.merged);
expect(result.union).toEqual(input.union);
expect(result.array).toEqual(input.array);
expect(result.sumMinLength).toEqual(input.sumMinLength);
expect(result.intersection).toEqual(input.intersection);
expect(result.enum).toEqual(input.enum);
expect(result.nonstrict).toEqual(input.nonstrict);
expect(result.numProm).toBeInstanceOf(Promise);
expect(typeof result.lenfun).toBe("function");
});

View File

@@ -0,0 +1 @@
{"version":3,"file":"combine-codec.d.ts","sourceRoot":"","sources":["../../src/combine-codec.ts"],"names":[],"mappings":"AAOA,OAAO,EACH,KAAK,EACL,OAAO,EACP,OAAO,EACP,cAAc,EACd,gBAAgB,EAChB,gBAAgB,EAEhB,iBAAiB,EACjB,mBAAmB,EACnB,mBAAmB,EACtB,MAAM,SAAS,CAAC;AAEjB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAqEG;AACH,wBAAgB,YAAY,CAAC,KAAK,EAAE,GAAG,SAAS,KAAK,EAAE,KAAK,SAAS,MAAM,EACvE,OAAO,EAAE,gBAAgB,CAAC,KAAK,EAAE,KAAK,CAAC,EACvC,OAAO,EAAE,gBAAgB,CAAC,GAAG,EAAE,KAAK,CAAC,GACtC,cAAc,CAAC,KAAK,EAAE,GAAG,EAAE,KAAK,CAAC,CAAC;AACrC,wBAAgB,YAAY,CAAC,KAAK,EAAE,GAAG,SAAS,KAAK,EACjD,OAAO,EAAE,mBAAmB,CAAC,KAAK,CAAC,EACnC,OAAO,EAAE,mBAAmB,CAAC,GAAG,CAAC,GAClC,iBAAiB,CAAC,KAAK,EAAE,GAAG,CAAC,CAAC;AACjC,wBAAgB,YAAY,CAAC,KAAK,EAAE,GAAG,SAAS,KAAK,EACjD,OAAO,EAAE,OAAO,CAAC,KAAK,CAAC,EACvB,OAAO,EAAE,OAAO,CAAC,GAAG,CAAC,GACtB,KAAK,CAAC,KAAK,EAAE,GAAG,CAAC,CAAC"}

View File

@@ -0,0 +1,163 @@
'use strict';
module.exports = function generate__limit(it, $keyword, $ruleType) {
var out = ' ';
var $lvl = it.level;
var $dataLvl = it.dataLevel;
var $schema = it.schema[$keyword];
var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
var $breakOnError = !it.opts.allErrors;
var $errorKeyword;
var $data = 'data' + ($dataLvl || '');
var $isData = it.opts.$data && $schema && $schema.$data,
$schemaValue;
if ($isData) {
out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; ';
$schemaValue = 'schema' + $lvl;
} else {
$schemaValue = $schema;
}
var $isMax = $keyword == 'maximum',
$exclusiveKeyword = $isMax ? 'exclusiveMaximum' : 'exclusiveMinimum',
$schemaExcl = it.schema[$exclusiveKeyword],
$isDataExcl = it.opts.$data && $schemaExcl && $schemaExcl.$data,
$op = $isMax ? '<' : '>',
$notOp = $isMax ? '>' : '<',
$errorKeyword = undefined;
if (!($isData || typeof $schema == 'number' || $schema === undefined)) {
throw new Error($keyword + ' must be number');
}
if (!($isDataExcl || $schemaExcl === undefined || typeof $schemaExcl == 'number' || typeof $schemaExcl == 'boolean')) {
throw new Error($exclusiveKeyword + ' must be number or boolean');
}
if ($isDataExcl) {
var $schemaValueExcl = it.util.getData($schemaExcl.$data, $dataLvl, it.dataPathArr),
$exclusive = 'exclusive' + $lvl,
$exclType = 'exclType' + $lvl,
$exclIsNumber = 'exclIsNumber' + $lvl,
$opExpr = 'op' + $lvl,
$opStr = '\' + ' + $opExpr + ' + \'';
out += ' var schemaExcl' + ($lvl) + ' = ' + ($schemaValueExcl) + '; ';
$schemaValueExcl = 'schemaExcl' + $lvl;
out += ' var ' + ($exclusive) + '; var ' + ($exclType) + ' = typeof ' + ($schemaValueExcl) + '; if (' + ($exclType) + ' != \'boolean\' && ' + ($exclType) + ' != \'undefined\' && ' + ($exclType) + ' != \'number\') { ';
var $errorKeyword = $exclusiveKeyword;
var $$outStack = $$outStack || [];
$$outStack.push(out);
out = ''; /* istanbul ignore else */
if (it.createErrors !== false) {
out += ' { keyword: \'' + ($errorKeyword || '_exclusiveLimit') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: {} ';
if (it.opts.messages !== false) {
out += ' , message: \'' + ($exclusiveKeyword) + ' should be boolean\' ';
}
if (it.opts.verbose) {
out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
}
out += ' } ';
} else {
out += ' {} ';
}
var __err = out;
out = $$outStack.pop();
if (!it.compositeRule && $breakOnError) {
/* istanbul ignore if */
if (it.async) {
out += ' throw new ValidationError([' + (__err) + ']); ';
} else {
out += ' validate.errors = [' + (__err) + ']; return false; ';
}
} else {
out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
}
out += ' } else if ( ';
if ($isData) {
out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'number\') || ';
}
out += ' ' + ($exclType) + ' == \'number\' ? ( (' + ($exclusive) + ' = ' + ($schemaValue) + ' === undefined || ' + ($schemaValueExcl) + ' ' + ($op) + '= ' + ($schemaValue) + ') ? ' + ($data) + ' ' + ($notOp) + '= ' + ($schemaValueExcl) + ' : ' + ($data) + ' ' + ($notOp) + ' ' + ($schemaValue) + ' ) : ( (' + ($exclusive) + ' = ' + ($schemaValueExcl) + ' === true) ? ' + ($data) + ' ' + ($notOp) + '= ' + ($schemaValue) + ' : ' + ($data) + ' ' + ($notOp) + ' ' + ($schemaValue) + ' ) || ' + ($data) + ' !== ' + ($data) + ') { var op' + ($lvl) + ' = ' + ($exclusive) + ' ? \'' + ($op) + '\' : \'' + ($op) + '=\'; ';
if ($schema === undefined) {
$errorKeyword = $exclusiveKeyword;
$errSchemaPath = it.errSchemaPath + '/' + $exclusiveKeyword;
$schemaValue = $schemaValueExcl;
$isData = $isDataExcl;
}
} else {
var $exclIsNumber = typeof $schemaExcl == 'number',
$opStr = $op;
if ($exclIsNumber && $isData) {
var $opExpr = '\'' + $opStr + '\'';
out += ' if ( ';
if ($isData) {
out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'number\') || ';
}
out += ' ( ' + ($schemaValue) + ' === undefined || ' + ($schemaExcl) + ' ' + ($op) + '= ' + ($schemaValue) + ' ? ' + ($data) + ' ' + ($notOp) + '= ' + ($schemaExcl) + ' : ' + ($data) + ' ' + ($notOp) + ' ' + ($schemaValue) + ' ) || ' + ($data) + ' !== ' + ($data) + ') { ';
} else {
if ($exclIsNumber && $schema === undefined) {
$exclusive = true;
$errorKeyword = $exclusiveKeyword;
$errSchemaPath = it.errSchemaPath + '/' + $exclusiveKeyword;
$schemaValue = $schemaExcl;
$notOp += '=';
} else {
if ($exclIsNumber) $schemaValue = Math[$isMax ? 'min' : 'max']($schemaExcl, $schema);
if ($schemaExcl === ($exclIsNumber ? $schemaValue : true)) {
$exclusive = true;
$errorKeyword = $exclusiveKeyword;
$errSchemaPath = it.errSchemaPath + '/' + $exclusiveKeyword;
$notOp += '=';
} else {
$exclusive = false;
$opStr += '=';
}
}
var $opExpr = '\'' + $opStr + '\'';
out += ' if ( ';
if ($isData) {
out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'number\') || ';
}
out += ' ' + ($data) + ' ' + ($notOp) + ' ' + ($schemaValue) + ' || ' + ($data) + ' !== ' + ($data) + ') { ';
}
}
$errorKeyword = $errorKeyword || $keyword;
var $$outStack = $$outStack || [];
$$outStack.push(out);
out = ''; /* istanbul ignore else */
if (it.createErrors !== false) {
out += ' { keyword: \'' + ($errorKeyword || '_limit') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { comparison: ' + ($opExpr) + ', limit: ' + ($schemaValue) + ', exclusive: ' + ($exclusive) + ' } ';
if (it.opts.messages !== false) {
out += ' , message: \'should be ' + ($opStr) + ' ';
if ($isData) {
out += '\' + ' + ($schemaValue);
} else {
out += '' + ($schemaValue) + '\'';
}
}
if (it.opts.verbose) {
out += ' , schema: ';
if ($isData) {
out += 'validate.schema' + ($schemaPath);
} else {
out += '' + ($schema);
}
out += ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
}
out += ' } ';
} else {
out += ' {} ';
}
var __err = out;
out = $$outStack.pop();
if (!it.compositeRule && $breakOnError) {
/* istanbul ignore if */
if (it.async) {
out += ' throw new ValidationError([' + (__err) + ']); ';
} else {
out += ' validate.errors = [' + (__err) + ']; return false; ';
}
} else {
out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
}
out += ' } ';
if ($breakOnError) {
out += ' else { ';
}
return out;
}

View File

@@ -0,0 +1,6 @@
/**
* @fileoverview typings for "eslint/universal" module
* @author 唯然<weiran.zsd@outlook.com>
*/
export { Linter } from "./index";

View File

@@ -0,0 +1,49 @@
# TypeScript
[![CI](https://github.com/microsoft/TypeScript/actions/workflows/ci.yml/badge.svg)](https://github.com/microsoft/TypeScript/actions/workflows/ci.yml)
[![npm version](https://badge.fury.io/js/typescript.svg)](https://www.npmjs.com/package/typescript)
[![Downloads](https://img.shields.io/npm/dm/typescript.svg)](https://www.npmjs.com/package/typescript)
[![OpenSSF Scorecard](https://api.securityscorecards.dev/projects/github.com/microsoft/TypeScript/badge)](https://securityscorecards.dev/viewer/?uri=github.com/microsoft/TypeScript)
[TypeScript](https://www.typescriptlang.org/) is a language for application-scale JavaScript. TypeScript adds optional types to JavaScript that support tools for large-scale JavaScript applications for any browser, for any host, on any OS. TypeScript compiles to readable, standards-based JavaScript. Try it out at the [playground](https://www.typescriptlang.org/play/), and stay up to date via [our blog](https://devblogs.microsoft.com/typescript/) and [Bluesky](https://bsky.app/profile/typescriptlang.org).
Find others who are using TypeScript at [our community page](https://www.typescriptlang.org/community/).
## Installing
For the latest stable version:
```bash
npm install -D typescript
```
For our nightly builds:
```bash
npm install -D typescript@next
```
## Contribute
There are many ways to [contribute](https://github.com/microsoft/TypeScript/blob/main/CONTRIBUTING.md) to TypeScript.
* [Submit bugs](https://github.com/microsoft/TypeScript/issues) and help us verify fixes as they are checked in.
* Review the [source code changes](https://github.com/microsoft/TypeScript/pulls).
* Engage with other TypeScript users and developers on [Stack Overflow](https://stackoverflow.com/questions/tagged/typescript).
* Help each other in the [TypeScript Community Discord](https://discord.gg/typescript).
* Join the [#typescript](https://bsky.app/search?q=%23typescript) discussion on Bluesky.
* [Contribute bug fixes](https://github.com/microsoft/TypeScript/blob/main/CONTRIBUTING.md).
This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/). For more information see
the [Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) or contact [opencode@microsoft.com](mailto:opencode@microsoft.com)
with any additional questions or comments.
## Documentation
* [TypeScript in 5 minutes](https://www.typescriptlang.org/docs/handbook/typescript-in-5-minutes.html)
* [Programming handbook](https://www.typescriptlang.org/docs/handbook/intro.html)
* [Homepage](https://www.typescriptlang.org/)
## Roadmap
For details on our planned features and future direction, please refer to our [roadmap](https://github.com/microsoft/TypeScript/wiki/Roadmap).

View File

@@ -0,0 +1,141 @@
import type { ConstructorOverloadParameters, NumOverloads, OverloadsInfoUnion } from './overloads';
import type { IsNever, IsAny, IsUnknown, ReadonlyKeys, RequiredKeys, OptionalKeys, MutuallyExtends, UnionToTuple, IsTuple, UnionToIntersection, TupleToRecord, IsRecord } from './utils';
export type DeepBrandOptions = {
nominalTypes: {};
};
export type DeepBrandOptionsDefaults = {
nominalTypes: {
Date: Date;
};
};
export type NominalType<T, Options extends DeepBrandOptions> = Options['nominalTypes'] extends infer N ? {
[K in keyof N]: MutuallyExtends<N[K], T> extends true ? K : never;
}[keyof N] : never;
/**
* Represents a deeply branded type.
*
* Recursively walk a type and replace it with a branded type related to the
* original. This is useful for equality-checking stricter than
* `A extends B ? B extends A ? true : false : false`, because it detects the
* difference between a few edge-case types that vanilla TypeScript
* doesn't by default:
* - `any` vs `unknown`
* - `{ readonly a: string }` vs `{ a: string }`
* - `{ a?: string }` vs `{ a: string | undefined }`
*
* __Note__: not very performant for complex types - this should only be used
* when you know you need it. If doing an equality check, it's almost always
* better to use {@linkcode StrictEqualUsingTSInternalIdenticalToOperator}.
*/
export type DeepBrand<T, Options extends DeepBrandOptions> = IsNever<T> extends true ? {
type: 'never';
} : IsAny<T> extends true ? {
type: 'any';
} : IsUnknown<T> extends true ? {
type: 'unknown';
} : NominalType<T, Options> extends infer Nominal ? IsNever<Nominal> extends true ? T extends string | number | boolean | symbol | bigint | null | undefined | void ? {
type: 'primitive';
value: T;
} : T extends new (...args: any[]) => any ? {
type: 'constructor';
params: ConstructorOverloadParameters<T>;
instance: DeepBrand<InstanceType<Extract<T, new (...args: any) => any>>, Options>;
} : T extends (...args: infer P) => infer R ? NumOverloads<T> extends 1 ? {
type: 'function';
params: DeepBrand<P, Options>;
return: DeepBrand<R, Options>;
this: DeepBrand<ThisParameterType<T>, Options>;
props: DeepBrand<Omit<T, keyof Function>, Options>;
} : UnionToTuple<OverloadsInfoUnion<T>> extends infer OverloadsTuple ? {
type: 'overloads';
overloads: {
[K in keyof OverloadsTuple]: DeepBrand<OverloadsTuple[K], Options>;
};
} : never : T extends any[] ? IsTuple<T> extends true ? {
type: 'tuple';
items: {
[K in keyof T]: DeepBrand<T[K], Options>;
};
} : {
type: 'array';
items: DeepBrand<T[number], Options>;
} : IsRecord<T> extends true ? {
type: 'record';
keys: keyof T;
values: DeepBrand<T[keyof T], Options>;
} : {
type: 'object';
properties: {
[K in keyof T]: DeepBrand<T[K], Options>;
};
readonly: ReadonlyKeys<T>;
required: RequiredKeys<T>;
optional: OptionalKeys<T>;
constructorParams: ConstructorOverloadParameters<T> extends infer P ? IsNever<P> extends true ? never : DeepBrand<P, Options> : never;
} : {
type: Nominal;
} : never;
/**
* Checks if two types are strictly equal using branding.
*/
export type StrictEqualUsingBranding<Left, Right, Options extends DeepBrandOptions> = MutuallyExtends<DeepBrand<Left, Options>, DeepBrand<Right, Options>>;
/**
* @internal don't use this unless you are deeply familiar with it!
*
* Walks over a type `T`, assuming that it's the output of the {@linkcode DeepBrand} utility. It looks for leaf nodes looking like `{type: FindType}`.
* When it finds them, it merges them into a string->string record, keeping track of a rough representation of the path-location.
* For simple objects, this path will roughly match dot-prop notation but it also traverses into all the structures that `DeepBrand` can emit.
* But it also goes into overloads, function parameters, return types, etc. The output is an ugly intersection of objects along with a marker `{deepBrandLeafNode: true}`
* which is purely for internal use. The output should not be shown to end-users!
*/
type _DeepPropTypesOfBranded<T, PathTo extends string, FindType extends string> = IsNever<T> extends true ? {} : T extends string ? {} : T extends {
type: FindType;
} ? {
[K in PathTo]: T['type'];
} & {
deepBrandLeafNode: true;
} : T extends any[] ? _DeepPropTypesOfBranded<TupleToRecord<T>, PathTo, FindType> : UnionToIntersection<{
[K in keyof T]: Extract<_DeepPropTypesOfBranded<T[K], `${PathTo}${DeepBrandPropPathSuffix<T, Prop<K>>}`, FindType>, {
deepBrandLeafNode: true;
}>;
}[keyof T]>;
/** Required options for for {@linkcode DeepBrandPropNotes}. */
export type DeepBrandPropNotesOptions = Partial<DeepBrandOptions> & {
findType: 'any' | 'never' | 'unknown';
};
/** Default options for for {@linkcode DeepBrandPropNotes}. */
export type DeepBrandPropNotesOptionsDefaults = {
findType: 'any' | 'never';
};
/**
* For an input type `T`, finds all deeply-nested properties in the {@linkcode DeepBrand} representation of it.
*
* The output is a developer-readable shallow record of prop-path -> resolved type.
* @example
* ```ts
* type X = {a: any; b: boolean; c: {d: any}}
* const notes: DeepBrandPropNotes<X, {findType: 'any'}> = {
* '.a': 'any',
* '.c.d': 'any',
* }
* ```
*/
export type DeepBrandPropNotes<T, Options extends DeepBrandPropNotesOptions> = _DeepPropTypesOfBranded<DeepBrand<T, DeepBrandOptionsDefaults & Options>, '', Options['findType']> extends infer X ? {} extends X ? Record<string | number | symbol, 'No flagged props found!'> : {
[K in Exclude<keyof X, 'deepBrandLeafNode'>]: X[K];
} : never;
/**
* @internal
*
* Helper to coerce a type `K` that you are already pretty sure is a string because it camed from a `keyof T` type expression.
* Useful because sometimes TypeScript forgets that.
* When it's not a string or number, it will output a big ugly literal type `'UNEXPECTED_NON_LITERAL_PROP'` - try to avoid this!
*/
export type Prop<K> = K extends string | number ? K : 'UNEXPECTED_NON_LITERAL_PROP';
/**
* Gets a sensible suffix to a property path for a {@linkcode DeepBrand} output type.
* `[number]` for arrays, empty string for objects, and parenthesised-input for anything else.
*/
type DeepBrandPropPathSuffix<T, K> = T extends {
type: string;
} ? K extends 'items' ? '[number]' : K extends 'properties' ? '' : `(${Prop<K>})` : `.${Prop<K>}`;
export {};

View File

@@ -0,0 +1,7 @@
import type { StringReader, StringWriter } from './strings.mts';
export declare const comma: number;
export declare const semicolon: number;
export declare function decodeInteger(reader: StringReader, relative: number): number;
export declare function encodeInteger(builder: StringWriter, num: number, relative: number): number;
export declare function hasMoreVlq(reader: StringReader, max: number): boolean;
//# sourceMappingURL=vlq.d.ts.map

View File

@@ -0,0 +1,30 @@
import type { CurveLengths } from './curve.ts';
type Hex = string | Uint8Array;
export type CurveType = {
P: bigint;
type: 'x25519' | 'x448';
adjustScalarBytes: (bytes: Uint8Array) => Uint8Array;
powPminus2: (x: bigint) => bigint;
randomBytes?: (bytesLength?: number) => Uint8Array;
};
export type MontgomeryECDH = {
scalarMult: (scalar: Hex, u: Hex) => Uint8Array;
scalarMultBase: (scalar: Hex) => Uint8Array;
getSharedSecret: (secretKeyA: Hex, publicKeyB: Hex) => Uint8Array;
getPublicKey: (secretKey: Hex) => Uint8Array;
utils: {
randomSecretKey: () => Uint8Array;
/** @deprecated use `randomSecretKey` */
randomPrivateKey: () => Uint8Array;
};
GuBytes: Uint8Array;
lengths: CurveLengths;
keygen: (seed?: Uint8Array) => {
secretKey: Uint8Array;
publicKey: Uint8Array;
};
};
export type CurveFn = MontgomeryECDH;
export declare function montgomery(curveDef: CurveType): MontgomeryECDH;
export {};
//# sourceMappingURL=montgomery.d.ts.map

View File

@@ -0,0 +1,89 @@
# cross-spawn
[![NPM version][npm-image]][npm-url] [![Downloads][downloads-image]][npm-url] [![Build Status][ci-image]][ci-url] [![Build status][appveyor-image]][appveyor-url]
[npm-url]:https://npmjs.org/package/cross-spawn
[downloads-image]:https://img.shields.io/npm/dm/cross-spawn.svg
[npm-image]:https://img.shields.io/npm/v/cross-spawn.svg
[ci-url]:https://github.com/moxystudio/node-cross-spawn/actions/workflows/ci.yaml
[ci-image]:https://github.com/moxystudio/node-cross-spawn/actions/workflows/ci.yaml/badge.svg
[appveyor-url]:https://ci.appveyor.com/project/satazor/node-cross-spawn
[appveyor-image]:https://img.shields.io/appveyor/ci/satazor/node-cross-spawn/master.svg
A cross platform solution to node's spawn and spawnSync.
## Installation
Node.js version 8 and up:
`$ npm install cross-spawn`
Node.js version 7 and under:
`$ npm install cross-spawn@6`
## Why
Node has issues when using spawn on Windows:
- It ignores [PATHEXT](https://github.com/joyent/node/issues/2318)
- It does not support [shebangs](https://en.wikipedia.org/wiki/Shebang_(Unix))
- Has problems running commands with [spaces](https://github.com/nodejs/node/issues/7367)
- Has problems running commands with posix relative paths (e.g.: `./my-folder/my-executable`)
- Has an [issue](https://github.com/moxystudio/node-cross-spawn/issues/82) with command shims (files in `node_modules/.bin/`), where arguments with quotes and parenthesis would result in [invalid syntax error](https://github.com/moxystudio/node-cross-spawn/blob/e77b8f22a416db46b6196767bcd35601d7e11d54/test/index.test.js#L149)
- No `options.shell` support on node `<v4.8`
All these issues are handled correctly by `cross-spawn`.
There are some known modules, such as [win-spawn](https://github.com/ForbesLindesay/win-spawn), that try to solve this but they are either broken or provide faulty escaping of shell arguments.
## Usage
Exactly the same way as node's [`spawn`](https://nodejs.org/api/child_process.html#child_process_child_process_spawn_command_args_options) or [`spawnSync`](https://nodejs.org/api/child_process.html#child_process_child_process_spawnsync_command_args_options), so it's a drop in replacement.
```js
const spawn = require('cross-spawn');
// Spawn NPM asynchronously
const child = spawn('npm', ['list', '-g', '-depth', '0'], { stdio: 'inherit' });
// Spawn NPM synchronously
const result = spawn.sync('npm', ['list', '-g', '-depth', '0'], { stdio: 'inherit' });
```
## Caveats
### Using `options.shell` as an alternative to `cross-spawn`
Starting from node `v4.8`, `spawn` has a `shell` option that allows you run commands from within a shell. This new option solves
the [PATHEXT](https://github.com/joyent/node/issues/2318) issue but:
- It's not supported in node `<v4.8`
- You must manually escape the command and arguments which is very error prone, specially when passing user input
- There are a lot of other unresolved issues from the [Why](#why) section that you must take into account
If you are using the `shell` option to spawn a command in a cross platform way, consider using `cross-spawn` instead. You have been warned.
### `options.shell` support
While `cross-spawn` adds support for `options.shell` in node `<v4.8`, all of its enhancements are disabled.
This mimics the Node.js behavior. More specifically, the command and its arguments will not be automatically escaped nor shebang support will be offered. This is by design because if you are using `options.shell` you are probably targeting a specific platform anyway and you don't want things to get into your way.
### Shebangs support
While `cross-spawn` handles shebangs on Windows, its support is limited. More specifically, it just supports `#!/usr/bin/env <program>` where `<program>` must not contain any arguments.
If you would like to have the shebang support improved, feel free to contribute via a pull-request.
Remember to always test your code on Windows!
## Tests
`$ npm test`
`$ npm test -- --watch` during development
## License
Released under the [MIT License](https://www.opensource.org/licenses/mit-license.php).

View File

@@ -0,0 +1,45 @@
import {
AnyNode,
AtRule,
Builder,
Comment,
Container,
Declaration,
Document,
Root,
Rule
} from './postcss.js'
declare namespace Stringifier {
export { Stringifier_ as default }
}
declare class Stringifier_ {
builder: Builder
constructor(builder: Builder)
atrule(node: AtRule, semicolon?: boolean): void
beforeAfter(node: AnyNode, detect: 'after' | 'before'): string
block(node: AnyNode, start: string): void
body(node: Container): void
comment(node: Comment): void
decl(node: Declaration, semicolon?: boolean): void
document(node: Document): void
raw(node: AnyNode, own: null | string, detect?: string): boolean | string
rawBeforeClose(root: Root): string | undefined
rawBeforeComment(root: Root, node: Comment): string | undefined
rawBeforeDecl(root: Root, node: Declaration): string | undefined
rawBeforeOpen(root: Root): string | undefined
rawBeforeRule(root: Root): string | undefined
rawColon(root: Root): string | undefined
rawEmptyBody(root: Root): string | undefined
rawIndent(root: Root): string | undefined
rawSemicolon(root: Root): boolean | undefined
rawValue(node: AnyNode, prop: string): number | string
root(node: Root): void
rule(node: Rule): void
stringify(node: AnyNode, semicolon?: boolean): void
}
declare class Stringifier extends Stringifier_ {}
export = Stringifier

View File

@@ -0,0 +1,162 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.SHA512_IV = exports.SHA384_IV = exports.SHA224_IV = exports.SHA256_IV = exports.HashMD = void 0;
exports.setBigUint64 = setBigUint64;
exports.Chi = Chi;
exports.Maj = Maj;
/**
* Internal Merkle-Damgard hash utils.
* @module
*/
const utils_ts_1 = require("./utils.js");
/** Polyfill for Safari 14. https://caniuse.com/mdn-javascript_builtins_dataview_setbiguint64 */
function setBigUint64(view, byteOffset, value, isLE) {
if (typeof view.setBigUint64 === 'function')
return view.setBigUint64(byteOffset, value, isLE);
const _32n = BigInt(32);
const _u32_max = BigInt(0xffffffff);
const wh = Number((value >> _32n) & _u32_max);
const wl = Number(value & _u32_max);
const h = isLE ? 4 : 0;
const l = isLE ? 0 : 4;
view.setUint32(byteOffset + h, wh, isLE);
view.setUint32(byteOffset + l, wl, isLE);
}
/** Choice: a ? b : c */
function Chi(a, b, c) {
return (a & b) ^ (~a & c);
}
/** Majority function, true if any two inputs is true. */
function Maj(a, b, c) {
return (a & b) ^ (a & c) ^ (b & c);
}
/**
* Merkle-Damgard hash construction base class.
* Could be used to create MD5, RIPEMD, SHA1, SHA2.
*/
class HashMD extends utils_ts_1.Hash {
constructor(blockLen, outputLen, padOffset, isLE) {
super();
this.finished = false;
this.length = 0;
this.pos = 0;
this.destroyed = false;
this.blockLen = blockLen;
this.outputLen = outputLen;
this.padOffset = padOffset;
this.isLE = isLE;
this.buffer = new Uint8Array(blockLen);
this.view = (0, utils_ts_1.createView)(this.buffer);
}
update(data) {
(0, utils_ts_1.aexists)(this);
data = (0, utils_ts_1.toBytes)(data);
(0, utils_ts_1.abytes)(data);
const { view, buffer, blockLen } = this;
const len = data.length;
for (let pos = 0; pos < len;) {
const take = Math.min(blockLen - this.pos, len - pos);
// Fast path: we have at least one block in input, cast it to view and process
if (take === blockLen) {
const dataView = (0, utils_ts_1.createView)(data);
for (; blockLen <= len - pos; pos += blockLen)
this.process(dataView, pos);
continue;
}
buffer.set(data.subarray(pos, pos + take), this.pos);
this.pos += take;
pos += take;
if (this.pos === blockLen) {
this.process(view, 0);
this.pos = 0;
}
}
this.length += data.length;
this.roundClean();
return this;
}
digestInto(out) {
(0, utils_ts_1.aexists)(this);
(0, utils_ts_1.aoutput)(out, this);
this.finished = true;
// Padding
// We can avoid allocation of buffer for padding completely if it
// was previously not allocated here. But it won't change performance.
const { buffer, view, blockLen, isLE } = this;
let { pos } = this;
// append the bit '1' to the message
buffer[pos++] = 0b10000000;
(0, utils_ts_1.clean)(this.buffer.subarray(pos));
// we have less than padOffset left in buffer, so we cannot put length in
// current block, need process it and pad again
if (this.padOffset > blockLen - pos) {
this.process(view, 0);
pos = 0;
}
// Pad until full block byte with zeros
for (let i = pos; i < blockLen; i++)
buffer[i] = 0;
// Note: sha512 requires length to be 128bit integer, but length in JS will overflow before that
// You need to write around 2 exabytes (u64_max / 8 / (1024**6)) for this to happen.
// So we just write lowest 64 bits of that value.
setBigUint64(view, blockLen - 8, BigInt(this.length * 8), isLE);
this.process(view, 0);
const oview = (0, utils_ts_1.createView)(out);
const len = this.outputLen;
// NOTE: we do division by 4 later, which should be fused in single op with modulo by JIT
if (len % 4)
throw new Error('_sha2: outputLen should be aligned to 32bit');
const outLen = len / 4;
const state = this.get();
if (outLen > state.length)
throw new Error('_sha2: outputLen bigger than state');
for (let i = 0; i < outLen; i++)
oview.setUint32(4 * i, state[i], isLE);
}
digest() {
const { buffer, outputLen } = this;
this.digestInto(buffer);
const res = buffer.slice(0, outputLen);
this.destroy();
return res;
}
_cloneInto(to) {
to || (to = new this.constructor());
to.set(...this.get());
const { blockLen, buffer, length, finished, destroyed, pos } = this;
to.destroyed = destroyed;
to.finished = finished;
to.length = length;
to.pos = pos;
if (length % blockLen)
to.buffer.set(buffer);
return to;
}
clone() {
return this._cloneInto();
}
}
exports.HashMD = HashMD;
/**
* Initial SHA-2 state: fractional parts of square roots of first 16 primes 2..53.
* Check out `test/misc/sha2-gen-iv.js` for recomputation guide.
*/
/** Initial SHA256 state. Bits 0..32 of frac part of sqrt of primes 2..19 */
exports.SHA256_IV = Uint32Array.from([
0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19,
]);
/** Initial SHA224 state. Bits 32..64 of frac part of sqrt of primes 23..53 */
exports.SHA224_IV = Uint32Array.from([
0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939, 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4,
]);
/** Initial SHA384 state. Bits 0..64 of frac part of sqrt of primes 23..53 */
exports.SHA384_IV = Uint32Array.from([
0xcbbb9d5d, 0xc1059ed8, 0x629a292a, 0x367cd507, 0x9159015a, 0x3070dd17, 0x152fecd8, 0xf70e5939,
0x67332667, 0xffc00b31, 0x8eb44a87, 0x68581511, 0xdb0c2e0d, 0x64f98fa7, 0x47b5481d, 0xbefa4fa4,
]);
/** Initial SHA512 state. Bits 0..64 of frac part of sqrt of primes 2..19 */
exports.SHA512_IV = Uint32Array.from([
0x6a09e667, 0xf3bcc908, 0xbb67ae85, 0x84caa73b, 0x3c6ef372, 0xfe94f82b, 0xa54ff53a, 0x5f1d36f1,
0x510e527f, 0xade682d1, 0x9b05688c, 0x2b3e6c1f, 0x1f83d9ab, 0xfb41bd6b, 0x5be0cd19, 0x137e2179,
]);
//# sourceMappingURL=_md.js.map

View File

@@ -0,0 +1,19 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.referenceContainsTypeQuery = referenceContainsTypeQuery;
const utils_1 = require("@typescript-eslint/utils");
/**
* Recursively checks whether a given reference has a type query declaration among its parents
*/
function referenceContainsTypeQuery(node) {
switch (node.type) {
case utils_1.AST_NODE_TYPES.TSTypeQuery:
return true;
case utils_1.AST_NODE_TYPES.TSQualifiedName:
case utils_1.AST_NODE_TYPES.Identifier:
return referenceContainsTypeQuery(node.parent);
default:
// if we find a different node, there's no chance that we're in a TSTypeQuery
return false;
}
}

View File

@@ -0,0 +1,153 @@
### Estraverse [![Build Status](https://secure.travis-ci.org/estools/estraverse.svg)](http://travis-ci.org/estools/estraverse)
Estraverse ([estraverse](http://github.com/estools/estraverse)) is
[ECMAScript](http://www.ecma-international.org/publications/standards/Ecma-262.htm)
traversal functions from [esmangle project](http://github.com/estools/esmangle).
### Documentation
You can find usage docs at [wiki page](https://github.com/estools/estraverse/wiki/Usage).
### Example Usage
The following code will output all variables declared at the root of a file.
```javascript
estraverse.traverse(ast, {
enter: function (node, parent) {
if (node.type == 'FunctionExpression' || node.type == 'FunctionDeclaration')
return estraverse.VisitorOption.Skip;
},
leave: function (node, parent) {
if (node.type == 'VariableDeclarator')
console.log(node.id.name);
}
});
```
We can use `this.skip`, `this.remove` and `this.break` functions instead of using Skip, Remove and Break.
```javascript
estraverse.traverse(ast, {
enter: function (node) {
this.break();
}
});
```
And estraverse provides `estraverse.replace` function. When returning node from `enter`/`leave`, current node is replaced with it.
```javascript
result = estraverse.replace(tree, {
enter: function (node) {
// Replace it with replaced.
if (node.type === 'Literal')
return replaced;
}
});
```
By passing `visitor.keys` mapping, we can extend estraverse traversing functionality.
```javascript
// This tree contains a user-defined `TestExpression` node.
var tree = {
type: 'TestExpression',
// This 'argument' is the property containing the other **node**.
argument: {
type: 'Literal',
value: 20
},
// This 'extended' is the property not containing the other **node**.
extended: true
};
estraverse.traverse(tree, {
enter: function (node) { },
// Extending the existing traversing rules.
keys: {
// TargetNodeName: [ 'keys', 'containing', 'the', 'other', '**node**' ]
TestExpression: ['argument']
}
});
```
By passing `visitor.fallback` option, we can control the behavior when encountering unknown nodes.
```javascript
// This tree contains a user-defined `TestExpression` node.
var tree = {
type: 'TestExpression',
// This 'argument' is the property containing the other **node**.
argument: {
type: 'Literal',
value: 20
},
// This 'extended' is the property not containing the other **node**.
extended: true
};
estraverse.traverse(tree, {
enter: function (node) { },
// Iterating the child **nodes** of unknown nodes.
fallback: 'iteration'
});
```
When `visitor.fallback` is a function, we can determine which keys to visit on each node.
```javascript
// This tree contains a user-defined `TestExpression` node.
var tree = {
type: 'TestExpression',
// This 'argument' is the property containing the other **node**.
argument: {
type: 'Literal',
value: 20
},
// This 'extended' is the property not containing the other **node**.
extended: true
};
estraverse.traverse(tree, {
enter: function (node) { },
// Skip the `argument` property of each node
fallback: function(node) {
return Object.keys(node).filter(function(key) {
return key !== 'argument';
});
}
});
```
### License
Copyright (C) 2012-2016 [Yusuke Suzuki](http://github.com/Constellation)
(twitter: [@Constellation](http://twitter.com/Constellation)) and other contributors.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

View File

@@ -0,0 +1,78 @@
/**
* @fileoverview Serialization utils.
* @author Bryan Mishkin
*/
"use strict";
/**
* Check if a value is a primitive or plain object created by the Object constructor.
* @param {any} val the value to check
* @returns {boolean} `true` if so
* @private
*/
function isSerializablePrimitiveOrPlainObject(val) {
return (
val === null ||
typeof val === "string" ||
typeof val === "boolean" ||
typeof val === "number" ||
(typeof val === "object" && val.constructor === Object) ||
Array.isArray(val)
);
}
/**
* Check if a value is serializable.
* Functions or objects like RegExp cannot be serialized by JSON.stringify().
* Inspired by: https://stackoverflow.com/questions/30579940/reliable-way-to-check-if-objects-is-serializable-in-javascript
* @param {any} val The value
* @param {Set<Object>} seenObjects Objects already seen in this path from the root object.
* @returns {boolean} `true` if the value is serializable
*/
function isSerializable(val, seenObjects = new Set()) {
if (!isSerializablePrimitiveOrPlainObject(val)) {
return false;
}
if (typeof val === "object" && val !== null) {
if (seenObjects.has(val)) {
/*
* Since this is a depth-first traversal, encountering
* the same object again means there is a circular reference.
* Objects with circular references are not serializable.
*/
return false;
}
for (const property in val) {
if (Object.hasOwn(val, property)) {
if (!isSerializablePrimitiveOrPlainObject(val[property])) {
return false;
}
if (
typeof val[property] === "object" &&
val[property] !== null
) {
if (
/*
* We're creating a new Set of seen objects because we want to
* ensure that `val` doesn't appear again in this path, but it can appear
* in other paths. This allows for reusing objects in the graph, as long as
* there are no cycles.
*/
!isSerializable(
val[property],
new Set([...seenObjects, val]),
)
) {
return false;
}
}
}
}
}
return true;
}
module.exports = {
isSerializable,
};

View File

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