WIP: bootstrap and partial real Solana watcher implementation
This commit is contained in:
@@ -0,0 +1,119 @@
|
||||
/** The Standard Typed interface. This is a base type extended by other specs. */
|
||||
interface StandardTypedV1<Input = unknown, Output = Input> {
|
||||
/** The Standard properties. */
|
||||
readonly "~standard": StandardTypedV1.Props<Input, Output>;
|
||||
}
|
||||
declare namespace StandardTypedV1 {
|
||||
/** The Standard Typed properties interface. */
|
||||
interface Props<Input = unknown, Output = Input> {
|
||||
/** The version number of the standard. */
|
||||
readonly version: 1;
|
||||
/** The vendor name of the schema library. */
|
||||
readonly vendor: string;
|
||||
/** Inferred types associated with the schema. */
|
||||
readonly types?: Types<Input, Output> | undefined;
|
||||
}
|
||||
/** The Standard Typed types interface. */
|
||||
interface Types<Input = unknown, Output = Input> {
|
||||
/** The input type of the schema. */
|
||||
readonly input: Input;
|
||||
/** The output type of the schema. */
|
||||
readonly output: Output;
|
||||
}
|
||||
/** Infers the input type of a Standard Typed. */
|
||||
type InferInput<Schema extends StandardTypedV1> = NonNullable<Schema["~standard"]["types"]>["input"];
|
||||
/** Infers the output type of a Standard Typed. */
|
||||
type InferOutput<Schema extends StandardTypedV1> = NonNullable<Schema["~standard"]["types"]>["output"];
|
||||
}
|
||||
/** The Standard Schema interface. */
|
||||
interface StandardSchemaV1<Input = unknown, Output = Input> {
|
||||
/** The Standard Schema properties. */
|
||||
readonly "~standard": StandardSchemaV1.Props<Input, Output>;
|
||||
}
|
||||
declare namespace StandardSchemaV1 {
|
||||
/** The Standard Schema properties interface. */
|
||||
interface Props<Input = unknown, Output = Input> extends StandardTypedV1.Props<Input, Output> {
|
||||
/** Validates unknown input values. */
|
||||
readonly validate: (value: unknown, options?: StandardSchemaV1.Options | undefined) => Result<Output> | Promise<Result<Output>>;
|
||||
}
|
||||
/** The result interface of the validate function. */
|
||||
type Result<Output> = SuccessResult<Output> | FailureResult;
|
||||
/** The result interface if validation succeeds. */
|
||||
interface SuccessResult<Output> {
|
||||
/** The typed output value. */
|
||||
readonly value: Output;
|
||||
/** A falsy value for `issues` indicates success. */
|
||||
readonly issues?: undefined;
|
||||
}
|
||||
interface Options {
|
||||
/** Explicit support for additional vendor-specific parameters, if needed. */
|
||||
readonly libraryOptions?: Record<string, unknown> | undefined;
|
||||
}
|
||||
/** The result interface if validation fails. */
|
||||
interface FailureResult {
|
||||
/** The issues of failed validation. */
|
||||
readonly issues: ReadonlyArray<Issue>;
|
||||
}
|
||||
/** The issue interface of the failure output. */
|
||||
interface Issue {
|
||||
/** The error message of the issue. */
|
||||
readonly message: string;
|
||||
/** The path of the issue, if any. */
|
||||
readonly path?: ReadonlyArray<PropertyKey | PathSegment> | undefined;
|
||||
}
|
||||
/** The path segment interface of the issue. */
|
||||
interface PathSegment {
|
||||
/** The key representing a path segment. */
|
||||
readonly key: PropertyKey;
|
||||
}
|
||||
/** The Standard types interface. */
|
||||
interface Types<Input = unknown, Output = Input> extends StandardTypedV1.Types<Input, Output> {
|
||||
}
|
||||
/** Infers the input type of a Standard. */
|
||||
type InferInput<Schema extends StandardTypedV1> = StandardTypedV1.InferInput<Schema>;
|
||||
/** Infers the output type of a Standard. */
|
||||
type InferOutput<Schema extends StandardTypedV1> = StandardTypedV1.InferOutput<Schema>;
|
||||
}
|
||||
/** The Standard JSON Schema interface. */
|
||||
interface StandardJSONSchemaV1<Input = unknown, Output = Input> {
|
||||
/** The Standard JSON Schema properties. */
|
||||
readonly "~standard": StandardJSONSchemaV1.Props<Input, Output>;
|
||||
}
|
||||
declare namespace StandardJSONSchemaV1 {
|
||||
/** The Standard JSON Schema properties interface. */
|
||||
interface Props<Input = unknown, Output = Input> extends StandardTypedV1.Props<Input, Output> {
|
||||
/** Methods for generating the input/output JSON Schema. */
|
||||
readonly jsonSchema: StandardJSONSchemaV1.Converter;
|
||||
}
|
||||
/** The Standard JSON Schema converter interface. */
|
||||
interface Converter {
|
||||
/** Converts the input type to JSON Schema. May throw if conversion is not supported. */
|
||||
readonly input: (options: StandardJSONSchemaV1.Options) => Record<string, unknown>;
|
||||
/** Converts the output type to JSON Schema. May throw if conversion is not supported. */
|
||||
readonly output: (options: StandardJSONSchemaV1.Options) => Record<string, unknown>;
|
||||
}
|
||||
/**
|
||||
* The target version of the generated JSON Schema.
|
||||
*
|
||||
* It is *strongly recommended* that implementers support `"draft-2020-12"` and `"draft-07"`, as they are both in wide use. All other targets can be implemented on a best-effort basis. Libraries should throw if they don't support a specified target.
|
||||
*
|
||||
* The `"openapi-3.0"` target is intended as a standardized specifier for OpenAPI 3.0 which is a superset of JSON Schema `"draft-04"`.
|
||||
*/
|
||||
type Target = "draft-2020-12" | "draft-07" | "openapi-3.0" | ({} & string);
|
||||
/** The options for the input/output methods. */
|
||||
interface Options {
|
||||
/** Specifies the target version of the generated JSON Schema. Support for all versions is on a best-effort basis. If a given version is not supported, the library should throw. */
|
||||
readonly target: Target;
|
||||
/** Explicit support for additional vendor-specific parameters, if needed. */
|
||||
readonly libraryOptions?: Record<string, unknown> | undefined;
|
||||
}
|
||||
/** The Standard types interface. */
|
||||
interface Types<Input = unknown, Output = Input> extends StandardTypedV1.Types<Input, Output> {
|
||||
}
|
||||
/** Infers the input type of a Standard. */
|
||||
type InferInput<Schema extends StandardTypedV1> = StandardTypedV1.InferInput<Schema>;
|
||||
/** Infers the output type of a Standard. */
|
||||
type InferOutput<Schema extends StandardTypedV1> = StandardTypedV1.InferOutput<Schema>;
|
||||
}
|
||||
|
||||
export { StandardJSONSchemaV1, StandardSchemaV1, StandardTypedV1 };
|
||||
File diff suppressed because one or more lines are too long
@@ -0,0 +1,5 @@
|
||||
import type * as errors from "../core/errors.cjs";
|
||||
declare function _default(): {
|
||||
localeError: errors.$ZodErrorMap;
|
||||
};
|
||||
export = _default;
|
||||
@@ -0,0 +1,66 @@
|
||||
import { MessageEvent, ErrorEvent } from './websocket'
|
||||
import Dispatcher from './dispatcher'
|
||||
|
||||
import {
|
||||
EventListenerOptions,
|
||||
AddEventListenerOptions,
|
||||
EventListenerOrEventListenerObject
|
||||
} from './patch'
|
||||
|
||||
interface EventSourceEventMap {
|
||||
error: ErrorEvent
|
||||
message: MessageEvent
|
||||
open: Event
|
||||
}
|
||||
|
||||
interface EventSource extends EventTarget {
|
||||
close(): void
|
||||
readonly CLOSED: 2
|
||||
readonly CONNECTING: 0
|
||||
readonly OPEN: 1
|
||||
onerror: ((this: EventSource, ev: ErrorEvent) => any) | null
|
||||
onmessage: ((this: EventSource, ev: MessageEvent) => any) | null
|
||||
onopen: ((this: EventSource, ev: Event) => any) | null
|
||||
readonly readyState: 0 | 1 | 2
|
||||
readonly url: string
|
||||
readonly withCredentials: boolean
|
||||
|
||||
addEventListener<K extends keyof EventSourceEventMap>(
|
||||
type: K,
|
||||
listener: (this: EventSource, ev: EventSourceEventMap[K]) => any,
|
||||
options?: boolean | AddEventListenerOptions
|
||||
): void
|
||||
addEventListener(
|
||||
type: string,
|
||||
listener: EventListenerOrEventListenerObject,
|
||||
options?: boolean | AddEventListenerOptions
|
||||
): void
|
||||
removeEventListener<K extends keyof EventSourceEventMap>(
|
||||
type: K,
|
||||
listener: (this: EventSource, ev: EventSourceEventMap[K]) => any,
|
||||
options?: boolean | EventListenerOptions
|
||||
): void
|
||||
removeEventListener(
|
||||
type: string,
|
||||
listener: EventListenerOrEventListenerObject,
|
||||
options?: boolean | EventListenerOptions
|
||||
): void
|
||||
}
|
||||
|
||||
export declare const EventSource: {
|
||||
prototype: EventSource
|
||||
new (url: string | URL, init?: EventSourceInit): EventSource
|
||||
readonly CLOSED: 2
|
||||
readonly CONNECTING: 0
|
||||
readonly OPEN: 1
|
||||
}
|
||||
|
||||
interface EventSourceInit {
|
||||
withCredentials?: boolean
|
||||
// @deprecated use `node.dispatcher` instead
|
||||
dispatcher?: Dispatcher
|
||||
node?: {
|
||||
dispatcher?: Dispatcher
|
||||
reconnectionTime?: number
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
import objectWithoutPropertiesLoose from "./objectWithoutPropertiesLoose.js";
|
||||
function _objectWithoutProperties(e, t) {
|
||||
if (null == e) return {};
|
||||
var o,
|
||||
r,
|
||||
i = objectWithoutPropertiesLoose(e, t);
|
||||
if (Object.getOwnPropertySymbols) {
|
||||
var n = Object.getOwnPropertySymbols(e);
|
||||
for (r = 0; r < n.length; r++) o = n[r], -1 === t.indexOf(o) && {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]);
|
||||
}
|
||||
return i;
|
||||
}
|
||||
export { _objectWithoutProperties as default };
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,6 @@
|
||||
function _setPrototypeOf(t, e) {
|
||||
return module.exports = _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) {
|
||||
return t.__proto__ = e, t;
|
||||
}, module.exports.__esModule = true, module.exports["default"] = module.exports, _setPrototypeOf(t, e);
|
||||
}
|
||||
module.exports = _setPrototypeOf, module.exports.__esModule = true, module.exports["default"] = module.exports;
|
||||
@@ -0,0 +1 @@
|
||||
export * from './dist/coverage.js'
|
||||
@@ -0,0 +1,325 @@
|
||||
"use strict";
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
const assert_1 = __importDefault(require("assert"));
|
||||
const serializer_1 = require("./serializer");
|
||||
const buffer_list_1 = __importDefault(require("./testing/buffer-list"));
|
||||
describe('serializer', () => {
|
||||
it('builds startup message', function () {
|
||||
const actual = serializer_1.serialize.startup({
|
||||
user: 'brian',
|
||||
database: 'bang',
|
||||
});
|
||||
assert_1.default.deepEqual(actual, new buffer_list_1.default()
|
||||
.addInt16(3)
|
||||
.addInt16(0)
|
||||
.addCString('user')
|
||||
.addCString('brian')
|
||||
.addCString('database')
|
||||
.addCString('bang')
|
||||
.addCString('client_encoding')
|
||||
.addCString('UTF8')
|
||||
.addCString('')
|
||||
.join(true));
|
||||
});
|
||||
it('builds password message', function () {
|
||||
const actual = serializer_1.serialize.password('!');
|
||||
assert_1.default.deepEqual(actual, new buffer_list_1.default().addCString('!').join(true, 'p'));
|
||||
});
|
||||
it('builds request ssl message', function () {
|
||||
const actual = serializer_1.serialize.requestSsl();
|
||||
const expected = new buffer_list_1.default().addInt32(80877103).join(true);
|
||||
assert_1.default.deepEqual(actual, expected);
|
||||
});
|
||||
it('builds SASLInitialResponseMessage message', function () {
|
||||
const actual = serializer_1.serialize.sendSASLInitialResponseMessage('mech', 'data');
|
||||
assert_1.default.deepEqual(actual, new buffer_list_1.default().addCString('mech').addInt32(4).addString('data').join(true, 'p'));
|
||||
});
|
||||
it('builds SCRAMClientFinalMessage message', function () {
|
||||
const actual = serializer_1.serialize.sendSCRAMClientFinalMessage('data');
|
||||
assert_1.default.deepEqual(actual, new buffer_list_1.default().addString('data').join(true, 'p'));
|
||||
});
|
||||
it('builds query message', function () {
|
||||
const txt = 'select * from boom';
|
||||
const actual = serializer_1.serialize.query(txt);
|
||||
assert_1.default.deepEqual(actual, new buffer_list_1.default().addCString(txt).join(true, 'Q'));
|
||||
});
|
||||
describe('parse message', () => {
|
||||
it('builds parse message', function () {
|
||||
const actual = serializer_1.serialize.parse({ text: '!' });
|
||||
const expected = new buffer_list_1.default().addCString('').addCString('!').addInt16(0).join(true, 'P');
|
||||
assert_1.default.deepEqual(actual, expected);
|
||||
});
|
||||
it('builds parse message with named query', function () {
|
||||
const actual = serializer_1.serialize.parse({
|
||||
name: 'boom',
|
||||
text: 'select * from boom',
|
||||
types: [],
|
||||
});
|
||||
const expected = new buffer_list_1.default().addCString('boom').addCString('select * from boom').addInt16(0).join(true, 'P');
|
||||
assert_1.default.deepEqual(actual, expected);
|
||||
});
|
||||
it('with multiple parameters', function () {
|
||||
const actual = serializer_1.serialize.parse({
|
||||
name: 'force',
|
||||
text: 'select * from bang where name = $1',
|
||||
types: [1, 2, 3, 4],
|
||||
});
|
||||
const expected = new buffer_list_1.default()
|
||||
.addCString('force')
|
||||
.addCString('select * from bang where name = $1')
|
||||
.addInt16(4)
|
||||
.addInt32(1)
|
||||
.addInt32(2)
|
||||
.addInt32(3)
|
||||
.addInt32(4)
|
||||
.join(true, 'P');
|
||||
assert_1.default.deepEqual(actual, expected);
|
||||
});
|
||||
});
|
||||
describe('bind messages', function () {
|
||||
it('with no values', function () {
|
||||
const actual = serializer_1.serialize.bind();
|
||||
const expectedBuffer = new buffer_list_1.default()
|
||||
.addCString('')
|
||||
.addCString('')
|
||||
.addInt16(0)
|
||||
.addInt16(0)
|
||||
.addInt16(1)
|
||||
.addInt16(0)
|
||||
.join(true, 'B');
|
||||
assert_1.default.deepEqual(actual, expectedBuffer);
|
||||
});
|
||||
it('with named statement, portal, and values', function () {
|
||||
const actual = serializer_1.serialize.bind({
|
||||
portal: 'bang',
|
||||
statement: 'woo',
|
||||
values: ['1', 'hi', null, 'zing'],
|
||||
});
|
||||
const expectedBuffer = new buffer_list_1.default()
|
||||
.addCString('bang') // portal name
|
||||
.addCString('woo') // statement name
|
||||
.addInt16(4)
|
||||
.addInt16(0)
|
||||
.addInt16(0)
|
||||
.addInt16(0)
|
||||
.addInt16(0)
|
||||
.addInt16(4)
|
||||
.addInt32(1)
|
||||
.add(Buffer.from('1'))
|
||||
.addInt32(2)
|
||||
.add(Buffer.from('hi'))
|
||||
.addInt32(-1)
|
||||
.addInt32(4)
|
||||
.add(Buffer.from('zing'))
|
||||
.addInt16(1)
|
||||
.addInt16(0)
|
||||
.join(true, 'B');
|
||||
assert_1.default.deepEqual(actual, expectedBuffer);
|
||||
});
|
||||
it('encodes a multi-byte string param with its UTF-8 byte length, not char length', function () {
|
||||
// Guards the single-pass addInt32PrefixedString write path: the Int32
|
||||
// length prefix must be the UTF-8 byte count, not String.length. 'héllo中🎉'
|
||||
// is 7 code points / 8 UTF-16 code units but 13 UTF-8 bytes.
|
||||
const value = 'héllo中🎉';
|
||||
const bytes = Buffer.from(value, 'utf8');
|
||||
assert_1.default.notEqual(bytes.length, value.length); // sanity: the divergence we're testing
|
||||
const actual = serializer_1.serialize.bind({ values: [value] });
|
||||
const expectedBuffer = new buffer_list_1.default()
|
||||
.addCString('') // portal
|
||||
.addCString('') // statement
|
||||
.addInt16(1) // param format code count
|
||||
.addInt16(0) // format code for the one value (text)
|
||||
.addInt16(1) // value count
|
||||
.addInt32(bytes.length) // 13 — the UTF-8 byte length, NOT value.length (8)
|
||||
.add(bytes)
|
||||
.addInt16(1) // result format code count
|
||||
.addInt16(0) // result format (text)
|
||||
.join(true, 'B');
|
||||
assert_1.default.deepEqual(actual, expectedBuffer);
|
||||
});
|
||||
});
|
||||
it('with custom valueMapper', function () {
|
||||
const actual = serializer_1.serialize.bind({
|
||||
portal: 'bang',
|
||||
statement: 'woo',
|
||||
values: ['1', 'hi', null, 'zing'],
|
||||
valueMapper: () => null,
|
||||
});
|
||||
const expectedBuffer = new buffer_list_1.default()
|
||||
.addCString('bang') // portal name
|
||||
.addCString('woo') // statement name
|
||||
.addInt16(4)
|
||||
.addInt16(0)
|
||||
.addInt16(0)
|
||||
.addInt16(0)
|
||||
.addInt16(0)
|
||||
.addInt16(4)
|
||||
.addInt32(-1)
|
||||
.addInt32(-1)
|
||||
.addInt32(-1)
|
||||
.addInt32(-1)
|
||||
.addInt16(1)
|
||||
.addInt16(0)
|
||||
.join(true, 'B');
|
||||
assert_1.default.deepEqual(actual, expectedBuffer);
|
||||
});
|
||||
it('with named statement, portal, and buffer value', function () {
|
||||
const actual = serializer_1.serialize.bind({
|
||||
portal: 'bang',
|
||||
statement: 'woo',
|
||||
values: ['1', 'hi', null, Buffer.from('zing', 'utf8')],
|
||||
});
|
||||
const expectedBuffer = new buffer_list_1.default()
|
||||
.addCString('bang') // portal name
|
||||
.addCString('woo') // statement name
|
||||
.addInt16(4) // value count
|
||||
.addInt16(0) // string
|
||||
.addInt16(0) // string
|
||||
.addInt16(0) // string
|
||||
.addInt16(1) // binary
|
||||
.addInt16(4)
|
||||
.addInt32(1)
|
||||
.add(Buffer.from('1'))
|
||||
.addInt32(2)
|
||||
.add(Buffer.from('hi'))
|
||||
.addInt32(-1)
|
||||
.addInt32(4)
|
||||
.add(Buffer.from('zing', 'utf-8'))
|
||||
.addInt16(1)
|
||||
.addInt16(0)
|
||||
.join(true, 'B');
|
||||
assert_1.default.deepEqual(actual, expectedBuffer);
|
||||
});
|
||||
describe('builds execute message', function () {
|
||||
it('for unamed portal with no row limit', function () {
|
||||
const actual = serializer_1.serialize.execute();
|
||||
const expectedBuffer = new buffer_list_1.default().addCString('').addInt32(0).join(true, 'E');
|
||||
assert_1.default.deepEqual(actual, expectedBuffer);
|
||||
});
|
||||
it('for named portal with row limit', function () {
|
||||
const actual = serializer_1.serialize.execute({
|
||||
portal: 'my favorite portal',
|
||||
rows: 100,
|
||||
});
|
||||
const expectedBuffer = new buffer_list_1.default().addCString('my favorite portal').addInt32(100).join(true, 'E');
|
||||
assert_1.default.deepEqual(actual, expectedBuffer);
|
||||
});
|
||||
});
|
||||
it('builds flush command', function () {
|
||||
const actual = serializer_1.serialize.flush();
|
||||
const expected = new buffer_list_1.default().join(true, 'H');
|
||||
assert_1.default.deepEqual(actual, expected);
|
||||
});
|
||||
it('builds sync command', function () {
|
||||
const actual = serializer_1.serialize.sync();
|
||||
const expected = new buffer_list_1.default().join(true, 'S');
|
||||
assert_1.default.deepEqual(actual, expected);
|
||||
});
|
||||
it('builds end command', function () {
|
||||
const actual = serializer_1.serialize.end();
|
||||
const expected = Buffer.from([0x58, 0, 0, 0, 4]);
|
||||
assert_1.default.deepEqual(actual, expected);
|
||||
});
|
||||
describe('builds describe command', function () {
|
||||
it('describe statement', function () {
|
||||
const actual = serializer_1.serialize.describe({ type: 'S', name: 'bang' });
|
||||
const expected = new buffer_list_1.default().addChar('S').addCString('bang').join(true, 'D');
|
||||
assert_1.default.deepEqual(actual, expected);
|
||||
});
|
||||
it('describe unnamed portal', function () {
|
||||
const actual = serializer_1.serialize.describe({ type: 'P' });
|
||||
const expected = new buffer_list_1.default().addChar('P').addCString('').join(true, 'D');
|
||||
assert_1.default.deepEqual(actual, expected);
|
||||
});
|
||||
});
|
||||
describe('builds close command', function () {
|
||||
it('describe statement', function () {
|
||||
const actual = serializer_1.serialize.close({ type: 'S', name: 'bang' });
|
||||
const expected = new buffer_list_1.default().addChar('S').addCString('bang').join(true, 'C');
|
||||
assert_1.default.deepEqual(actual, expected);
|
||||
});
|
||||
it('describe unnamed portal', function () {
|
||||
const actual = serializer_1.serialize.close({ type: 'P' });
|
||||
const expected = new buffer_list_1.default().addChar('P').addCString('').join(true, 'C');
|
||||
assert_1.default.deepEqual(actual, expected);
|
||||
});
|
||||
});
|
||||
describe('copy messages', function () {
|
||||
it('builds copyFromChunk', () => {
|
||||
const actual = serializer_1.serialize.copyData(Buffer.from([1, 2, 3]));
|
||||
const expected = new buffer_list_1.default().add(Buffer.from([1, 2, 3])).join(true, 'd');
|
||||
assert_1.default.deepEqual(actual, expected);
|
||||
});
|
||||
it('builds copy fail', () => {
|
||||
const actual = serializer_1.serialize.copyFail('err!');
|
||||
const expected = new buffer_list_1.default().addCString('err!').join(true, 'f');
|
||||
assert_1.default.deepEqual(actual, expected);
|
||||
});
|
||||
it('builds copy done', () => {
|
||||
const actual = serializer_1.serialize.copyDone();
|
||||
const expected = new buffer_list_1.default().join(true, 'c');
|
||||
assert_1.default.deepEqual(actual, expected);
|
||||
});
|
||||
});
|
||||
it('builds cancel message', () => {
|
||||
const actual = serializer_1.serialize.cancel(3, 4);
|
||||
const expected = new buffer_list_1.default().addInt16(1234).addInt16(5678).addInt32(3).addInt32(4).join(true);
|
||||
assert_1.default.deepEqual(actual, expected);
|
||||
});
|
||||
describe('bind error recovery', () => {
|
||||
const throwingMapper = () => {
|
||||
throw new Error('valueMapper error');
|
||||
};
|
||||
it('produces correct bind output after a valueMapper exception', () => {
|
||||
assert_1.default.throws(() => {
|
||||
serializer_1.serialize.bind({
|
||||
values: ['fail'],
|
||||
valueMapper: throwingMapper,
|
||||
});
|
||||
}, /valueMapper error/);
|
||||
const actual = serializer_1.serialize.bind({
|
||||
portal: 'bang',
|
||||
statement: 'woo',
|
||||
values: ['1', 'hi', null, 'zing'],
|
||||
});
|
||||
const expectedBuffer = new buffer_list_1.default()
|
||||
.addCString('bang')
|
||||
.addCString('woo')
|
||||
.addInt16(4)
|
||||
.addInt16(0)
|
||||
.addInt16(0)
|
||||
.addInt16(0)
|
||||
.addInt16(0)
|
||||
.addInt16(4)
|
||||
.addInt32(1)
|
||||
.add(Buffer.from('1'))
|
||||
.addInt32(2)
|
||||
.add(Buffer.from('hi'))
|
||||
.addInt32(-1)
|
||||
.addInt32(4)
|
||||
.add(Buffer.from('zing'))
|
||||
.addInt16(1)
|
||||
.addInt16(0)
|
||||
.join(true, 'B');
|
||||
assert_1.default.deepEqual(actual, expectedBuffer);
|
||||
});
|
||||
it('produces correct output from other serializer methods after a failed bind', () => {
|
||||
assert_1.default.throws(() => {
|
||||
serializer_1.serialize.bind({
|
||||
values: ['fail'],
|
||||
valueMapper: throwingMapper,
|
||||
});
|
||||
}, /valueMapper error/);
|
||||
const parseActual = serializer_1.serialize.parse({ text: '!' });
|
||||
const parseExpected = new buffer_list_1.default().addCString('').addCString('!').addInt16(0).join(true, 'P');
|
||||
assert_1.default.deepEqual(parseActual, parseExpected);
|
||||
const queryActual = serializer_1.serialize.query('select 1');
|
||||
const queryExpected = new buffer_list_1.default().addCString('select 1').join(true, 'Q');
|
||||
assert_1.default.deepEqual(queryActual, queryExpected);
|
||||
});
|
||||
});
|
||||
});
|
||||
//# sourceMappingURL=outbound-serializer.test.js.map
|
||||
@@ -0,0 +1 @@
|
||||
export { SourceNode } from '..';
|
||||
@@ -0,0 +1,29 @@
|
||||
"use strict";
|
||||
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
||||
if (k2 === undefined) k2 = k;
|
||||
var desc = Object.getOwnPropertyDescriptor(m, k);
|
||||
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
||||
desc = { enumerable: true, get: function() { return m[k]; } };
|
||||
}
|
||||
Object.defineProperty(o, k2, desc);
|
||||
}) : (function(o, m, k, k2) {
|
||||
if (k2 === undefined) k2 = k;
|
||||
o[k2] = m[k];
|
||||
}));
|
||||
var __exportStar = (this && this.__exportStar) || function(m, exports) {
|
||||
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.getCanonicalFileName = exports.typescriptVersionIsAtLeast = exports.SUPPORTED_TYPESCRIPT_VERSIONS = void 0;
|
||||
// required by website
|
||||
__exportStar(require("./ast-converter"), exports);
|
||||
__exportStar(require("./create-program/getScriptKind"), exports);
|
||||
var warnAboutTSVersion_1 = require("./parseSettings/warnAboutTSVersion");
|
||||
Object.defineProperty(exports, "SUPPORTED_TYPESCRIPT_VERSIONS", { enumerable: true, get: function () { return warnAboutTSVersion_1.SUPPORTED_TYPESCRIPT_VERSIONS; } });
|
||||
// required by packages/utils/src/ts-estree.ts
|
||||
__exportStar(require("./getModifiers"), exports);
|
||||
var version_check_1 = require("./version-check");
|
||||
Object.defineProperty(exports, "typescriptVersionIsAtLeast", { enumerable: true, get: function () { return version_check_1.typescriptVersionIsAtLeast; } });
|
||||
// required by packages/type-utils
|
||||
var shared_1 = require("./create-program/shared");
|
||||
Object.defineProperty(exports, "getCanonicalFileName", { enumerable: true, get: function () { return shared_1.getCanonicalFileName; } });
|
||||
@@ -0,0 +1,123 @@
|
||||
import type { $ZodStringFormats } from "../core/checks.js";
|
||||
import type * as errors from "../core/errors.js";
|
||||
import * as util from "../core/util.js";
|
||||
|
||||
const error: () => errors.$ZodErrorMap = () => {
|
||||
const Sizable: Record<string, { unit: string; verb: string }> = {
|
||||
string: { unit: "tegn", verb: "havde" },
|
||||
file: { unit: "bytes", verb: "havde" },
|
||||
array: { unit: "elementer", verb: "indeholdt" },
|
||||
set: { unit: "elementer", verb: "indeholdt" },
|
||||
};
|
||||
|
||||
function getSizing(origin: string): { unit: string; verb: string } | null {
|
||||
return Sizable[origin] ?? null;
|
||||
}
|
||||
|
||||
const FormatDictionary: {
|
||||
[k in $ZodStringFormats | (string & {})]?: string;
|
||||
} = {
|
||||
regex: "input",
|
||||
email: "e-mailadresse",
|
||||
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 dato- og klokkeslæt",
|
||||
date: "ISO-dato",
|
||||
time: "ISO-klokkeslæt",
|
||||
duration: "ISO-varighed",
|
||||
ipv4: "IPv4-område",
|
||||
ipv6: "IPv6-område",
|
||||
cidrv4: "IPv4-spektrum",
|
||||
cidrv6: "IPv6-spektrum",
|
||||
base64: "base64-kodet streng",
|
||||
base64url: "base64url-kodet streng",
|
||||
json_string: "JSON-streng",
|
||||
e164: "E.164-nummer",
|
||||
jwt: "JWT",
|
||||
template_literal: "input",
|
||||
};
|
||||
|
||||
const TypeDictionary: {
|
||||
[k in errors.$ZodInvalidTypeExpected | (string & {})]?: string;
|
||||
} = {
|
||||
nan: "NaN",
|
||||
string: "streng",
|
||||
number: "tal",
|
||||
boolean: "boolean",
|
||||
array: "liste",
|
||||
object: "objekt",
|
||||
set: "sæt",
|
||||
file: "fil",
|
||||
};
|
||||
|
||||
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;
|
||||
if (/^[A-Z]/.test(issue.expected)) {
|
||||
return `Ugyldigt input: forventede instanceof ${issue.expected}, fik ${received}`;
|
||||
}
|
||||
return `Ugyldigt input: forventede ${expected}, fik ${received}`;
|
||||
}
|
||||
case "invalid_value":
|
||||
if (issue.values.length === 1) return `Ugyldig værdi: forventede ${util.stringifyPrimitive(issue.values[0])}`;
|
||||
return `Ugyldigt valg: forventede en af følgende ${util.joinValues(issue.values, "|")}`;
|
||||
case "too_big": {
|
||||
const adj = issue.inclusive ? "<=" : "<";
|
||||
const sizing = getSizing(issue.origin);
|
||||
const origin = TypeDictionary[issue.origin] ?? issue.origin;
|
||||
if (sizing)
|
||||
return `For stor: forventede ${origin ?? "value"} ${sizing.verb} ${adj} ${issue.maximum.toString()} ${sizing.unit ?? "elementer"}`;
|
||||
return `For stor: forventede ${origin ?? "value"} havde ${adj} ${issue.maximum.toString()}`;
|
||||
}
|
||||
case "too_small": {
|
||||
const adj = issue.inclusive ? ">=" : ">";
|
||||
const sizing = getSizing(issue.origin);
|
||||
const origin = TypeDictionary[issue.origin] ?? issue.origin;
|
||||
if (sizing) {
|
||||
return `For lille: forventede ${origin} ${sizing.verb} ${adj} ${issue.minimum.toString()} ${sizing.unit}`;
|
||||
}
|
||||
|
||||
return `For lille: forventede ${origin} havde ${adj} ${issue.minimum.toString()}`;
|
||||
}
|
||||
case "invalid_format": {
|
||||
const _issue = issue as errors.$ZodStringFormatIssues;
|
||||
if (_issue.format === "starts_with") return `Ugyldig streng: skal starte med "${_issue.prefix}"`;
|
||||
if (_issue.format === "ends_with") return `Ugyldig streng: skal ende med "${_issue.suffix}"`;
|
||||
if (_issue.format === "includes") return `Ugyldig streng: skal indeholde "${_issue.includes}"`;
|
||||
if (_issue.format === "regex") return `Ugyldig streng: skal matche mønsteret ${_issue.pattern}`;
|
||||
return `Ugyldig ${FormatDictionary[_issue.format] ?? issue.format}`;
|
||||
}
|
||||
case "not_multiple_of":
|
||||
return `Ugyldigt tal: skal være deleligt med ${issue.divisor}`;
|
||||
case "unrecognized_keys":
|
||||
return `${issue.keys.length > 1 ? "Ukendte nøgler" : "Ukendt nøgle"}: ${util.joinValues(issue.keys, ", ")}`;
|
||||
case "invalid_key":
|
||||
return `Ugyldig nøgle i ${issue.origin}`;
|
||||
case "invalid_union":
|
||||
return "Ugyldigt input: matcher ingen af de tilladte typer";
|
||||
case "invalid_element":
|
||||
return `Ugyldig værdi i ${issue.origin}`;
|
||||
default:
|
||||
return `Ugyldigt input`;
|
||||
}
|
||||
};
|
||||
};
|
||||
|
||||
export default function (): { localeError: errors.$ZodErrorMap } {
|
||||
return {
|
||||
localeError: error(),
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
'use strict'
|
||||
|
||||
const { test } = require('node:test')
|
||||
const { createWarning } = require('..')
|
||||
const { withResolvers } = require('./promise')
|
||||
|
||||
test('Must not overwrite config', t => {
|
||||
t.plan(1)
|
||||
|
||||
function onWarning (warning) {
|
||||
t.assert.deepStrictEqual(warning.code, 'CODE_1')
|
||||
}
|
||||
|
||||
const a = createWarning({
|
||||
name: 'TestWarning',
|
||||
code: 'CODE_1',
|
||||
message: 'Msg'
|
||||
})
|
||||
createWarning({
|
||||
name: 'TestWarning',
|
||||
code: 'CODE_2',
|
||||
message: 'Msg',
|
||||
unlimited: true
|
||||
})
|
||||
|
||||
const { promise, resolve } = withResolvers()
|
||||
|
||||
process.on('warning', onWarning)
|
||||
a('CODE_1')
|
||||
a('CODE_1')
|
||||
|
||||
setImmediate(() => {
|
||||
process.removeListener('warning', onWarning)
|
||||
resolve()
|
||||
})
|
||||
|
||||
return promise
|
||||
})
|
||||
@@ -0,0 +1,33 @@
|
||||
'use strict'
|
||||
|
||||
process.env.TZ = 'UTC'
|
||||
|
||||
const { describe, test } = require('node:test')
|
||||
const _prettyFactory = require('../').prettyFactory
|
||||
|
||||
function prettyFactory (opts) {
|
||||
if (!opts) {
|
||||
opts = { colorize: false }
|
||||
} else if (!Object.prototype.hasOwnProperty.call(opts, 'colorize')) {
|
||||
opts.colorize = false
|
||||
}
|
||||
return _prettyFactory(opts)
|
||||
}
|
||||
|
||||
const logLine = '{"level":30,"time":1522431328992,"msg":"hello world","pid":42,"hostname":"foo"}\n'
|
||||
|
||||
describe('crlf', () => {
|
||||
test('uses LF by default', (t) => {
|
||||
t.plan(1)
|
||||
const pretty = prettyFactory()
|
||||
const formatted = pretty(logLine)
|
||||
t.assert.strictEqual(formatted.substr(-2), 'd\n')
|
||||
})
|
||||
|
||||
test('can use CRLF', (t) => {
|
||||
t.plan(1)
|
||||
const pretty = prettyFactory({ crlf: true })
|
||||
const formatted = pretty(logLine)
|
||||
t.assert.strictEqual(formatted.substr(-3), 'd\r\n')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,171 @@
|
||||
// @ts-ignore TS6133
|
||||
import { expect, test } from "vitest";
|
||||
|
||||
import * as z from "zod/v3";
|
||||
import { util } from "../helpers/util.js";
|
||||
|
||||
const booleanRecord = z.record(z.boolean());
|
||||
type booleanRecord = z.infer<typeof booleanRecord>;
|
||||
|
||||
const recordWithEnumKeys = z.record(z.enum(["Tuna", "Salmon"]), z.string());
|
||||
type recordWithEnumKeys = z.infer<typeof recordWithEnumKeys>;
|
||||
|
||||
const recordWithLiteralKeys = z.record(z.union([z.literal("Tuna"), z.literal("Salmon")]), z.string());
|
||||
type recordWithLiteralKeys = z.infer<typeof recordWithLiteralKeys>;
|
||||
|
||||
test("type inference", () => {
|
||||
util.assertEqual<booleanRecord, Record<string, boolean>>(true);
|
||||
|
||||
util.assertEqual<recordWithEnumKeys, Partial<Record<"Tuna" | "Salmon", string>>>(true);
|
||||
|
||||
util.assertEqual<recordWithLiteralKeys, Partial<Record<"Tuna" | "Salmon", string>>>(true);
|
||||
});
|
||||
|
||||
test("methods", () => {
|
||||
booleanRecord.optional();
|
||||
booleanRecord.nullable();
|
||||
});
|
||||
|
||||
test("string record parse - pass", () => {
|
||||
booleanRecord.parse({
|
||||
k1: true,
|
||||
k2: false,
|
||||
1234: false,
|
||||
});
|
||||
});
|
||||
|
||||
test("string record parse - fail", () => {
|
||||
const badCheck = () =>
|
||||
booleanRecord.parse({
|
||||
asdf: 1234,
|
||||
} as any);
|
||||
expect(badCheck).toThrow();
|
||||
|
||||
expect(() => booleanRecord.parse("asdf")).toThrow();
|
||||
});
|
||||
|
||||
test("string record parse - fail", () => {
|
||||
const badCheck = () =>
|
||||
booleanRecord.parse({
|
||||
asdf: {},
|
||||
} as any);
|
||||
expect(badCheck).toThrow();
|
||||
});
|
||||
|
||||
test("string record parse - fail", () => {
|
||||
const badCheck = () =>
|
||||
booleanRecord.parse({
|
||||
asdf: [],
|
||||
} as any);
|
||||
expect(badCheck).toThrow();
|
||||
});
|
||||
|
||||
test("key schema", () => {
|
||||
const result1 = recordWithEnumKeys.parse({
|
||||
Tuna: "asdf",
|
||||
Salmon: "asdf",
|
||||
});
|
||||
expect(result1).toEqual({
|
||||
Tuna: "asdf",
|
||||
Salmon: "asdf",
|
||||
});
|
||||
|
||||
const result2 = recordWithLiteralKeys.parse({
|
||||
Tuna: "asdf",
|
||||
Salmon: "asdf",
|
||||
});
|
||||
expect(result2).toEqual({
|
||||
Tuna: "asdf",
|
||||
Salmon: "asdf",
|
||||
});
|
||||
|
||||
// shouldn't require us to specify all props in record
|
||||
const result3 = recordWithEnumKeys.parse({
|
||||
Tuna: "abcd",
|
||||
});
|
||||
expect(result3).toEqual({
|
||||
Tuna: "abcd",
|
||||
});
|
||||
|
||||
// shouldn't require us to specify all props in record
|
||||
const result4 = recordWithLiteralKeys.parse({
|
||||
Salmon: "abcd",
|
||||
});
|
||||
expect(result4).toEqual({
|
||||
Salmon: "abcd",
|
||||
});
|
||||
|
||||
expect(() =>
|
||||
recordWithEnumKeys.parse({
|
||||
Tuna: "asdf",
|
||||
Salmon: "asdf",
|
||||
Trout: "asdf",
|
||||
})
|
||||
).toThrow();
|
||||
|
||||
expect(() =>
|
||||
recordWithLiteralKeys.parse({
|
||||
Tuna: "asdf",
|
||||
Salmon: "asdf",
|
||||
|
||||
Trout: "asdf",
|
||||
})
|
||||
).toThrow();
|
||||
});
|
||||
|
||||
// test("record element", () => {
|
||||
// expect(booleanRecord.element).toBeInstanceOf(z.ZodBoolean);
|
||||
// });
|
||||
|
||||
test("key and value getters", () => {
|
||||
const rec = z.record(z.string(), z.number());
|
||||
|
||||
rec.keySchema.parse("asdf");
|
||||
rec.valueSchema.parse(1234);
|
||||
rec.element.parse(1234);
|
||||
});
|
||||
|
||||
test("is not vulnerable to prototype pollution", async () => {
|
||||
const rec = z.record(
|
||||
z.object({
|
||||
a: z.string(),
|
||||
})
|
||||
);
|
||||
|
||||
const data = JSON.parse(`
|
||||
{
|
||||
"__proto__": {
|
||||
"a": "evil"
|
||||
},
|
||||
"b": {
|
||||
"a": "good"
|
||||
}
|
||||
}
|
||||
`);
|
||||
|
||||
const obj1 = rec.parse(data);
|
||||
expect(obj1.a).toBeUndefined();
|
||||
|
||||
const obj2 = rec.safeParse(data);
|
||||
expect(obj2.success).toBe(true);
|
||||
if (obj2.success) {
|
||||
expect(obj2.data.a).toBeUndefined();
|
||||
}
|
||||
|
||||
const obj3 = await rec.parseAsync(data);
|
||||
expect(obj3.a).toBeUndefined();
|
||||
|
||||
const obj4 = await rec.safeParseAsync(data);
|
||||
expect(obj4.success).toBe(true);
|
||||
if (obj4.success) {
|
||||
expect(obj4.data.a).toBeUndefined();
|
||||
}
|
||||
});
|
||||
|
||||
test("dont parse undefined values", () => {
|
||||
const result1 = z.record(z.any()).parse({ foo: undefined });
|
||||
|
||||
expect(result1).toEqual({
|
||||
foo: undefined,
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,176 @@
|
||||
import type { IssueData, ZodErrorMap, ZodIssue } from "../ZodError.js";
|
||||
import { getErrorMap } from "../errors.js";
|
||||
import defaultErrorMap from "../locales/en.js";
|
||||
import type { ZodParsedType } from "./util.js";
|
||||
|
||||
export const makeIssue = (params: {
|
||||
data: any;
|
||||
path: (string | number)[];
|
||||
errorMaps: ZodErrorMap[];
|
||||
issueData: IssueData;
|
||||
}): ZodIssue => {
|
||||
const { data, path, errorMaps, issueData } = params;
|
||||
const fullPath = [...path, ...(issueData.path || [])];
|
||||
const fullIssue = {
|
||||
...issueData,
|
||||
path: fullPath,
|
||||
};
|
||||
|
||||
if (issueData.message !== undefined) {
|
||||
return {
|
||||
...issueData,
|
||||
path: fullPath,
|
||||
message: issueData.message,
|
||||
};
|
||||
}
|
||||
|
||||
let errorMessage = "";
|
||||
const maps = errorMaps
|
||||
.filter((m) => !!m)
|
||||
.slice()
|
||||
.reverse();
|
||||
for (const map of maps) {
|
||||
errorMessage = map(fullIssue, { data, defaultError: errorMessage }).message;
|
||||
}
|
||||
|
||||
return {
|
||||
...issueData,
|
||||
path: fullPath,
|
||||
message: errorMessage,
|
||||
};
|
||||
};
|
||||
|
||||
export type ParseParams = {
|
||||
path: (string | number)[];
|
||||
errorMap: ZodErrorMap;
|
||||
async: boolean;
|
||||
};
|
||||
|
||||
export type ParsePathComponent = string | number;
|
||||
export type ParsePath = ParsePathComponent[];
|
||||
export const EMPTY_PATH: ParsePath = [];
|
||||
|
||||
export interface ParseContext {
|
||||
readonly common: {
|
||||
readonly issues: ZodIssue[];
|
||||
readonly contextualErrorMap?: ZodErrorMap | undefined;
|
||||
readonly async: boolean;
|
||||
};
|
||||
readonly path: ParsePath;
|
||||
readonly schemaErrorMap?: ZodErrorMap | undefined;
|
||||
readonly parent: ParseContext | null;
|
||||
readonly data: any;
|
||||
readonly parsedType: ZodParsedType;
|
||||
}
|
||||
|
||||
export type ParseInput = {
|
||||
data: any;
|
||||
path: (string | number)[];
|
||||
parent: ParseContext;
|
||||
};
|
||||
|
||||
export function addIssueToContext(ctx: ParseContext, issueData: IssueData): void {
|
||||
const overrideMap = getErrorMap();
|
||||
const issue = makeIssue({
|
||||
issueData: issueData,
|
||||
data: ctx.data,
|
||||
path: ctx.path,
|
||||
errorMaps: [
|
||||
ctx.common.contextualErrorMap, // contextual error map is first priority
|
||||
ctx.schemaErrorMap, // then schema-bound map if available
|
||||
overrideMap, // then global override map
|
||||
overrideMap === defaultErrorMap ? undefined : defaultErrorMap, // then global default map
|
||||
].filter((x) => !!x),
|
||||
});
|
||||
ctx.common.issues.push(issue);
|
||||
}
|
||||
|
||||
export type ObjectPair = {
|
||||
key: SyncParseReturnType<any>;
|
||||
value: SyncParseReturnType<any>;
|
||||
};
|
||||
export class ParseStatus {
|
||||
value: "aborted" | "dirty" | "valid" = "valid";
|
||||
dirty(): void {
|
||||
if (this.value === "valid") this.value = "dirty";
|
||||
}
|
||||
abort(): void {
|
||||
if (this.value !== "aborted") this.value = "aborted";
|
||||
}
|
||||
|
||||
static mergeArray(status: ParseStatus, results: SyncParseReturnType<any>[]): SyncParseReturnType {
|
||||
const arrayValue: any[] = [];
|
||||
for (const s of results) {
|
||||
if (s.status === "aborted") return INVALID;
|
||||
if (s.status === "dirty") status.dirty();
|
||||
arrayValue.push(s.value);
|
||||
}
|
||||
|
||||
return { status: status.value, value: arrayValue };
|
||||
}
|
||||
|
||||
static async mergeObjectAsync(
|
||||
status: ParseStatus,
|
||||
pairs: { key: ParseReturnType<any>; value: ParseReturnType<any> }[]
|
||||
): Promise<SyncParseReturnType<any>> {
|
||||
const syncPairs: ObjectPair[] = [];
|
||||
for (const pair of pairs) {
|
||||
const key = await pair.key;
|
||||
const value = await pair.value;
|
||||
syncPairs.push({
|
||||
key,
|
||||
value,
|
||||
});
|
||||
}
|
||||
return ParseStatus.mergeObjectSync(status, syncPairs);
|
||||
}
|
||||
|
||||
static mergeObjectSync(
|
||||
status: ParseStatus,
|
||||
pairs: {
|
||||
key: SyncParseReturnType<any>;
|
||||
value: SyncParseReturnType<any>;
|
||||
alwaysSet?: boolean;
|
||||
}[]
|
||||
): SyncParseReturnType {
|
||||
const finalObject: any = {};
|
||||
for (const pair of pairs) {
|
||||
const { key, value } = pair;
|
||||
if (key.status === "aborted") return INVALID;
|
||||
if (value.status === "aborted") return INVALID;
|
||||
if (key.status === "dirty") status.dirty();
|
||||
if (value.status === "dirty") status.dirty();
|
||||
|
||||
if (key.value !== "__proto__" && (typeof value.value !== "undefined" || pair.alwaysSet)) {
|
||||
finalObject[key.value] = value.value;
|
||||
}
|
||||
}
|
||||
|
||||
return { status: status.value, value: finalObject };
|
||||
}
|
||||
}
|
||||
export interface ParseResult {
|
||||
status: "aborted" | "dirty" | "valid";
|
||||
data: any;
|
||||
}
|
||||
|
||||
export type INVALID = { status: "aborted" };
|
||||
export const INVALID: INVALID = Object.freeze({
|
||||
status: "aborted",
|
||||
});
|
||||
|
||||
export type DIRTY<T> = { status: "dirty"; value: T };
|
||||
export const DIRTY = <T>(value: T): DIRTY<T> => ({ status: "dirty", value });
|
||||
|
||||
export type OK<T> = { status: "valid"; value: T };
|
||||
export const OK = <T>(value: T): OK<T> => ({ status: "valid", value });
|
||||
|
||||
export type SyncParseReturnType<T = any> = OK<T> | DIRTY<T> | INVALID;
|
||||
export type AsyncParseReturnType<T> = Promise<SyncParseReturnType<T>>;
|
||||
export type ParseReturnType<T> = SyncParseReturnType<T> | AsyncParseReturnType<T>;
|
||||
|
||||
export const isAborted = (x: ParseReturnType<any>): x is INVALID => (x as any).status === "aborted";
|
||||
export const isDirty = <T>(x: ParseReturnType<T>): x is OK<T> | DIRTY<T> => (x as any).status === "dirty";
|
||||
export const isValid = <T>(x: ParseReturnType<T>): x is OK<T> => (x as any).status === "valid";
|
||||
export const isAsync = <T>(x: ParseReturnType<T>): x is AsyncParseReturnType<T> =>
|
||||
typeof Promise !== "undefined" && x instanceof Promise;
|
||||
@@ -0,0 +1,13 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.ImplicitGlobalVariableDefinition = void 0;
|
||||
const DefinitionBase_1 = require("./DefinitionBase");
|
||||
const DefinitionType_1 = require("./DefinitionType");
|
||||
class ImplicitGlobalVariableDefinition extends DefinitionBase_1.DefinitionBase {
|
||||
isTypeDefinition = false;
|
||||
isVariableDefinition = true;
|
||||
constructor(name, node) {
|
||||
super(DefinitionType_1.DefinitionType.ImplicitGlobalVariable, name, node, null);
|
||||
}
|
||||
}
|
||||
exports.ImplicitGlobalVariableDefinition = ImplicitGlobalVariableDefinition;
|
||||
@@ -0,0 +1,24 @@
|
||||
<a id="Systemd"></a>
|
||||
## Systemd example
|
||||
|
||||
If you run your Node.js process via [Systemd](https://www.freedesktop.org/wiki/Software/systemd/) and you examine your logs with [journalctl](https://www.freedesktop.org/software/systemd/man/journalctl.html) some data will be duplicated. You can use a combination of `journalctl` options and `pino-pretty` options to shape the output.
|
||||
|
||||
For example viewing the prettified logs of a process named `monitor` with `journalctl -u monitor -f | pino-pretty`, might output something like this:
|
||||
|
||||
```
|
||||
Apr 24 07:40:01 nanopi node[6080]: {"level":30,"time":1587706801902,"pid":6080,"hostname":"nanopi","msg":"TT
|
||||
21","v":1}
|
||||
```
|
||||
As you can see, the timestamp, hostname, and pid are duplicated.
|
||||
If you just want the bare prettified Pino logs you can strip out the duplicate items from the `journalctl` output with the `-o cat` option of `journalctl`:
|
||||
```
|
||||
journalctl -u monitor -f -o cat | pino-pretty
|
||||
```
|
||||
the output now looks something like this:
|
||||
```
|
||||
[1587706801902] INFO (6080 on nanopi): TT 21
|
||||
```
|
||||
Make the output even more human readable by using the pino-pretty options `-t` to format the timestamp and `-i pid, hostname` to filter out hostname and pid:
|
||||
```
|
||||
[2020-04-24 05:42:24.836 +0000] INFO : TT 21
|
||||
```
|
||||
@@ -0,0 +1,460 @@
|
||||
/******************************************************************************
|
||||
Copyright (c) Microsoft Corporation.
|
||||
|
||||
Permission to use, copy, modify, and/or distribute this software for any
|
||||
purpose with or without fee is hereby granted.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
|
||||
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
|
||||
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
|
||||
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
|
||||
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
|
||||
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
|
||||
PERFORMANCE OF THIS SOFTWARE.
|
||||
***************************************************************************** */
|
||||
|
||||
/**
|
||||
* Used to shim class extends.
|
||||
*
|
||||
* @param d The derived class.
|
||||
* @param b The base class.
|
||||
*/
|
||||
export declare function __extends(d: Function, b: Function): void;
|
||||
|
||||
/**
|
||||
* Copy the values of all of the enumerable own properties from one or more source objects to a
|
||||
* target object. Returns the target object.
|
||||
*
|
||||
* @param t The target object to copy to.
|
||||
* @param sources One or more source objects from which to copy properties
|
||||
*/
|
||||
export declare function __assign(t: any, ...sources: any[]): any;
|
||||
|
||||
/**
|
||||
* Performs a rest spread on an object.
|
||||
*
|
||||
* @param t The source value.
|
||||
* @param propertyNames The property names excluded from the rest spread.
|
||||
*/
|
||||
export declare function __rest(t: any, propertyNames: (string | symbol)[]): any;
|
||||
|
||||
/**
|
||||
* Applies decorators to a target object
|
||||
*
|
||||
* @param decorators The set of decorators to apply.
|
||||
* @param target The target object.
|
||||
* @param key If specified, the own property to apply the decorators to.
|
||||
* @param desc The property descriptor, defaults to fetching the descriptor from the target object.
|
||||
* @experimental
|
||||
*/
|
||||
export declare function __decorate(decorators: Function[], target: any, key?: string | symbol, desc?: any): any;
|
||||
|
||||
/**
|
||||
* Creates an observing function decorator from a parameter decorator.
|
||||
*
|
||||
* @param paramIndex The parameter index to apply the decorator to.
|
||||
* @param decorator The parameter decorator to apply. Note that the return value is ignored.
|
||||
* @experimental
|
||||
*/
|
||||
export declare function __param(paramIndex: number, decorator: Function): Function;
|
||||
|
||||
/**
|
||||
* Applies decorators to a class or class member, following the native ECMAScript decorator specification.
|
||||
* @param ctor For non-field class members, the class constructor. Otherwise, `null`.
|
||||
* @param descriptorIn The `PropertyDescriptor` to use when unable to look up the property from `ctor`.
|
||||
* @param decorators The decorators to apply
|
||||
* @param contextIn The `DecoratorContext` to clone for each decorator application.
|
||||
* @param initializers An array of field initializer mutation functions into which new initializers are written.
|
||||
* @param extraInitializers An array of extra initializer functions into which new initializers are written.
|
||||
*/
|
||||
export declare function __esDecorate(ctor: Function | null, descriptorIn: object | null, decorators: Function[], contextIn: object, initializers: Function[] | null, extraInitializers: Function[]): void;
|
||||
|
||||
/**
|
||||
* Runs field initializers or extra initializers generated by `__esDecorate`.
|
||||
* @param thisArg The `this` argument to use.
|
||||
* @param initializers The array of initializers to evaluate.
|
||||
* @param value The initial value to pass to the initializers.
|
||||
*/
|
||||
export declare function __runInitializers(thisArg: unknown, initializers: Function[], value?: any): any;
|
||||
|
||||
/**
|
||||
* Converts a computed property name into a `string` or `symbol` value.
|
||||
*/
|
||||
export declare function __propKey(x: any): string | symbol;
|
||||
|
||||
/**
|
||||
* Assigns the name of a function derived from the left-hand side of an assignment.
|
||||
* @param f The function to rename.
|
||||
* @param name The new name for the function.
|
||||
* @param prefix A prefix (such as `"get"` or `"set"`) to insert before the name.
|
||||
*/
|
||||
export declare function __setFunctionName(f: Function, name: string | symbol, prefix?: string): Function;
|
||||
|
||||
/**
|
||||
* Creates a decorator that sets metadata.
|
||||
*
|
||||
* @param metadataKey The metadata key
|
||||
* @param metadataValue The metadata value
|
||||
* @experimental
|
||||
*/
|
||||
export declare function __metadata(metadataKey: any, metadataValue: any): Function;
|
||||
|
||||
/**
|
||||
* Converts a generator function into a pseudo-async function, by treating each `yield` as an `await`.
|
||||
*
|
||||
* @param thisArg The reference to use as the `this` value in the generator function
|
||||
* @param _arguments The optional arguments array
|
||||
* @param P The optional promise constructor argument, defaults to the `Promise` property of the global object.
|
||||
* @param generator The generator function
|
||||
*/
|
||||
export declare function __awaiter(thisArg: any, _arguments: any, P: Function, generator: Function): any;
|
||||
|
||||
/**
|
||||
* Creates an Iterator object using the body as the implementation.
|
||||
*
|
||||
* @param thisArg The reference to use as the `this` value in the function
|
||||
* @param body The generator state-machine based implementation.
|
||||
*
|
||||
* @see [./docs/generator.md]
|
||||
*/
|
||||
export declare function __generator(thisArg: any, body: Function): any;
|
||||
|
||||
/**
|
||||
* Creates bindings for all enumerable properties of `m` on `exports`
|
||||
*
|
||||
* @param m The source object
|
||||
* @param o The `exports` object.
|
||||
*/
|
||||
export declare function __exportStar(m: any, o: any): void;
|
||||
|
||||
/**
|
||||
* Creates a value iterator from an `Iterable` or `ArrayLike` object.
|
||||
*
|
||||
* @param o The object.
|
||||
* @throws {TypeError} If `o` is neither `Iterable`, nor an `ArrayLike`.
|
||||
*/
|
||||
export declare function __values(o: any): any;
|
||||
|
||||
/**
|
||||
* Reads values from an `Iterable` or `ArrayLike` object and returns the resulting array.
|
||||
*
|
||||
* @param o The object to read from.
|
||||
* @param n The maximum number of arguments to read, defaults to `Infinity`.
|
||||
*/
|
||||
export declare function __read(o: any, n?: number): any[];
|
||||
|
||||
/**
|
||||
* Creates an array from iterable spread.
|
||||
*
|
||||
* @param args The Iterable objects to spread.
|
||||
* @deprecated since TypeScript 4.2 - Use `__spreadArray`
|
||||
*/
|
||||
export declare function __spread(...args: any[][]): any[];
|
||||
|
||||
/**
|
||||
* Creates an array from array spread.
|
||||
*
|
||||
* @param args The ArrayLikes to spread into the resulting array.
|
||||
* @deprecated since TypeScript 4.2 - Use `__spreadArray`
|
||||
*/
|
||||
export declare function __spreadArrays(...args: any[][]): any[];
|
||||
|
||||
/**
|
||||
* Spreads the `from` array into the `to` array.
|
||||
*
|
||||
* @param pack Replace empty elements with `undefined`.
|
||||
*/
|
||||
export declare function __spreadArray(to: any[], from: any[], pack?: boolean): any[];
|
||||
|
||||
/**
|
||||
* Creates an object that signals to `__asyncGenerator` that it shouldn't be yielded,
|
||||
* and instead should be awaited and the resulting value passed back to the generator.
|
||||
*
|
||||
* @param v The value to await.
|
||||
*/
|
||||
export declare function __await(v: any): any;
|
||||
|
||||
/**
|
||||
* Converts a generator function into an async generator function, by using `yield __await`
|
||||
* in place of normal `await`.
|
||||
*
|
||||
* @param thisArg The reference to use as the `this` value in the generator function
|
||||
* @param _arguments The optional arguments array
|
||||
* @param generator The generator function
|
||||
*/
|
||||
export declare function __asyncGenerator(thisArg: any, _arguments: any, generator: Function): any;
|
||||
|
||||
/**
|
||||
* Used to wrap a potentially async iterator in such a way so that it wraps the result
|
||||
* of calling iterator methods of `o` in `__await` instances, and then yields the awaited values.
|
||||
*
|
||||
* @param o The potentially async iterator.
|
||||
* @returns A synchronous iterator yielding `__await` instances on every odd invocation
|
||||
* and returning the awaited `IteratorResult` passed to `next` every even invocation.
|
||||
*/
|
||||
export declare function __asyncDelegator(o: any): any;
|
||||
|
||||
/**
|
||||
* Creates a value async iterator from an `AsyncIterable`, `Iterable` or `ArrayLike` object.
|
||||
*
|
||||
* @param o The object.
|
||||
* @throws {TypeError} If `o` is neither `AsyncIterable`, `Iterable`, nor an `ArrayLike`.
|
||||
*/
|
||||
export declare function __asyncValues(o: any): any;
|
||||
|
||||
/**
|
||||
* Creates a `TemplateStringsArray` frozen object from the `cooked` and `raw` arrays.
|
||||
*
|
||||
* @param cooked The cooked possibly-sparse array.
|
||||
* @param raw The raw string content.
|
||||
*/
|
||||
export declare function __makeTemplateObject(cooked: string[], raw: string[]): TemplateStringsArray;
|
||||
|
||||
/**
|
||||
* Used to shim default and named imports in ECMAScript Modules transpiled to CommonJS.
|
||||
*
|
||||
* ```js
|
||||
* import Default, { Named, Other } from "mod";
|
||||
* // or
|
||||
* import { default as Default, Named, Other } from "mod";
|
||||
* ```
|
||||
*
|
||||
* @param mod The CommonJS module exports object.
|
||||
*/
|
||||
export declare function __importStar<T>(mod: T): T;
|
||||
|
||||
/**
|
||||
* Used to shim default imports in ECMAScript Modules transpiled to CommonJS.
|
||||
*
|
||||
* ```js
|
||||
* import Default from "mod";
|
||||
* ```
|
||||
*
|
||||
* @param mod The CommonJS module exports object.
|
||||
*/
|
||||
export declare function __importDefault<T>(mod: T): T | { default: T };
|
||||
|
||||
/**
|
||||
* Emulates reading a private instance field.
|
||||
*
|
||||
* @param receiver The instance from which to read the private field.
|
||||
* @param state A WeakMap containing the private field value for an instance.
|
||||
* @param kind Either `"f"` for a field, `"a"` for an accessor, or `"m"` for a method.
|
||||
*
|
||||
* @throws {TypeError} If `state` doesn't have an entry for `receiver`.
|
||||
*/
|
||||
export declare function __classPrivateFieldGet<T extends object, V>(
|
||||
receiver: T,
|
||||
state: { has(o: T): boolean, get(o: T): V | undefined },
|
||||
kind?: "f"
|
||||
): V;
|
||||
|
||||
/**
|
||||
* Emulates reading a private static field.
|
||||
*
|
||||
* @param receiver The object from which to read the private static field.
|
||||
* @param state The class constructor containing the definition of the static field.
|
||||
* @param kind Either `"f"` for a field, `"a"` for an accessor, or `"m"` for a method.
|
||||
* @param f The descriptor that holds the static field value.
|
||||
*
|
||||
* @throws {TypeError} If `receiver` is not `state`.
|
||||
*/
|
||||
export declare function __classPrivateFieldGet<T extends new (...args: any[]) => unknown, V>(
|
||||
receiver: T,
|
||||
state: T,
|
||||
kind: "f",
|
||||
f: { value: V }
|
||||
): V;
|
||||
|
||||
/**
|
||||
* Emulates evaluating a private instance "get" accessor.
|
||||
*
|
||||
* @param receiver The instance on which to evaluate the private "get" accessor.
|
||||
* @param state A WeakSet used to verify an instance supports the private "get" accessor.
|
||||
* @param kind Either `"f"` for a field, `"a"` for an accessor, or `"m"` for a method.
|
||||
* @param f The "get" accessor function to evaluate.
|
||||
*
|
||||
* @throws {TypeError} If `state` doesn't have an entry for `receiver`.
|
||||
*/
|
||||
export declare function __classPrivateFieldGet<T extends object, V>(
|
||||
receiver: T,
|
||||
state: { has(o: T): boolean },
|
||||
kind: "a",
|
||||
f: () => V
|
||||
): V;
|
||||
|
||||
/**
|
||||
* Emulates evaluating a private static "get" accessor.
|
||||
*
|
||||
* @param receiver The object on which to evaluate the private static "get" accessor.
|
||||
* @param state The class constructor containing the definition of the static "get" accessor.
|
||||
* @param kind Either `"f"` for a field, `"a"` for an accessor, or `"m"` for a method.
|
||||
* @param f The "get" accessor function to evaluate.
|
||||
*
|
||||
* @throws {TypeError} If `receiver` is not `state`.
|
||||
*/
|
||||
export declare function __classPrivateFieldGet<T extends new (...args: any[]) => unknown, V>(
|
||||
receiver: T,
|
||||
state: T,
|
||||
kind: "a",
|
||||
f: () => V
|
||||
): V;
|
||||
|
||||
/**
|
||||
* Emulates reading a private instance method.
|
||||
*
|
||||
* @param receiver The instance from which to read a private method.
|
||||
* @param state A WeakSet used to verify an instance supports the private method.
|
||||
* @param kind Either `"f"` for a field, `"a"` for an accessor, or `"m"` for a method.
|
||||
* @param f The function to return as the private instance method.
|
||||
*
|
||||
* @throws {TypeError} If `state` doesn't have an entry for `receiver`.
|
||||
*/
|
||||
export declare function __classPrivateFieldGet<T extends object, V extends (...args: any[]) => unknown>(
|
||||
receiver: T,
|
||||
state: { has(o: T): boolean },
|
||||
kind: "m",
|
||||
f: V
|
||||
): V;
|
||||
|
||||
/**
|
||||
* Emulates reading a private static method.
|
||||
*
|
||||
* @param receiver The object from which to read the private static method.
|
||||
* @param state The class constructor containing the definition of the static method.
|
||||
* @param kind Either `"f"` for a field, `"a"` for an accessor, or `"m"` for a method.
|
||||
* @param f The function to return as the private static method.
|
||||
*
|
||||
* @throws {TypeError} If `receiver` is not `state`.
|
||||
*/
|
||||
export declare function __classPrivateFieldGet<T extends new (...args: any[]) => unknown, V extends (...args: any[]) => unknown>(
|
||||
receiver: T,
|
||||
state: T,
|
||||
kind: "m",
|
||||
f: V
|
||||
): V;
|
||||
|
||||
/**
|
||||
* Emulates writing to a private instance field.
|
||||
*
|
||||
* @param receiver The instance on which to set a private field value.
|
||||
* @param state A WeakMap used to store the private field value for an instance.
|
||||
* @param value The value to store in the private field.
|
||||
* @param kind Either `"f"` for a field, `"a"` for an accessor, or `"m"` for a method.
|
||||
*
|
||||
* @throws {TypeError} If `state` doesn't have an entry for `receiver`.
|
||||
*/
|
||||
export declare function __classPrivateFieldSet<T extends object, V>(
|
||||
receiver: T,
|
||||
state: { has(o: T): boolean, set(o: T, value: V): unknown },
|
||||
value: V,
|
||||
kind?: "f"
|
||||
): V;
|
||||
|
||||
/**
|
||||
* Emulates writing to a private static field.
|
||||
*
|
||||
* @param receiver The object on which to set the private static field.
|
||||
* @param state The class constructor containing the definition of the private static field.
|
||||
* @param value The value to store in the private field.
|
||||
* @param kind Either `"f"` for a field, `"a"` for an accessor, or `"m"` for a method.
|
||||
* @param f The descriptor that holds the static field value.
|
||||
*
|
||||
* @throws {TypeError} If `receiver` is not `state`.
|
||||
*/
|
||||
export declare function __classPrivateFieldSet<T extends new (...args: any[]) => unknown, V>(
|
||||
receiver: T,
|
||||
state: T,
|
||||
value: V,
|
||||
kind: "f",
|
||||
f: { value: V }
|
||||
): V;
|
||||
|
||||
/**
|
||||
* Emulates writing to a private instance "set" accessor.
|
||||
*
|
||||
* @param receiver The instance on which to evaluate the private instance "set" accessor.
|
||||
* @param state A WeakSet used to verify an instance supports the private "set" accessor.
|
||||
* @param value The value to store in the private accessor.
|
||||
* @param kind Either `"f"` for a field, `"a"` for an accessor, or `"m"` for a method.
|
||||
* @param f The "set" accessor function to evaluate.
|
||||
*
|
||||
* @throws {TypeError} If `state` doesn't have an entry for `receiver`.
|
||||
*/
|
||||
export declare function __classPrivateFieldSet<T extends object, V>(
|
||||
receiver: T,
|
||||
state: { has(o: T): boolean },
|
||||
value: V,
|
||||
kind: "a",
|
||||
f: (v: V) => void
|
||||
): V;
|
||||
|
||||
/**
|
||||
* Emulates writing to a private static "set" accessor.
|
||||
*
|
||||
* @param receiver The object on which to evaluate the private static "set" accessor.
|
||||
* @param state The class constructor containing the definition of the static "set" accessor.
|
||||
* @param value The value to store in the private field.
|
||||
* @param kind Either `"f"` for a field, `"a"` for an accessor, or `"m"` for a method.
|
||||
* @param f The "set" accessor function to evaluate.
|
||||
*
|
||||
* @throws {TypeError} If `receiver` is not `state`.
|
||||
*/
|
||||
export declare function __classPrivateFieldSet<T extends new (...args: any[]) => unknown, V>(
|
||||
receiver: T,
|
||||
state: T,
|
||||
value: V,
|
||||
kind: "a",
|
||||
f: (v: V) => void
|
||||
): V;
|
||||
|
||||
/**
|
||||
* Checks for the existence of a private field/method/accessor.
|
||||
*
|
||||
* @param state The class constructor containing the static member, or the WeakMap or WeakSet associated with a private instance member.
|
||||
* @param receiver The object for which to test the presence of the private member.
|
||||
*/
|
||||
export declare function __classPrivateFieldIn(
|
||||
state: (new (...args: any[]) => unknown) | { has(o: any): boolean },
|
||||
receiver: unknown,
|
||||
): boolean;
|
||||
|
||||
/**
|
||||
* Creates a re-export binding on `object` with key `objectKey` that references `target[key]`.
|
||||
*
|
||||
* @param object The local `exports` object.
|
||||
* @param target The object to re-export from.
|
||||
* @param key The property key of `target` to re-export.
|
||||
* @param objectKey The property key to re-export as. Defaults to `key`.
|
||||
*/
|
||||
export declare function __createBinding(object: object, target: object, key: PropertyKey, objectKey?: PropertyKey): void;
|
||||
|
||||
/**
|
||||
* Adds a disposable resource to a resource-tracking environment object.
|
||||
* @param env A resource-tracking environment object.
|
||||
* @param value Either a Disposable or AsyncDisposable object, `null`, or `undefined`.
|
||||
* @param async When `true`, `AsyncDisposable` resources can be added. When `false`, `AsyncDisposable` resources cannot be added.
|
||||
* @returns The {@link value} argument.
|
||||
*
|
||||
* @throws {TypeError} If {@link value} is not an object, or if either `Symbol.dispose` or `Symbol.asyncDispose` are not
|
||||
* defined, or if {@link value} does not have an appropriate `Symbol.dispose` or `Symbol.asyncDispose` method.
|
||||
*/
|
||||
export declare function __addDisposableResource<T>(env: { stack: { value?: unknown, dispose?: Function, async: boolean }[]; error: unknown; hasError: boolean; }, value: T, async: boolean): T;
|
||||
|
||||
/**
|
||||
* Disposes all resources in a resource-tracking environment object.
|
||||
* @param env A resource-tracking environment object.
|
||||
* @returns A {@link Promise} if any resources in the environment were marked as `async` when added; otherwise, `void`.
|
||||
*
|
||||
* @throws {SuppressedError} if an error thrown during disposal would have suppressed a prior error from disposal or the
|
||||
* error recorded in the resource-tracking environment object.
|
||||
* @seealso {@link __addDisposableResource}
|
||||
*/
|
||||
export declare function __disposeResources(env: { stack: { value?: unknown, dispose?: Function, async: boolean }[]; error: unknown; hasError: boolean; }): any;
|
||||
|
||||
/**
|
||||
* Transforms a relative import specifier ending in a non-declaration TypeScript file extension to its JavaScript file extension counterpart.
|
||||
* @param path The import specifier.
|
||||
* @param preserveJsx Causes '*.tsx' to transform to '*.jsx' instead of '*.js'. Should be true when `--jsx` is set to `preserve`.
|
||||
*/
|
||||
export declare function __rewriteRelativeImportExtension(path: string, preserveJsx?: boolean): string;
|
||||
@@ -0,0 +1,357 @@
|
||||
"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");
|
||||
const getParentFunctionNode_1 = require("../util/getParentFunctionNode");
|
||||
exports.default = (0, util_1.createRule)({
|
||||
name: 'no-confusing-void-expression',
|
||||
meta: {
|
||||
type: 'problem',
|
||||
docs: {
|
||||
description: 'Require expressions of type void to appear in statement position',
|
||||
recommended: 'strict',
|
||||
requiresTypeChecking: true,
|
||||
},
|
||||
fixable: 'code',
|
||||
hasSuggestions: true,
|
||||
messages: {
|
||||
invalidVoidExpr: 'Placing a void expression inside another expression is forbidden. ' +
|
||||
'Move it to its own statement instead.',
|
||||
invalidVoidExprArrow: 'Returning a void expression from an arrow function shorthand is forbidden. ' +
|
||||
'Please add braces to the arrow function.',
|
||||
invalidVoidExprArrowWrapVoid: 'Void expressions returned from an arrow function shorthand ' +
|
||||
'must be marked explicitly with the `void` operator.',
|
||||
invalidVoidExprReturn: 'Returning a void expression from a function is forbidden. ' +
|
||||
'Please move it before the `return` statement.',
|
||||
invalidVoidExprReturnLast: 'Returning a void expression from a function is forbidden. ' +
|
||||
'Please remove the `return` statement.',
|
||||
invalidVoidExprReturnWrapVoid: 'Void expressions returned from a function ' +
|
||||
'must be marked explicitly with the `void` operator.',
|
||||
invalidVoidExprWrapVoid: 'Void expressions used inside another expression ' +
|
||||
'must be moved to its own statement ' +
|
||||
'or marked explicitly with the `void` operator.',
|
||||
voidExprWrapVoid: 'Mark with an explicit `void` operator.',
|
||||
},
|
||||
schema: [
|
||||
{
|
||||
type: 'object',
|
||||
additionalProperties: false,
|
||||
properties: {
|
||||
ignoreArrowShorthand: {
|
||||
type: 'boolean',
|
||||
description: 'Whether to ignore "shorthand" `() =>` arrow functions: those without `{ ... }` braces.',
|
||||
},
|
||||
ignoreVoidOperator: {
|
||||
type: 'boolean',
|
||||
description: 'Whether to ignore returns that start with the `void` operator.',
|
||||
},
|
||||
ignoreVoidReturningFunctions: {
|
||||
type: 'boolean',
|
||||
description: 'Whether to ignore returns from functions with explicit `void` return types and functions with contextual `void` return types.',
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
defaultOptions: [
|
||||
{
|
||||
ignoreArrowShorthand: false,
|
||||
ignoreVoidOperator: false,
|
||||
ignoreVoidReturningFunctions: false,
|
||||
},
|
||||
],
|
||||
create(context, [options]) {
|
||||
const services = (0, util_1.getParserServices)(context);
|
||||
return {
|
||||
'AwaitExpression, CallExpression, TaggedTemplateExpression'(node) {
|
||||
const invalidAncestor = findInvalidAncestor(node);
|
||||
if (invalidAncestor == null) {
|
||||
// void expression is in valid position
|
||||
return;
|
||||
}
|
||||
const type = (0, util_1.getConstrainedTypeAtLocation)(services, node);
|
||||
if (!tsutils.isTypeFlagSet(type, ts.TypeFlags.VoidLike)) {
|
||||
// not a void expression
|
||||
return;
|
||||
}
|
||||
const wrapVoidFix = (fixer) => {
|
||||
const nodeText = context.sourceCode.getText(node);
|
||||
const newNodeText = `void ${nodeText}`;
|
||||
return fixer.replaceText(node, newNodeText);
|
||||
};
|
||||
if (invalidAncestor.type === utils_1.AST_NODE_TYPES.ArrowFunctionExpression) {
|
||||
// handle arrow function shorthand
|
||||
if (options.ignoreVoidReturningFunctions) {
|
||||
const returnsVoid = isVoidReturningFunctionNode(invalidAncestor);
|
||||
if (returnsVoid) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
if (options.ignoreVoidOperator) {
|
||||
// handle wrapping with `void`
|
||||
return context.report({
|
||||
node,
|
||||
messageId: 'invalidVoidExprArrowWrapVoid',
|
||||
fix: wrapVoidFix,
|
||||
});
|
||||
}
|
||||
// handle wrapping with braces
|
||||
const arrowFunction = invalidAncestor;
|
||||
return context.report({
|
||||
node,
|
||||
messageId: 'invalidVoidExprArrow',
|
||||
fix(fixer) {
|
||||
if (!canFix(arrowFunction)) {
|
||||
return null;
|
||||
}
|
||||
const arrowBody = arrowFunction.body;
|
||||
const arrowBodyText = context.sourceCode.getText(arrowBody);
|
||||
const newArrowBodyText = `{ ${arrowBodyText}; }`;
|
||||
if ((0, util_1.isParenthesized)(arrowBody, context.sourceCode)) {
|
||||
const bodyOpeningParen = (0, util_1.nullThrows)(context.sourceCode.getTokenBefore(arrowBody, util_1.isOpeningParenToken), util_1.NullThrowsReasons.MissingToken('opening parenthesis', 'arrow body'));
|
||||
const bodyClosingParen = (0, util_1.nullThrows)(context.sourceCode.getTokenAfter(arrowBody, util_1.isClosingParenToken), util_1.NullThrowsReasons.MissingToken('closing parenthesis', 'arrow body'));
|
||||
return fixer.replaceTextRange([bodyOpeningParen.range[0], bodyClosingParen.range[1]], newArrowBodyText);
|
||||
}
|
||||
return fixer.replaceText(arrowBody, newArrowBodyText);
|
||||
},
|
||||
});
|
||||
}
|
||||
if (invalidAncestor.type === utils_1.AST_NODE_TYPES.ReturnStatement) {
|
||||
// handle return statement
|
||||
if (options.ignoreVoidReturningFunctions) {
|
||||
const functionNode = (0, getParentFunctionNode_1.getParentFunctionNode)(invalidAncestor);
|
||||
if (functionNode) {
|
||||
const returnsVoid = isVoidReturningFunctionNode(functionNode);
|
||||
if (returnsVoid) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (options.ignoreVoidOperator) {
|
||||
// handle wrapping with `void`
|
||||
return context.report({
|
||||
node,
|
||||
messageId: 'invalidVoidExprReturnWrapVoid',
|
||||
fix: wrapVoidFix,
|
||||
});
|
||||
}
|
||||
if (isFinalReturn(invalidAncestor)) {
|
||||
// remove the `return` keyword
|
||||
return context.report({
|
||||
node,
|
||||
messageId: 'invalidVoidExprReturnLast',
|
||||
fix(fixer) {
|
||||
if (!canFix(invalidAncestor)) {
|
||||
return null;
|
||||
}
|
||||
const returnValue = invalidAncestor.argument;
|
||||
const returnValueText = context.sourceCode.getText(returnValue);
|
||||
let newReturnStmtText = `${returnValueText};`;
|
||||
if (isPreventingASI(returnValue)) {
|
||||
// put a semicolon at the beginning of the line
|
||||
newReturnStmtText = `;${newReturnStmtText}`;
|
||||
}
|
||||
return fixer.replaceText(invalidAncestor, newReturnStmtText);
|
||||
},
|
||||
});
|
||||
}
|
||||
// move before the `return` keyword
|
||||
return context.report({
|
||||
node,
|
||||
messageId: 'invalidVoidExprReturn',
|
||||
fix(fixer) {
|
||||
const returnValue = invalidAncestor.argument;
|
||||
const returnValueText = context.sourceCode.getText(returnValue);
|
||||
let newReturnStmtText = `${returnValueText}; return;`;
|
||||
if (isPreventingASI(returnValue)) {
|
||||
// put a semicolon at the beginning of the line
|
||||
newReturnStmtText = `;${newReturnStmtText}`;
|
||||
}
|
||||
if (invalidAncestor.parent.type !== utils_1.AST_NODE_TYPES.BlockStatement) {
|
||||
// e.g. `if (cond) return console.error();`
|
||||
// add braces if not inside a block
|
||||
newReturnStmtText = `{ ${newReturnStmtText} }`;
|
||||
}
|
||||
return fixer.replaceText(invalidAncestor, newReturnStmtText);
|
||||
},
|
||||
});
|
||||
}
|
||||
// handle generic case
|
||||
if (options.ignoreVoidOperator) {
|
||||
// this would be reported by this rule btw. such irony
|
||||
return context.report({
|
||||
node,
|
||||
messageId: 'invalidVoidExprWrapVoid',
|
||||
suggest: [{ messageId: 'voidExprWrapVoid', fix: wrapVoidFix }],
|
||||
});
|
||||
}
|
||||
context.report({
|
||||
node,
|
||||
messageId: 'invalidVoidExpr',
|
||||
});
|
||||
},
|
||||
};
|
||||
/**
|
||||
* Inspects the void expression's ancestors and finds closest invalid one.
|
||||
* By default anything other than an ExpressionStatement is invalid.
|
||||
* Parent expressions which can be used for their short-circuiting behavior
|
||||
* are ignored and their parents are checked instead.
|
||||
* @param node The void expression node to check.
|
||||
* @returns Invalid ancestor node if it was found. `null` otherwise.
|
||||
*/
|
||||
function findInvalidAncestor(node) {
|
||||
const parent = node.parent;
|
||||
if (parent.type === utils_1.AST_NODE_TYPES.SequenceExpression &&
|
||||
node !== parent.expressions[parent.expressions.length - 1]) {
|
||||
return null;
|
||||
}
|
||||
if (parent.type === utils_1.AST_NODE_TYPES.ExpressionStatement) {
|
||||
// e.g. `{ console.log("foo"); }`
|
||||
// this is always valid
|
||||
return null;
|
||||
}
|
||||
if (parent.type === utils_1.AST_NODE_TYPES.LogicalExpression &&
|
||||
parent.right === node) {
|
||||
// e.g. `x && console.log(x)`
|
||||
// this is valid only if the next ancestor is valid
|
||||
return findInvalidAncestor(parent);
|
||||
}
|
||||
if (parent.type === utils_1.AST_NODE_TYPES.ConditionalExpression &&
|
||||
(parent.consequent === node || parent.alternate === node)) {
|
||||
// e.g. `cond ? console.log(true) : console.log(false)`
|
||||
// this is valid only if the next ancestor is valid
|
||||
return findInvalidAncestor(parent);
|
||||
}
|
||||
if (parent.type === utils_1.AST_NODE_TYPES.ArrowFunctionExpression &&
|
||||
// e.g. `() => console.log("foo")`
|
||||
// this is valid with an appropriate option
|
||||
options.ignoreArrowShorthand) {
|
||||
return null;
|
||||
}
|
||||
if (parent.type === utils_1.AST_NODE_TYPES.UnaryExpression &&
|
||||
parent.operator === 'void' &&
|
||||
// e.g. `void console.log("foo")`
|
||||
// this is valid with an appropriate option
|
||||
options.ignoreVoidOperator) {
|
||||
return null;
|
||||
}
|
||||
if (parent.type === utils_1.AST_NODE_TYPES.ChainExpression) {
|
||||
// e.g. `console?.log('foo')`
|
||||
return findInvalidAncestor(parent);
|
||||
}
|
||||
// Any other parent is invalid.
|
||||
// We can assume a return statement will have an argument.
|
||||
return parent;
|
||||
}
|
||||
/** Checks whether the return statement is the last statement in a function body. */
|
||||
function isFinalReturn(node) {
|
||||
// the parent must be a block
|
||||
const block = node.parent;
|
||||
if (block.type !== utils_1.AST_NODE_TYPES.BlockStatement) {
|
||||
// e.g. `if (cond) return;` (not in a block)
|
||||
return false;
|
||||
}
|
||||
// the block's parent must be a function
|
||||
const blockParent = block.parent;
|
||||
if (![
|
||||
utils_1.AST_NODE_TYPES.ArrowFunctionExpression,
|
||||
utils_1.AST_NODE_TYPES.FunctionDeclaration,
|
||||
utils_1.AST_NODE_TYPES.FunctionExpression,
|
||||
].includes(blockParent.type)) {
|
||||
// e.g. `if (cond) { return; }`
|
||||
// not in a top-level function block
|
||||
return false;
|
||||
}
|
||||
// must be the last child of the block
|
||||
if (block.body.indexOf(node) < block.body.length - 1) {
|
||||
// not the last statement in the block
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
/**
|
||||
* Checks whether the given node, if placed on its own line,
|
||||
* would prevent automatic semicolon insertion on the line before.
|
||||
*
|
||||
* This happens if the line begins with `(`, `[` or `` ` ``
|
||||
*/
|
||||
function isPreventingASI(node) {
|
||||
const startToken = (0, util_1.nullThrows)(context.sourceCode.getFirstToken(node), util_1.NullThrowsReasons.MissingToken('first token', node.type));
|
||||
return ['(', '[', '`'].includes(startToken.value);
|
||||
}
|
||||
function canFix(node) {
|
||||
const targetNode = node.type === utils_1.AST_NODE_TYPES.ReturnStatement
|
||||
? node.argument
|
||||
: node.body;
|
||||
const type = (0, util_1.getConstrainedTypeAtLocation)(services, targetNode);
|
||||
return tsutils.isTypeFlagSet(type, ts.TypeFlags.VoidLike);
|
||||
}
|
||||
function isFunctionReturnTypeIncludesVoid(functionType) {
|
||||
const callSignatures = tsutils.getCallSignaturesOfType(functionType);
|
||||
return callSignatures.some(signature => {
|
||||
const returnType = signature.getReturnType();
|
||||
return tsutils
|
||||
.unionConstituents(returnType)
|
||||
.some(tsutils.isIntrinsicVoidType);
|
||||
});
|
||||
}
|
||||
function isVoidReturningFunctionNode(functionNode) {
|
||||
// Game plan:
|
||||
// - If the function node has a type annotation, check if it includes `void`.
|
||||
// - If it does then the function is safe to return `void` expressions in.
|
||||
// - Otherwise, check if the function is a function-expression or an arrow-function.
|
||||
// - If it is, get its contextual type and bail if we cannot.
|
||||
// - Return based on whether the contextual type includes `void` or not
|
||||
if (functionNode.returnType) {
|
||||
const returnType = services.getTypeFromTypeNode(functionNode.returnType.typeAnnotation);
|
||||
return tsutils
|
||||
.unionConstituents(returnType)
|
||||
.some(tsutils.isIntrinsicVoidType);
|
||||
}
|
||||
if (functionNode.type !== utils_1.AST_NODE_TYPES.FunctionDeclaration) {
|
||||
const functionType = services.getContextualType(functionNode);
|
||||
if (functionType) {
|
||||
return tsutils
|
||||
.unionConstituents(functionType)
|
||||
.some(isFunctionReturnTypeIncludesVoid);
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,98 @@
|
||||
/**
|
||||
* @fileoverview Types for object-schema package.
|
||||
*/
|
||||
|
||||
/**
|
||||
* Built-in validation strategies.
|
||||
*/
|
||||
export type BuiltInValidationStrategy =
|
||||
| "array"
|
||||
| "boolean"
|
||||
| "number"
|
||||
| "object"
|
||||
| "object?"
|
||||
| "string"
|
||||
| "string!";
|
||||
|
||||
/**
|
||||
* Built-in merge strategies.
|
||||
*/
|
||||
export type BuiltInMergeStrategy = "assign" | "overwrite" | "replace";
|
||||
|
||||
/**
|
||||
* Custom merge strategy.
|
||||
*/
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- https://github.com/eslint/rewrite/pull/90#discussion_r1687206213
|
||||
export type CustomMergeStrategy = (target: any, source: any) => any;
|
||||
|
||||
/**
|
||||
* Custom validation strategy.
|
||||
*/
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- https://github.com/eslint/rewrite/pull/90#discussion_r1687206213
|
||||
export type CustomValidationStrategy = (value: any) => void;
|
||||
|
||||
interface BasePropertyDefinition {
|
||||
/**
|
||||
* Indicates if the property is required.
|
||||
*/
|
||||
required?: boolean;
|
||||
|
||||
/**
|
||||
* The other properties that must be present when this property is used.
|
||||
*/
|
||||
requires?: string[];
|
||||
}
|
||||
|
||||
/**
|
||||
* Property definition that specifies explicit merge and validation strategies.
|
||||
* This form cannot include a `schema`.
|
||||
*/
|
||||
export interface PropertyDefinitionWithStrategies extends BasePropertyDefinition {
|
||||
/**
|
||||
* The schema for the object value of this property.
|
||||
*/
|
||||
schema?: never;
|
||||
|
||||
/**
|
||||
* The strategy to merge the property.
|
||||
*/
|
||||
merge: BuiltInMergeStrategy | CustomMergeStrategy;
|
||||
|
||||
/**
|
||||
* The strategy to validate the property.
|
||||
*/
|
||||
validate: BuiltInValidationStrategy | CustomValidationStrategy;
|
||||
}
|
||||
|
||||
/**
|
||||
* Property definition that uses a nested `schema`.
|
||||
* When `schema` is present, merge and validation strategies are optional.
|
||||
*/
|
||||
export interface PropertyDefinitionWithSchema extends BasePropertyDefinition {
|
||||
/**
|
||||
* The schema for the object value of this property.
|
||||
*/
|
||||
schema: ObjectDefinition;
|
||||
|
||||
/**
|
||||
* The strategy to merge the property.
|
||||
*/
|
||||
merge?: BuiltInMergeStrategy | CustomMergeStrategy;
|
||||
|
||||
/**
|
||||
* The strategy to validate the property.
|
||||
*/
|
||||
validate?: BuiltInValidationStrategy | CustomValidationStrategy;
|
||||
}
|
||||
|
||||
/**
|
||||
* Property definition.
|
||||
*/
|
||||
export type PropertyDefinition =
|
||||
| PropertyDefinitionWithStrategies
|
||||
| PropertyDefinitionWithSchema;
|
||||
|
||||
/**
|
||||
* Object definition.
|
||||
*/
|
||||
export type ObjectDefinition = Record<string, PropertyDefinition>;
|
||||
@@ -0,0 +1,165 @@
|
||||
"use strict";
|
||||
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
||||
if (k2 === undefined) k2 = k;
|
||||
var desc = Object.getOwnPropertyDescriptor(m, k);
|
||||
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
||||
desc = { enumerable: true, get: function() { return m[k]; } };
|
||||
}
|
||||
Object.defineProperty(o, k2, desc);
|
||||
}) : (function(o, m, k, k2) {
|
||||
if (k2 === undefined) k2 = k;
|
||||
o[k2] = m[k];
|
||||
}));
|
||||
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
||||
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
||||
}) : function(o, v) {
|
||||
o["default"] = v;
|
||||
});
|
||||
var __importStar = (this && this.__importStar) || (function () {
|
||||
var ownKeys = function(o) {
|
||||
ownKeys = Object.getOwnPropertyNames || function (o) {
|
||||
var ar = [];
|
||||
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
|
||||
return ar;
|
||||
};
|
||||
return ownKeys(o);
|
||||
};
|
||||
return function (mod) {
|
||||
if (mod && mod.__esModule) return mod;
|
||||
var result = {};
|
||||
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
|
||||
__setModuleDefault(result, mod);
|
||||
return result;
|
||||
};
|
||||
})();
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.isPromiseLike = isPromiseLike;
|
||||
exports.isPromiseConstructorLike = isPromiseConstructorLike;
|
||||
exports.isErrorLike = isErrorLike;
|
||||
exports.isReadonlyErrorLike = isReadonlyErrorLike;
|
||||
exports.isReadonlyTypeLike = isReadonlyTypeLike;
|
||||
exports.isBuiltinTypeAliasLike = isBuiltinTypeAliasLike;
|
||||
exports.isBuiltinSymbolLike = isBuiltinSymbolLike;
|
||||
exports.isBuiltinSymbolLikeRecurser = isBuiltinSymbolLikeRecurser;
|
||||
const tsutils = __importStar(require("ts-api-utils"));
|
||||
const ts = __importStar(require("typescript"));
|
||||
const isSymbolFromDefaultLibrary_1 = require("./isSymbolFromDefaultLibrary");
|
||||
/**
|
||||
* @example
|
||||
* ```ts
|
||||
* class DerivedClass extends Promise<number> {}
|
||||
* DerivedClass.reject
|
||||
* // ^ PromiseLike
|
||||
* ```
|
||||
*/
|
||||
function isPromiseLike(program, type) {
|
||||
return isBuiltinSymbolLike(program, type, 'Promise');
|
||||
}
|
||||
/**
|
||||
* @example
|
||||
* ```ts
|
||||
* const value = Promise
|
||||
* value.reject
|
||||
* // ^ PromiseConstructorLike
|
||||
* ```
|
||||
*/
|
||||
function isPromiseConstructorLike(program, type) {
|
||||
return isBuiltinSymbolLike(program, type, 'PromiseConstructor');
|
||||
}
|
||||
/**
|
||||
* @example
|
||||
* ```ts
|
||||
* class Foo extends Error {}
|
||||
* new Foo()
|
||||
* // ^ ErrorLike
|
||||
* ```
|
||||
*/
|
||||
function isErrorLike(program, type) {
|
||||
return isBuiltinSymbolLike(program, type, 'Error');
|
||||
}
|
||||
/**
|
||||
* @example
|
||||
* ```ts
|
||||
* type T = Readonly<Error>
|
||||
* // ^ ReadonlyErrorLike
|
||||
* ```
|
||||
*/
|
||||
function isReadonlyErrorLike(program, type) {
|
||||
return isReadonlyTypeLike(program, type, subtype => {
|
||||
const [typeArgument] = subtype.aliasTypeArguments;
|
||||
return (isErrorLike(program, typeArgument) ||
|
||||
isReadonlyErrorLike(program, typeArgument));
|
||||
});
|
||||
}
|
||||
/**
|
||||
* @example
|
||||
* ```ts
|
||||
* type T = Readonly<{ foo: 'bar' }>
|
||||
* // ^ ReadonlyTypeLike
|
||||
* ```
|
||||
*/
|
||||
function isReadonlyTypeLike(program, type, predicate) {
|
||||
return isBuiltinTypeAliasLike(program, type, subtype => {
|
||||
return (subtype.aliasSymbol.getName() === 'Readonly' && !!predicate?.(subtype));
|
||||
});
|
||||
}
|
||||
function isBuiltinTypeAliasLike(program, type, predicate) {
|
||||
return isBuiltinSymbolLikeRecurser(program, type, subtype => {
|
||||
const { aliasSymbol, aliasTypeArguments } = subtype;
|
||||
if (!aliasSymbol || !aliasTypeArguments) {
|
||||
return false;
|
||||
}
|
||||
if ((0, isSymbolFromDefaultLibrary_1.isSymbolFromDefaultLibrary)(program, aliasSymbol) &&
|
||||
predicate(subtype)) {
|
||||
return true;
|
||||
}
|
||||
return null;
|
||||
});
|
||||
}
|
||||
function isBuiltinSymbolLike(program, type, symbolName) {
|
||||
return isBuiltinSymbolLikeRecurser(program, type, subType => {
|
||||
const symbol = subType.getSymbol();
|
||||
if (!symbol) {
|
||||
return false;
|
||||
}
|
||||
const actualSymbolName = symbol.getName();
|
||||
if ((Array.isArray(symbolName)
|
||||
? symbolName.some(name => actualSymbolName === name)
|
||||
: actualSymbolName === symbolName) &&
|
||||
(0, isSymbolFromDefaultLibrary_1.isSymbolFromDefaultLibrary)(program, symbol)) {
|
||||
return true;
|
||||
}
|
||||
return null;
|
||||
});
|
||||
}
|
||||
function isBuiltinSymbolLikeRecurser(program, type, predicate) {
|
||||
if (type.isIntersection()) {
|
||||
return type.types.some(t => isBuiltinSymbolLikeRecurser(program, t, predicate));
|
||||
}
|
||||
if (type.isUnion()) {
|
||||
return type.types.every(t => isBuiltinSymbolLikeRecurser(program, t, predicate));
|
||||
}
|
||||
if (tsutils.isTypeParameter(type)) {
|
||||
const t = type.getConstraint();
|
||||
if (t) {
|
||||
return isBuiltinSymbolLikeRecurser(program, t, predicate);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
const predicateResult = predicate(type);
|
||||
if (typeof predicateResult === 'boolean') {
|
||||
return predicateResult;
|
||||
}
|
||||
const symbol = type.getSymbol();
|
||||
if (symbol &&
|
||||
tsutils.isSymbolFlagSet(symbol, ts.SymbolFlags.Class | ts.SymbolFlags.Interface)) {
|
||||
const checker = program.getTypeChecker();
|
||||
const declaredType = checker.getDeclaredTypeOfSymbol(symbol);
|
||||
for (const baseType of checker.getBaseTypes(declaredType)) {
|
||||
if (isBuiltinSymbolLikeRecurser(program, baseType, predicate)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
'use strict';
|
||||
|
||||
const StreamBase = require('./StreamBase');
|
||||
const withParser = require('../utils/withParser');
|
||||
|
||||
class StreamObject extends StreamBase {
|
||||
static make(options) {
|
||||
return new StreamObject(options);
|
||||
}
|
||||
|
||||
static withParser(options) {
|
||||
return withParser(StreamObject.make, options);
|
||||
}
|
||||
|
||||
constructor(options) {
|
||||
super(options);
|
||||
this._level = 1;
|
||||
this._lastKey = null;
|
||||
}
|
||||
|
||||
_wait(chunk, _, callback) {
|
||||
// first chunk should open an array
|
||||
if (chunk.name !== 'startObject') {
|
||||
return callback(new Error('Top-level object should be an object.'));
|
||||
}
|
||||
this._transform = this._filter;
|
||||
return this._transform(chunk, _, callback);
|
||||
}
|
||||
|
||||
_push(discard) {
|
||||
if (this._lastKey === null) {
|
||||
this._lastKey = this._assembler.key;
|
||||
} else {
|
||||
!discard && this.push({key: this._lastKey, value: this._assembler.current[this._lastKey]});
|
||||
this._assembler.current = {};
|
||||
this._lastKey = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
StreamObject.streamObject = StreamObject.make;
|
||||
StreamObject.make.Constructor = StreamObject;
|
||||
|
||||
module.exports = StreamObject;
|
||||
@@ -0,0 +1,79 @@
|
||||
"use strict";
|
||||
|
||||
Object.defineProperty(exports, "__esModule", {
|
||||
value: true
|
||||
});
|
||||
Object.defineProperty(exports, "v1", {
|
||||
enumerable: true,
|
||||
get: function () {
|
||||
return _v.default;
|
||||
}
|
||||
});
|
||||
Object.defineProperty(exports, "v3", {
|
||||
enumerable: true,
|
||||
get: function () {
|
||||
return _v2.default;
|
||||
}
|
||||
});
|
||||
Object.defineProperty(exports, "v4", {
|
||||
enumerable: true,
|
||||
get: function () {
|
||||
return _v3.default;
|
||||
}
|
||||
});
|
||||
Object.defineProperty(exports, "v5", {
|
||||
enumerable: true,
|
||||
get: function () {
|
||||
return _v4.default;
|
||||
}
|
||||
});
|
||||
Object.defineProperty(exports, "NIL", {
|
||||
enumerable: true,
|
||||
get: function () {
|
||||
return _nil.default;
|
||||
}
|
||||
});
|
||||
Object.defineProperty(exports, "version", {
|
||||
enumerable: true,
|
||||
get: function () {
|
||||
return _version.default;
|
||||
}
|
||||
});
|
||||
Object.defineProperty(exports, "validate", {
|
||||
enumerable: true,
|
||||
get: function () {
|
||||
return _validate.default;
|
||||
}
|
||||
});
|
||||
Object.defineProperty(exports, "stringify", {
|
||||
enumerable: true,
|
||||
get: function () {
|
||||
return _stringify.default;
|
||||
}
|
||||
});
|
||||
Object.defineProperty(exports, "parse", {
|
||||
enumerable: true,
|
||||
get: function () {
|
||||
return _parse.default;
|
||||
}
|
||||
});
|
||||
|
||||
var _v = _interopRequireDefault(require("./v1.js"));
|
||||
|
||||
var _v2 = _interopRequireDefault(require("./v3.js"));
|
||||
|
||||
var _v3 = _interopRequireDefault(require("./v4.js"));
|
||||
|
||||
var _v4 = _interopRequireDefault(require("./v5.js"));
|
||||
|
||||
var _nil = _interopRequireDefault(require("./nil.js"));
|
||||
|
||||
var _version = _interopRequireDefault(require("./version.js"));
|
||||
|
||||
var _validate = _interopRequireDefault(require("./validate.js"));
|
||||
|
||||
var _stringify = _interopRequireDefault(require("./stringify.js"));
|
||||
|
||||
var _parse = _interopRequireDefault(require("./parse.js"));
|
||||
|
||||
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
|
||||
@@ -0,0 +1,69 @@
|
||||
'use strict';
|
||||
|
||||
var parse = require('../');
|
||||
var test = require('tape');
|
||||
|
||||
test('numeric short args', function (t) {
|
||||
t.plan(2);
|
||||
t.deepEqual(parse(['-n123']), { n: 123, _: [] });
|
||||
t.deepEqual(
|
||||
parse(['-123', '456']),
|
||||
{ 1: true, 2: true, 3: 456, _: [] }
|
||||
);
|
||||
});
|
||||
|
||||
test('short', function (t) {
|
||||
t.deepEqual(
|
||||
parse(['-b']),
|
||||
{ b: true, _: [] },
|
||||
'short boolean'
|
||||
);
|
||||
t.deepEqual(
|
||||
parse(['foo', 'bar', 'baz']),
|
||||
{ _: ['foo', 'bar', 'baz'] },
|
||||
'bare'
|
||||
);
|
||||
t.deepEqual(
|
||||
parse(['-cats']),
|
||||
{ c: true, a: true, t: true, s: true, _: [] },
|
||||
'group'
|
||||
);
|
||||
t.deepEqual(
|
||||
parse(['-cats', 'meow']),
|
||||
{ c: true, a: true, t: true, s: 'meow', _: [] },
|
||||
'short group next'
|
||||
);
|
||||
t.deepEqual(
|
||||
parse(['-h', 'localhost']),
|
||||
{ h: 'localhost', _: [] },
|
||||
'short capture'
|
||||
);
|
||||
t.deepEqual(
|
||||
parse(['-h', 'localhost', '-p', '555']),
|
||||
{ h: 'localhost', p: 555, _: [] },
|
||||
'short captures'
|
||||
);
|
||||
t.end();
|
||||
});
|
||||
|
||||
test('mixed short bool and capture', function (t) {
|
||||
t.same(
|
||||
parse(['-h', 'localhost', '-fp', '555', 'script.js']),
|
||||
{
|
||||
f: true, p: 555, h: 'localhost',
|
||||
_: ['script.js'],
|
||||
}
|
||||
);
|
||||
t.end();
|
||||
});
|
||||
|
||||
test('short and long', function (t) {
|
||||
t.deepEqual(
|
||||
parse(['-h', 'localhost', '-fp', '555', 'script.js']),
|
||||
{
|
||||
f: true, p: 555, h: 'localhost',
|
||||
_: ['script.js'],
|
||||
}
|
||||
);
|
||||
t.end();
|
||||
});
|
||||
@@ -0,0 +1,39 @@
|
||||
/**
|
||||
* @fileoverview Define the cursor which limits the number of tokens.
|
||||
* @author Toru Nagashima
|
||||
*/
|
||||
"use strict";
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Requirements
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
const DecorativeCursor = require("./decorative-cursor");
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Exports
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* The decorative cursor which limits the number of tokens.
|
||||
*/
|
||||
module.exports = class LimitCursor extends DecorativeCursor {
|
||||
/**
|
||||
* Initializes this cursor.
|
||||
* @param {Cursor} cursor The cursor to be decorated.
|
||||
* @param {number} count The count of tokens this cursor iterates.
|
||||
*/
|
||||
constructor(cursor, count) {
|
||||
super(cursor);
|
||||
this.count = count;
|
||||
}
|
||||
|
||||
/** @inheritdoc */
|
||||
moveNext() {
|
||||
if (this.count > 0) {
|
||||
this.count -= 1;
|
||||
return super.moveNext();
|
||||
}
|
||||
return false;
|
||||
}
|
||||
};
|
||||
Reference in New Issue
Block a user