@travetto/runtime 8.0.0-alpha.2 → 8.0.0-alpha.21
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +24 -21
- package/__index__.ts +6 -5
- package/package.json +9 -6
- package/src/binary-metadata.ts +33 -19
- package/src/binary.ts +18 -10
- package/src/codec.ts +25 -7
- package/src/console.ts +20 -12
- package/src/context.ts +26 -17
- package/src/debug.ts +1 -2
- package/src/env.ts +42 -22
- package/src/error.ts +4 -15
- package/src/exec.ts +41 -27
- package/src/file-loader.ts +4 -5
- package/src/function.ts +14 -6
- package/src/global.d.ts +20 -0
- package/src/json.ts +63 -48
- package/src/manifest-index.ts +1 -1
- package/src/queue.ts +1 -2
- package/src/resources.ts +1 -1
- package/src/shutdown.ts +21 -14
- package/src/time.ts +54 -19
- package/src/trv.d.ts +1 -1
- package/src/types.ts +30 -15
- package/src/util.ts +20 -22
- package/src/watch.ts +27 -18
- package/support/patch.js +42 -0
- package/support/transformer/metadata.ts +15 -28
- package/support/transformer.concrete-type.ts +19 -21
- package/support/transformer.console-log.ts +13 -19
- package/support/transformer.debug-method.ts +13 -9
- package/support/transformer.dynamic-import.ts +1 -2
- package/support/transformer.function-metadata.ts +6 -4
- package/support/transformer.rewrite-path-import.ts +9 -12
- package/support/polyfill.js +0 -9
package/src/env.ts
CHANGED
|
@@ -3,11 +3,13 @@ import { castKey, castTo } from './types.ts';
|
|
|
3
3
|
const IS_TRUE = /^(true|yes|on|1)$/i;
|
|
4
4
|
const IS_FALSE = /^(false|no|off|0)$/i;
|
|
5
5
|
|
|
6
|
-
export interface EnvData {
|
|
6
|
+
export interface EnvData {}
|
|
7
7
|
|
|
8
8
|
export class EnvProp<T> {
|
|
9
9
|
readonly key: string;
|
|
10
|
-
constructor(key: string) {
|
|
10
|
+
constructor(key: string) {
|
|
11
|
+
this.key = key;
|
|
12
|
+
}
|
|
11
13
|
|
|
12
14
|
/** Set value according to type */
|
|
13
15
|
set(value: T | undefined | null): void {
|
|
@@ -26,14 +28,18 @@ export class EnvProp<T> {
|
|
|
26
28
|
/** Export value */
|
|
27
29
|
export(value?: T | undefined | null): Record<string, string> {
|
|
28
30
|
let out: string;
|
|
29
|
-
|
|
31
|
+
// biome-ignore lint/complexity/noArguments: We want to use arguments here to detect if nothing was truly passed
|
|
32
|
+
if (arguments.length === 0) {
|
|
33
|
+
// If nothing passed in
|
|
30
34
|
out = `${this.value}`;
|
|
31
35
|
} else if (value === undefined || value === null) {
|
|
32
36
|
out = '';
|
|
33
37
|
} else if (Array.isArray(value)) {
|
|
34
38
|
out = value.join(',');
|
|
35
39
|
} else if (typeof value === 'object') {
|
|
36
|
-
out = Object.entries(value)
|
|
40
|
+
out = Object.entries(value)
|
|
41
|
+
.map(([key, keyValue]) => `${key}=${keyValue}`)
|
|
42
|
+
.join(',');
|
|
37
43
|
} else {
|
|
38
44
|
out = `${value}`;
|
|
39
45
|
}
|
|
@@ -41,13 +47,19 @@ export class EnvProp<T> {
|
|
|
41
47
|
}
|
|
42
48
|
|
|
43
49
|
/** Read value as string */
|
|
44
|
-
get value(): string | undefined {
|
|
50
|
+
get value(): string | undefined {
|
|
51
|
+
return process.env[this.key] || undefined;
|
|
52
|
+
}
|
|
45
53
|
|
|
46
54
|
/** Read value as list */
|
|
47
55
|
get list(): string[] | undefined {
|
|
48
56
|
const value = this.value;
|
|
49
|
-
return
|
|
50
|
-
undefined
|
|
57
|
+
return value === undefined || value === ''
|
|
58
|
+
? undefined
|
|
59
|
+
: value
|
|
60
|
+
.split(/[, ]+/g)
|
|
61
|
+
.map(item => item.trim())
|
|
62
|
+
.filter(item => !!item);
|
|
51
63
|
}
|
|
52
64
|
|
|
53
65
|
/** Read value as object */
|
|
@@ -58,7 +70,7 @@ export class EnvProp<T> {
|
|
|
58
70
|
|
|
59
71
|
/** Add values to list */
|
|
60
72
|
add(...items: string[]): void {
|
|
61
|
-
process.env[this.key] = [...
|
|
73
|
+
process.env[this.key] = [...new Set([...(this.list ?? []), ...items])].join(',');
|
|
62
74
|
}
|
|
63
75
|
|
|
64
76
|
/** Read value as int */
|
|
@@ -70,7 +82,7 @@ export class EnvProp<T> {
|
|
|
70
82
|
/** Read value as boolean */
|
|
71
83
|
get bool(): boolean | undefined {
|
|
72
84
|
const value = this.value;
|
|
73
|
-
return
|
|
85
|
+
return value === undefined || value === '' ? undefined : IS_TRUE.test(value);
|
|
74
86
|
}
|
|
75
87
|
|
|
76
88
|
/** Determine if the underlying value is truthy */
|
|
@@ -90,25 +102,33 @@ export class EnvProp<T> {
|
|
|
90
102
|
}
|
|
91
103
|
}
|
|
92
104
|
|
|
93
|
-
type
|
|
94
|
-
[K in keyof EnvData]: Pick<
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
105
|
+
type EnvDataCombinedType = {
|
|
106
|
+
[K in keyof EnvData]: Pick<
|
|
107
|
+
EnvProp<EnvData[K]>,
|
|
108
|
+
| 'key'
|
|
109
|
+
| 'export'
|
|
110
|
+
| 'value'
|
|
111
|
+
| 'set'
|
|
112
|
+
| 'clear'
|
|
113
|
+
| 'isSet'
|
|
114
|
+
| (EnvData[K] extends unknown[] ? 'list' | 'add' : never)
|
|
115
|
+
| (Extract<EnvData[K], object> extends never ? never : 'object')
|
|
116
|
+
| (Extract<EnvData[K], number> extends never ? never : 'int')
|
|
117
|
+
| (Extract<EnvData[K], boolean> extends never ? never : 'bool' | 'isTrue' | 'isFalse')
|
|
118
|
+
>;
|
|
100
119
|
};
|
|
101
120
|
|
|
102
|
-
function delegate<T extends object>(base: T):
|
|
121
|
+
function delegate<T extends object>(base: T): EnvDataCombinedType & T {
|
|
103
122
|
return new Proxy(castTo(base), {
|
|
104
123
|
get(target, property): unknown {
|
|
105
|
-
return typeof property !== 'string'
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
124
|
+
return typeof property !== 'string'
|
|
125
|
+
? undefined
|
|
126
|
+
: property in base
|
|
127
|
+
? base[castKey(property)]
|
|
128
|
+
: (target[castKey<typeof target>(property)] ??= castTo(new EnvProp(property)));
|
|
109
129
|
}
|
|
110
130
|
});
|
|
111
131
|
}
|
|
112
132
|
|
|
113
133
|
/** Basic utils for reading known environment variables */
|
|
114
|
-
export const Env = delegate({});
|
|
134
|
+
export const Env = delegate({});
|
package/src/error.ts
CHANGED
|
@@ -1,13 +1,6 @@
|
|
|
1
1
|
import { castTo } from './types.ts';
|
|
2
2
|
|
|
3
|
-
export type ErrorCategory =
|
|
4
|
-
'general' |
|
|
5
|
-
'notfound' |
|
|
6
|
-
'data' |
|
|
7
|
-
'permissions' |
|
|
8
|
-
'authentication' |
|
|
9
|
-
'timeout' |
|
|
10
|
-
'unavailable';
|
|
3
|
+
export type ErrorCategory = 'general' | 'notfound' | 'data' | 'permissions' | 'authentication' | 'timeout' | 'unavailable';
|
|
11
4
|
|
|
12
5
|
export type RuntimeErrorOptions<T> = Omit<Partial<RuntimeError>, 'details'> & (T extends undefined ? { details?: T } : { details: T });
|
|
13
6
|
|
|
@@ -15,7 +8,6 @@ export type RuntimeErrorOptions<T> = Omit<Partial<RuntimeError>, 'details'> & (T
|
|
|
15
8
|
* Framework error class, with the aim of being extensible
|
|
16
9
|
*/
|
|
17
10
|
export class RuntimeError<T = Record<string, unknown> | undefined> extends Error {
|
|
18
|
-
|
|
19
11
|
static defaultCategory: ErrorCategory = 'general';
|
|
20
12
|
|
|
21
13
|
type: string;
|
|
@@ -28,14 +20,11 @@ export class RuntimeError<T = Record<string, unknown> | undefined> extends Error
|
|
|
28
20
|
*
|
|
29
21
|
* @param message The error message
|
|
30
22
|
*/
|
|
31
|
-
constructor(
|
|
32
|
-
...[message, options]:
|
|
33
|
-
T extends undefined ? ([string] | [string, RuntimeErrorOptions<T>]) : [string, RuntimeErrorOptions<T>]
|
|
34
|
-
) {
|
|
23
|
+
constructor(...[message, options]: T extends undefined ? [string] | [string, RuntimeErrorOptions<T>] : [string, RuntimeErrorOptions<T>]) {
|
|
35
24
|
super(message, options?.cause ? { cause: options.cause } : undefined);
|
|
36
25
|
this.type = options?.type ?? this.constructor.name;
|
|
37
|
-
this.details = options?.details!;
|
|
26
|
+
this.details = options?.details ?? undefined!;
|
|
38
27
|
this.category = options?.category ?? castTo<typeof RuntimeError>(this.constructor).defaultCategory ?? 'general';
|
|
39
28
|
this.at = new Date(options?.at ?? Date.now());
|
|
40
29
|
}
|
|
41
|
-
}
|
|
30
|
+
}
|
package/src/exec.ts
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
import { type ChildProcess,
|
|
1
|
+
import { type ChildProcess, type SpawnOptions, spawn } from 'node:child_process';
|
|
2
2
|
|
|
3
|
-
import {
|
|
4
|
-
import { RuntimeIndex } from './manifest-index.ts';
|
|
5
|
-
import { BinaryUtil, type BinaryArray } from './binary.ts';
|
|
3
|
+
import { type BinaryArray, BinaryUtil } from './binary.ts';
|
|
6
4
|
import { CodecUtil } from './codec.ts';
|
|
5
|
+
import { RuntimeIndex } from './manifest-index.ts';
|
|
6
|
+
import { castTo } from './types.ts';
|
|
7
7
|
|
|
8
8
|
const ResultSymbol = Symbol();
|
|
9
9
|
|
|
@@ -39,6 +39,17 @@ type ExecutionBaseResult = Omit<ExecutionResult, 'stdout' | 'stderr'>;
|
|
|
39
39
|
* Standard utilities for managing executions
|
|
40
40
|
*/
|
|
41
41
|
export class ExecUtil {
|
|
42
|
+
/** Read stream as string from a result */
|
|
43
|
+
static toString(result: ExecutionResult<BinaryArray | string>, stream: 'stdout' | 'stderr' | 'any'): string {
|
|
44
|
+
if (stream === 'any') {
|
|
45
|
+
return this.toString(result, 'stderr') || this.toString(result, 'stdout');
|
|
46
|
+
}
|
|
47
|
+
const value = result[stream];
|
|
48
|
+
if (typeof value === 'string') {
|
|
49
|
+
return value.trim();
|
|
50
|
+
}
|
|
51
|
+
return CodecUtil.toUTF8String(value).trim();
|
|
52
|
+
}
|
|
42
53
|
|
|
43
54
|
/**
|
|
44
55
|
* Take a child process, and some additional options, and produce a promise that
|
|
@@ -49,11 +60,14 @@ export class ExecUtil {
|
|
|
49
60
|
* @param options The options to use to enhance the process
|
|
50
61
|
*/
|
|
51
62
|
static getResult(subProcess: ChildProcess): Promise<ExecutionResult<string>>;
|
|
52
|
-
static getResult(subProcess: ChildProcess, options: { catch?: boolean
|
|
53
|
-
static getResult(subProcess: ChildProcess, options: { catch?: boolean
|
|
54
|
-
static getResult<T extends string | BinaryArray>(
|
|
63
|
+
static getResult(subProcess: ChildProcess, options: { catch?: boolean; binary?: false }): Promise<ExecutionResult<string>>;
|
|
64
|
+
static getResult(subProcess: ChildProcess, options: { catch?: boolean; binary: true }): Promise<ExecutionResult<BinaryArray>>;
|
|
65
|
+
static getResult<T extends string | BinaryArray>(
|
|
66
|
+
subProcess: ChildProcess,
|
|
67
|
+
options: { catch?: boolean; binary?: boolean } = {}
|
|
68
|
+
): Promise<ExecutionResult<T>> {
|
|
55
69
|
const typed: ChildProcess & { [ResultSymbol]?: Promise<ExecutionResult> } = subProcess;
|
|
56
|
-
const result = typed[ResultSymbol] ??= new Promise<ExecutionResult>(resolve => {
|
|
70
|
+
const result = (typed[ResultSymbol] ??= new Promise<ExecutionResult>(resolve => {
|
|
57
71
|
const stdout: BinaryArray[] = [];
|
|
58
72
|
const stderr: BinaryArray[] = [];
|
|
59
73
|
let done = false;
|
|
@@ -65,7 +79,7 @@ export class ExecUtil {
|
|
|
65
79
|
|
|
66
80
|
const buffers = {
|
|
67
81
|
stdout: BinaryUtil.combineBinaryArrays(stdout),
|
|
68
|
-
stderr: BinaryUtil.combineBinaryArrays(stderr)
|
|
82
|
+
stderr: BinaryUtil.combineBinaryArrays(stderr)
|
|
69
83
|
};
|
|
70
84
|
|
|
71
85
|
const final = {
|
|
@@ -74,37 +88,37 @@ export class ExecUtil {
|
|
|
74
88
|
...finalResult
|
|
75
89
|
};
|
|
76
90
|
|
|
77
|
-
resolve(!final.valid ?
|
|
78
|
-
{ ...final, message: `${final.message || final.stderr || final.stdout || 'failed'}` } :
|
|
79
|
-
final
|
|
80
|
-
);
|
|
91
|
+
resolve(!final.valid ? { ...final, message: `${final.message || final.stderr || final.stdout || 'failed'}` } : final);
|
|
81
92
|
};
|
|
82
93
|
|
|
83
94
|
subProcess.stdout?.on('data', data => stdout.push(CodecUtil.readChunk(data, subProcess.stdout?.readableEncoding)));
|
|
84
95
|
subProcess.stderr?.on('data', data => stderr.push(CodecUtil.readChunk(data, subProcess.stderr?.readableEncoding)));
|
|
85
96
|
|
|
86
|
-
subProcess.on('error', (error: Error) =>
|
|
87
|
-
finish({ code: 1, message: error.message, valid: false }));
|
|
97
|
+
subProcess.on('error', (error: Error) => finish({ code: 1, message: error.message, valid: false }));
|
|
88
98
|
|
|
89
|
-
subProcess.on('close', (code: number) =>
|
|
90
|
-
finish({ code, valid: code === null || code === 0 }));
|
|
99
|
+
subProcess.on('close', (code: number) => finish({ code, valid: code === null || code === 0 }));
|
|
91
100
|
|
|
92
|
-
if (subProcess.exitCode !== null) {
|
|
101
|
+
if (subProcess.exitCode !== null) {
|
|
102
|
+
// We are already done
|
|
93
103
|
finish({ code: subProcess.exitCode, valid: subProcess.exitCode === 0 });
|
|
94
104
|
}
|
|
95
|
-
});
|
|
96
|
-
|
|
97
|
-
return castTo(options.catch ? result : result.then(executionResult => {
|
|
98
|
-
if (executionResult.valid) {
|
|
99
|
-
return executionResult;
|
|
100
|
-
} else {
|
|
101
|
-
throw new Error(executionResult.message);
|
|
102
|
-
}
|
|
103
105
|
}));
|
|
106
|
+
|
|
107
|
+
return castTo(
|
|
108
|
+
options.catch
|
|
109
|
+
? result
|
|
110
|
+
: result.then(executionResult => {
|
|
111
|
+
if (executionResult.valid) {
|
|
112
|
+
return executionResult;
|
|
113
|
+
} else {
|
|
114
|
+
throw new Error(executionResult.message);
|
|
115
|
+
}
|
|
116
|
+
})
|
|
117
|
+
);
|
|
104
118
|
}
|
|
105
119
|
|
|
106
120
|
/** Spawn a package command */
|
|
107
121
|
static spawnPackageCommand(cmd: string, args: string[], config: SpawnOptions = {}): ChildProcess {
|
|
108
122
|
return spawn(process.argv0, [RuntimeIndex.resolvePackageCommand(cmd), ...args], config);
|
|
109
123
|
}
|
|
110
|
-
}
|
|
124
|
+
}
|
package/src/file-loader.ts
CHANGED
|
@@ -2,14 +2,13 @@ import { createReadStream } from 'node:fs';
|
|
|
2
2
|
import fs from 'node:fs/promises';
|
|
3
3
|
import path from 'node:path';
|
|
4
4
|
|
|
5
|
+
import { type BinaryArray, type BinaryStream, BinaryUtil } from './binary.ts';
|
|
5
6
|
import { RuntimeError } from './error.ts';
|
|
6
|
-
import { BinaryUtil, type BinaryArray, type BinaryStream } from './binary.ts';
|
|
7
7
|
|
|
8
8
|
/**
|
|
9
9
|
* File loader that will search for files across the provided search paths
|
|
10
10
|
*/
|
|
11
11
|
export class FileLoader {
|
|
12
|
-
|
|
13
12
|
#searchPaths: readonly string[];
|
|
14
13
|
|
|
15
14
|
constructor(paths: string[]) {
|
|
@@ -30,7 +29,7 @@ export class FileLoader {
|
|
|
30
29
|
async resolve(relativePath: string): Promise<string> {
|
|
31
30
|
for (const sub of this.searchPaths) {
|
|
32
31
|
const resolved = path.join(sub, relativePath);
|
|
33
|
-
if (await fs.stat(resolved
|
|
32
|
+
if (await fs.stat(resolved, { throwIfNoEntry: false })) {
|
|
34
33
|
return resolved;
|
|
35
34
|
}
|
|
36
35
|
}
|
|
@@ -41,7 +40,7 @@ export class FileLoader {
|
|
|
41
40
|
* Read a file as utf8 text, after resolving the path
|
|
42
41
|
* @param relativePath The path to read
|
|
43
42
|
*/
|
|
44
|
-
async
|
|
43
|
+
async readUTF8(relativePath: string): Promise<string> {
|
|
45
44
|
const file = await this.resolve(relativePath);
|
|
46
45
|
return fs.readFile(file, 'utf8');
|
|
47
46
|
}
|
|
@@ -72,4 +71,4 @@ export class FileLoader {
|
|
|
72
71
|
const buffer = BinaryUtil.binaryArrayToBuffer(await this.readBinaryArray(relativePath));
|
|
73
72
|
return new File([buffer], path.basename(relativePath));
|
|
74
73
|
}
|
|
75
|
-
}
|
|
74
|
+
}
|
package/src/function.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { ManifestModuleUtil } from '@travetto/manifest';
|
|
2
2
|
|
|
3
|
-
export type FunctionMetadataTag = { hash: number
|
|
3
|
+
export type FunctionMetadataTag = { hash: number; lines: [start: number, end: number, bodyStart?: number] };
|
|
4
4
|
export type FunctionMetadata = FunctionMetadataTag & {
|
|
5
5
|
id: string;
|
|
6
6
|
import: string;
|
|
@@ -26,13 +26,16 @@ const pending = new Set<Function>([]);
|
|
|
26
26
|
* @private
|
|
27
27
|
*/
|
|
28
28
|
export function registerFunction(
|
|
29
|
-
input: Function,
|
|
30
|
-
|
|
29
|
+
input: Function,
|
|
30
|
+
[module, relativePath]: [string, string],
|
|
31
|
+
tag: FunctionMetadataTag,
|
|
32
|
+
methods?: Record<string, FunctionMetadataTag>,
|
|
33
|
+
abstract?: boolean
|
|
31
34
|
): void {
|
|
32
35
|
const modulePath = ManifestModuleUtil.withoutSourceExtension(relativePath);
|
|
33
36
|
|
|
34
37
|
const metadata: FunctionMetadata = {
|
|
35
|
-
id:
|
|
38
|
+
id: input.name ? `${module}:${modulePath}#${input.name}` : `${module}:${modulePath}`,
|
|
36
39
|
import: `${module}/${relativePath}`,
|
|
37
40
|
module,
|
|
38
41
|
modulePath,
|
|
@@ -65,5 +68,10 @@ export function describeFunction(input?: Function): FunctionMetadata | undefined
|
|
|
65
68
|
|
|
66
69
|
const foreignTypeRegistry = new Map<string, Function>();
|
|
67
70
|
export function foreignType(id: string): Function {
|
|
68
|
-
return foreignTypeRegistry.getOrInsert(
|
|
69
|
-
|
|
71
|
+
return foreignTypeRegistry.getOrInsert(
|
|
72
|
+
id,
|
|
73
|
+
class {
|
|
74
|
+
static Ⲑid = id;
|
|
75
|
+
}
|
|
76
|
+
);
|
|
77
|
+
}
|
package/src/global.d.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import './types';
|
|
2
2
|
|
|
3
3
|
declare const write: unique symbol;
|
|
4
|
+
|
|
4
5
|
declare global {
|
|
5
6
|
// https://github.com/microsoft/TypeScript/issues/59012
|
|
6
7
|
interface WritableStreamDefaultWriter<W = any> {
|
|
@@ -52,6 +53,18 @@ declare module 'buffer' {
|
|
|
52
53
|
interface File { }
|
|
53
54
|
}
|
|
54
55
|
|
|
56
|
+
declare module 'node:buffer' {
|
|
57
|
+
/**
|
|
58
|
+
* @concrete node:buffer#Blob
|
|
59
|
+
*/
|
|
60
|
+
interface Blob { }
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* @concrete node:buffer#File
|
|
64
|
+
*/
|
|
65
|
+
interface File { }
|
|
66
|
+
}
|
|
67
|
+
|
|
55
68
|
declare module 'stream' {
|
|
56
69
|
/**
|
|
57
70
|
* @concrete node:stream#Readable
|
|
@@ -64,4 +77,11 @@ declare module 'stream/web' {
|
|
|
64
77
|
* @concrete node:stream/web#ReadableStream
|
|
65
78
|
*/
|
|
66
79
|
interface ReadableStream { }
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
// Remove once node 26 types are released
|
|
83
|
+
declare module 'node:fs' {
|
|
84
|
+
interface StatOptions {
|
|
85
|
+
throwIfNoEntry?: boolean;
|
|
86
|
+
}
|
|
67
87
|
}
|
package/src/json.ts
CHANGED
|
@@ -1,27 +1,35 @@
|
|
|
1
|
+
import { AssertionError } from 'node:assert';
|
|
2
|
+
|
|
1
3
|
import type { BinaryArray } from './binary.ts';
|
|
2
4
|
import { CodecUtil } from './codec.ts';
|
|
3
5
|
import { RuntimeError, type RuntimeErrorOptions } from './error.ts';
|
|
4
|
-
import { castTo } from './types.ts';
|
|
6
|
+
import { type Any, castTo } from './types.ts';
|
|
7
|
+
|
|
8
|
+
const VALID_JSON_ERROR_TYPES = ['runtime', 'plain', 'assert'] as const;
|
|
9
|
+
const VALID_JSON_ERROR_TYPE_SET = new Set<unknown>(VALID_JSON_ERROR_TYPES);
|
|
5
10
|
|
|
6
11
|
type JSONTransformer = (this: unknown, key: string, value: unknown) => unknown;
|
|
7
|
-
type JSONOutputConfig = { indent?: number
|
|
12
|
+
type JSONOutputConfig = { indent?: number; replacer?: JSONTransformer };
|
|
8
13
|
type JSONInputConfig = { reviver?: JSONTransformer };
|
|
9
14
|
type JSONCloneConfig = JSONOutputConfig & JSONInputConfig;
|
|
10
|
-
type
|
|
11
|
-
type JSONError =
|
|
12
|
-
ErrorShape<'runtime', RuntimeErrorOptions<Record<string, unknown>>> |
|
|
13
|
-
ErrorShape<'plain', { name: string }>;
|
|
15
|
+
type JSONError = { $trv: (typeof VALID_JSON_ERROR_TYPES)[number]; name?: string } & Partial<RuntimeErrorOptions<Record<string, unknown>>>;
|
|
14
16
|
|
|
15
17
|
Object.defineProperty(BigInt.prototype, 'toJSON', {
|
|
16
|
-
value() {
|
|
18
|
+
value() {
|
|
19
|
+
return `${this}n`;
|
|
20
|
+
}
|
|
17
21
|
});
|
|
18
22
|
|
|
19
23
|
Object.defineProperty(Error.prototype, 'toJSON', {
|
|
20
|
-
value() {
|
|
24
|
+
value() {
|
|
25
|
+
return JSONUtil.errorToJSONError(this);
|
|
26
|
+
}
|
|
21
27
|
});
|
|
22
28
|
|
|
23
29
|
Object.defineProperty(RuntimeError.prototype, 'toJSON', {
|
|
24
|
-
value() {
|
|
30
|
+
value() {
|
|
31
|
+
return JSONUtil.errorToJSONError(this);
|
|
32
|
+
}
|
|
25
33
|
});
|
|
26
34
|
|
|
27
35
|
const ISO_8601_REGEX = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})?$/;
|
|
@@ -29,7 +37,6 @@ const BIGINT_REGEX = /^-?\d+n$/;
|
|
|
29
37
|
|
|
30
38
|
/** Utilities for JSON */
|
|
31
39
|
export class JSONUtil {
|
|
32
|
-
|
|
33
40
|
static includeStackTraces = false;
|
|
34
41
|
|
|
35
42
|
static TRANSMIT_REVIVER: JSONTransformer = function (this: unknown, key: string, value: unknown): unknown {
|
|
@@ -45,55 +52,63 @@ export class JSONUtil {
|
|
|
45
52
|
return value;
|
|
46
53
|
};
|
|
47
54
|
|
|
48
|
-
|
|
49
55
|
static isJSONError(value: unknown): value is JSONError {
|
|
50
|
-
return typeof value === 'object' && value !== null && '$trv' in value && (
|
|
51
|
-
value.$trv === 'runtime' || value.$trv === 'plain'
|
|
52
|
-
);
|
|
56
|
+
return typeof value === 'object' && value !== null && '$trv' in value && VALID_JSON_ERROR_TYPE_SET.has(value.$trv);
|
|
53
57
|
}
|
|
54
58
|
|
|
55
59
|
/** Convert from JSON object */
|
|
56
|
-
static jsonErrorToError(error: JSONError): Error
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
60
|
+
static jsonErrorToError(error: JSONError): Error {
|
|
61
|
+
const { $trv, message, stack, name, ...rest } = error;
|
|
62
|
+
let response: Error;
|
|
63
|
+
switch ($trv) {
|
|
64
|
+
case 'runtime':
|
|
65
|
+
response = new RuntimeError(message!, castTo<Any>(rest));
|
|
66
|
+
break;
|
|
67
|
+
case 'assert':
|
|
68
|
+
response = new AssertionError({ message, ...rest });
|
|
69
|
+
break;
|
|
70
|
+
case 'plain':
|
|
71
|
+
response = new Error(message!);
|
|
72
|
+
break;
|
|
73
|
+
}
|
|
74
|
+
response.stack = stack;
|
|
75
|
+
if (name) {
|
|
76
|
+
response.name = name;
|
|
70
77
|
}
|
|
78
|
+
return response;
|
|
71
79
|
}
|
|
72
80
|
|
|
73
81
|
/**
|
|
74
82
|
* Serializes an error to a basic object
|
|
75
83
|
*/
|
|
76
|
-
static errorToJSONError(error:
|
|
84
|
+
static errorToJSONError(error: Error, includeStack?: boolean): JSONError | undefined {
|
|
77
85
|
includeStack ??= JSONUtil.includeStackTraces;
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
} else {
|
|
90
|
-
return {
|
|
91
|
-
$trv: 'plain',
|
|
92
|
-
message: error.message,
|
|
93
|
-
name: error.name,
|
|
94
|
-
...(includeStack ? { stack: error.stack } : undefined)
|
|
95
|
-
};
|
|
86
|
+
let $trv: JSONError['$trv'];
|
|
87
|
+
switch (true) {
|
|
88
|
+
case error instanceof RuntimeError:
|
|
89
|
+
$trv = 'runtime';
|
|
90
|
+
break;
|
|
91
|
+
case error instanceof AssertionError:
|
|
92
|
+
$trv = 'assert';
|
|
93
|
+
break;
|
|
94
|
+
default:
|
|
95
|
+
$trv = 'plain';
|
|
96
|
+
break;
|
|
96
97
|
}
|
|
98
|
+
return {
|
|
99
|
+
$trv,
|
|
100
|
+
message: error.message,
|
|
101
|
+
...(error.cause ? { cause: `${error.cause}` } : undefined),
|
|
102
|
+
...(includeStack ? { stack: error.stack } : undefined),
|
|
103
|
+
...(error instanceof RuntimeError
|
|
104
|
+
? {
|
|
105
|
+
category: error.category,
|
|
106
|
+
type: error.type,
|
|
107
|
+
at: error.at,
|
|
108
|
+
...(error.details ? { details: error.details } : undefined!)
|
|
109
|
+
}
|
|
110
|
+
: {})
|
|
111
|
+
};
|
|
97
112
|
}
|
|
98
113
|
|
|
99
114
|
/** UTF8 string to JSON */
|
|
@@ -152,4 +167,4 @@ export class JSONUtil {
|
|
|
152
167
|
static cloneFromTransmit<T, R = T>(input: T): R {
|
|
153
168
|
return JSONUtil.clone<T, R>(input, { reviver: JSONUtil.TRANSMIT_REVIVER });
|
|
154
169
|
}
|
|
155
|
-
}
|
|
170
|
+
}
|
package/src/manifest-index.ts
CHANGED
package/src/queue.ts
CHANGED
|
@@ -2,7 +2,6 @@
|
|
|
2
2
|
* An asynchronous queue
|
|
3
3
|
*/
|
|
4
4
|
export class AsyncQueue<X> implements AsyncIterator<X>, AsyncIterable<X> {
|
|
5
|
-
|
|
6
5
|
#buffer: X[] = [];
|
|
7
6
|
#done = false;
|
|
8
7
|
#ready = Promise.withResolvers<void>();
|
|
@@ -59,4 +58,4 @@ export class AsyncQueue<X> implements AsyncIterator<X>, AsyncIterable<X> {
|
|
|
59
58
|
this.#ready.reject(error);
|
|
60
59
|
return { value: undefined, done: this.#done };
|
|
61
60
|
}
|
|
62
|
-
}
|
|
61
|
+
}
|
package/src/resources.ts
CHANGED
package/src/shutdown.ts
CHANGED
|
@@ -1,17 +1,21 @@
|
|
|
1
1
|
import type { ChildProcess } from 'node:child_process';
|
|
2
2
|
|
|
3
3
|
import { Env } from './env.ts';
|
|
4
|
-
import { Util } from './util.ts';
|
|
5
4
|
import { TimeUtil } from './time.ts';
|
|
5
|
+
import { Util } from './util.ts';
|
|
6
6
|
|
|
7
|
-
const MAPPING = [
|
|
8
|
-
|
|
7
|
+
const MAPPING = [
|
|
8
|
+
['restart', 200],
|
|
9
|
+
['error', 1],
|
|
10
|
+
['quit', 0]
|
|
11
|
+
] as const;
|
|
12
|
+
export type ShutdownReason = (typeof MAPPING)[number][0];
|
|
9
13
|
|
|
10
14
|
const REASON_TO_CODE = new Map<ShutdownReason, number>(MAPPING);
|
|
11
15
|
const CODE_TO_REASON = new Map<number, ShutdownReason>(MAPPING.map(([k, v]) => [v, k]));
|
|
12
16
|
|
|
13
17
|
type Handler = (event: Event) => unknown;
|
|
14
|
-
type ShutdownEvent = { reason?: ShutdownReason
|
|
18
|
+
type ShutdownEvent = { reason?: ShutdownReason; mode?: 'exit' | 'interrupt' };
|
|
15
19
|
|
|
16
20
|
const isShutdownEvent = (event: unknown): event is ShutdownEvent =>
|
|
17
21
|
typeof event === 'object' && event !== null && 'type' in event && event.type === 'shutdown';
|
|
@@ -33,14 +37,20 @@ export class ShutdownManager {
|
|
|
33
37
|
static #controller = new AbortController();
|
|
34
38
|
|
|
35
39
|
static {
|
|
36
|
-
this.#controller.signal.addEventListener = (_: 'abort', listener: Handler): void => {
|
|
37
|
-
|
|
40
|
+
this.#controller.signal.addEventListener = (_: 'abort', listener: Handler): void => {
|
|
41
|
+
this.#registered.add(listener);
|
|
42
|
+
};
|
|
43
|
+
this.#controller.signal.removeEventListener = (_: 'abort', listener: Handler): void => {
|
|
44
|
+
this.#registered.delete(listener);
|
|
45
|
+
};
|
|
38
46
|
try {
|
|
39
47
|
process
|
|
40
|
-
.on('message', event => {
|
|
48
|
+
.on('message', event => {
|
|
49
|
+
isShutdownEvent(event) && this.shutdown(event);
|
|
50
|
+
})
|
|
41
51
|
.on('SIGINT', () => this.shutdown({ mode: 'interrupt' }))
|
|
42
52
|
.on('SIGTERM', () => this.shutdown());
|
|
43
|
-
} catch {
|
|
53
|
+
} catch {}
|
|
44
54
|
}
|
|
45
55
|
|
|
46
56
|
static get signal(): AbortSignal {
|
|
@@ -60,7 +70,7 @@ export class ShutdownManager {
|
|
|
60
70
|
|
|
61
71
|
/** Trigger a watch signal signal to a subprocess */
|
|
62
72
|
static async shutdownChild(subprocess: ChildProcess, config?: ShutdownEvent): Promise<void> {
|
|
63
|
-
subprocess?.send
|
|
73
|
+
subprocess?.send?.({ type: 'shutdown', ...config });
|
|
64
74
|
}
|
|
65
75
|
|
|
66
76
|
/**
|
|
@@ -87,10 +97,7 @@ export class ShutdownManager {
|
|
|
87
97
|
this.#controller.abort('Shutdown started');
|
|
88
98
|
console.debug('Shutdown started', context);
|
|
89
99
|
|
|
90
|
-
const winner = await Promise.race([
|
|
91
|
-
Util.nonBlockingTimeout(timeout).then(() => this),
|
|
92
|
-
Promise.all([...this.#registered].map(wrapped))
|
|
93
|
-
]);
|
|
100
|
+
const winner = await Promise.race([Util.nonBlockingTimeout(timeout).then(() => this), Promise.all([...this.#registered].map(wrapped))]);
|
|
94
101
|
|
|
95
102
|
if (winner !== this) {
|
|
96
103
|
console.debug('Shutdown completed', context);
|
|
@@ -102,4 +109,4 @@ export class ShutdownManager {
|
|
|
102
109
|
process.exit();
|
|
103
110
|
}
|
|
104
111
|
}
|
|
105
|
-
}
|
|
112
|
+
}
|