@orpc/shared 2.0.0-beta.5 → 2.0.0-beta.50
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 +137 -102
- package/dist/args.d.ts +2 -0
- package/dist/args.js +5 -0
- package/dist/array.d.ts +5 -0
- package/dist/array.js +13 -0
- package/dist/bigint.d.ts +9 -0
- package/dist/bigint.js +15 -0
- package/dist/buffer.d.ts +18 -0
- package/dist/buffer.js +54 -0
- package/dist/compare.d.ts +1 -0
- package/dist/compare.js +26 -0
- package/dist/consts.d.ts +1 -0
- package/dist/consts.js +3 -0
- package/dist/error.d.ts +1 -0
- package/dist/error.js +5 -0
- package/dist/function.d.ts +12 -0
- package/dist/function.js +33 -0
- package/dist/http.d.ts +58 -0
- package/dist/http.js +147 -0
- package/dist/id.d.ts +8 -0
- package/dist/id.js +13 -0
- package/dist/index.d.ts +26 -306
- package/dist/index.js +23 -0
- package/dist/interceptor.d.ts +60 -0
- package/dist/interceptor.js +119 -0
- package/dist/iterator.d.ts +56 -0
- package/dist/iterator.js +141 -0
- package/dist/object.d.ts +62 -0
- package/dist/object.js +194 -0
- package/dist/plugin.d.ts +12 -0
- package/dist/plugin.js +45 -0
- package/dist/promise.d.ts +17 -0
- package/dist/promise.js +32 -0
- package/dist/proxy.d.ts +12 -0
- package/dist/proxy.js +25 -0
- package/dist/queue.d.ts +16 -0
- package/dist/queue.js +64 -0
- package/dist/regex.d.ts +9 -0
- package/dist/regex.js +11 -0
- package/dist/signal.d.ts +23 -0
- package/dist/signal.js +88 -0
- package/dist/stream.d.ts +48 -0
- package/dist/stream.js +129 -0
- package/dist/tracing.d.ts +73 -0
- package/dist/tracing.js +69 -0
- package/dist/types.d.ts +23 -0
- package/dist/value.d.ts +2 -0
- package/dist/value.js +6 -0
- package/package.json +22 -30
- package/dist/index.d.mts +0 -306
- package/dist/index.mjs +0 -892
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
import { PromiseWithError, ThrowableError } from "./types.js";
|
|
2
|
+
import { Promisable } from "type-fest";
|
|
3
|
+
export type InterceptableOptions = Record<string, any>;
|
|
4
|
+
export type InterceptorOptions<TOptions extends InterceptableOptions, TResult> = Omit<TOptions, "next"> & {
|
|
5
|
+
next(options?: TOptions): TResult;
|
|
6
|
+
};
|
|
7
|
+
export type Interceptor<TOptions extends InterceptableOptions, TResult> = (options: InterceptorOptions<TOptions, TResult>) => TResult;
|
|
8
|
+
/**
|
|
9
|
+
* Can used for interceptors or middlewares
|
|
10
|
+
*/
|
|
11
|
+
export declare function onStart<T, TOptions extends {
|
|
12
|
+
next: () => any;
|
|
13
|
+
}, TRest extends any[]>(callback: NoInfer<(options: TOptions, ...rest: TRest) => Promisable<void>>): (options: TOptions, ...rest: TRest) => T | Promise<Awaited<ReturnType<TOptions["next"]>>>;
|
|
14
|
+
/**
|
|
15
|
+
* Can used for interceptors or middlewares
|
|
16
|
+
*/
|
|
17
|
+
export declare function onSuccess<T, TOptions extends {
|
|
18
|
+
next: () => any;
|
|
19
|
+
}, TRest extends any[]>(callback: NoInfer<(result: Awaited<ReturnType<TOptions["next"]>>, options: TOptions, ...rest: TRest) => Promisable<void>>): (options: TOptions, ...rest: TRest) => T | Promise<Awaited<ReturnType<TOptions["next"]>>>;
|
|
20
|
+
/**
|
|
21
|
+
* Creates an interceptor or middleware that invokes a callback whenever an error
|
|
22
|
+
* is thrown. The error is rethrown after the callback completes.
|
|
23
|
+
*
|
|
24
|
+
* @see {@link https://orpc.dev/docs/adapters/fetch-api | Fetch API Adapter}
|
|
25
|
+
*/
|
|
26
|
+
export declare function onError<T, TOptions extends {
|
|
27
|
+
next: () => any;
|
|
28
|
+
}, TRest extends any[]>(callback: NoInfer<(error: ReturnType<TOptions["next"]> extends PromiseWithError<any, infer E> ? E : ThrowableError, options: TOptions, ...rest: TRest) => Promisable<void>>): (options: TOptions, ...rest: TRest) => T | Promise<Awaited<ReturnType<TOptions["next"]>>>;
|
|
29
|
+
export type OnFinishState<TResult, TError> = [error: TError, data: undefined, isSuccess: false] | [error: null, data: TResult, isSuccess: true];
|
|
30
|
+
/**
|
|
31
|
+
* Can used for interceptors or middlewares
|
|
32
|
+
*/
|
|
33
|
+
export declare function onFinish<T, TOptions extends {
|
|
34
|
+
next: () => any;
|
|
35
|
+
}, TRest extends any[]>(callback: NoInfer<(state: OnFinishState<Awaited<ReturnType<TOptions["next"]>>, ReturnType<TOptions["next"]> extends PromiseWithError<any, infer E> ? E : ThrowableError>, options: TOptions, ...rest: TRest) => Promisable<void>>): (options: TOptions, ...rest: TRest) => T | Promise<Awaited<ReturnType<TOptions["next"]>>>;
|
|
36
|
+
/**
|
|
37
|
+
* Creates a middleware or interceptor that invokes a callback when the returned async
|
|
38
|
+
* iterator object throws an error while being consumed.
|
|
39
|
+
*
|
|
40
|
+
* This does not replace the `onError`. `onError` only fires on the
|
|
41
|
+
* initial call (before the interceptor returns the iterator), whereas this
|
|
42
|
+
* callback only fires while consuming the iterator. Use both together to
|
|
43
|
+
* catch all possible errors.
|
|
44
|
+
*/
|
|
45
|
+
export declare function onAsyncIteratorObjectError<T, TOptions extends {
|
|
46
|
+
next: () => any;
|
|
47
|
+
}, TRest extends any[]>(callback: NoInfer<(error: ThrowableError | (ReturnType<TOptions["next"]> extends PromiseWithError<any, infer E> ? E : ThrowableError), options: TOptions, ...rest: TRest) => Promisable<void>>): (options: TOptions, ...rest: TRest) => T | Promise<Awaited<ReturnType<TOptions["next"]>>>;
|
|
48
|
+
/**
|
|
49
|
+
* Creates an interceptor that invokes a callback when the returned readable
|
|
50
|
+
* stream errors while being consumed.
|
|
51
|
+
*
|
|
52
|
+
* This does not replace the `onError`. `onError` only fires on the
|
|
53
|
+
* initial call (before the interceptor returns the stream), whereas this
|
|
54
|
+
* callback only fires while consuming the stream. Use both together to catch
|
|
55
|
+
* all possible errors.
|
|
56
|
+
*/
|
|
57
|
+
export declare function onReadableStreamError<T, TOptions extends {
|
|
58
|
+
next: () => any;
|
|
59
|
+
}, TRest extends any[]>(callback: NoInfer<(error: ThrowableError | (ReturnType<TOptions["next"]> extends PromiseWithError<any, infer E> ? E : ThrowableError), options: TOptions, ...rest: TRest) => Promisable<void>>): (options: TOptions, ...rest: TRest) => T | Promise<Awaited<ReturnType<TOptions["next"]>>>;
|
|
60
|
+
export declare function intercept<TOptions extends InterceptableOptions, TResult>(interceptors: undefined | Interceptor<TOptions, TResult>[], options: NoInfer<TOptions>, main: NoInfer<(options: TOptions) => TResult>): TResult;
|
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
import { wrapAsyncIterator } from "./iterator.js";
|
|
2
|
+
import { override } from "./proxy.js";
|
|
3
|
+
import { wrapReadableStream } from "./stream.js";
|
|
4
|
+
import { isAsyncIteratorObject } from "@standard-server/shared";
|
|
5
|
+
// src/interceptor.ts
|
|
6
|
+
/**
|
|
7
|
+
* Can used for interceptors or middlewares
|
|
8
|
+
*/
|
|
9
|
+
function onStart(callback) {
|
|
10
|
+
return async (options, ...rest) => {
|
|
11
|
+
await callback(options, ...rest);
|
|
12
|
+
return await options.next();
|
|
13
|
+
};
|
|
14
|
+
}
|
|
15
|
+
/**
|
|
16
|
+
* Can used for interceptors or middlewares
|
|
17
|
+
*/
|
|
18
|
+
function onSuccess(callback) {
|
|
19
|
+
return async (options, ...rest) => {
|
|
20
|
+
const result = await options.next();
|
|
21
|
+
await callback(result, options, ...rest);
|
|
22
|
+
return result;
|
|
23
|
+
};
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* Creates an interceptor or middleware that invokes a callback whenever an error
|
|
27
|
+
* is thrown. The error is rethrown after the callback completes.
|
|
28
|
+
*
|
|
29
|
+
* @see {@link https://orpc.dev/docs/adapters/fetch-api | Fetch API Adapter}
|
|
30
|
+
*/
|
|
31
|
+
function onError(callback) {
|
|
32
|
+
return async (options, ...rest) => {
|
|
33
|
+
try {
|
|
34
|
+
return await options.next();
|
|
35
|
+
} catch (error) {
|
|
36
|
+
await callback(error, options, ...rest);
|
|
37
|
+
throw error;
|
|
38
|
+
}
|
|
39
|
+
};
|
|
40
|
+
}
|
|
41
|
+
/**
|
|
42
|
+
* Can used for interceptors or middlewares
|
|
43
|
+
*/
|
|
44
|
+
function onFinish(callback) {
|
|
45
|
+
return async (options, ...rest) => {
|
|
46
|
+
let state;
|
|
47
|
+
try {
|
|
48
|
+
const result = await options.next();
|
|
49
|
+
state = [
|
|
50
|
+
null,
|
|
51
|
+
result,
|
|
52
|
+
true
|
|
53
|
+
];
|
|
54
|
+
return result;
|
|
55
|
+
} catch (error) {
|
|
56
|
+
state = [
|
|
57
|
+
error,
|
|
58
|
+
void 0,
|
|
59
|
+
false
|
|
60
|
+
];
|
|
61
|
+
throw error;
|
|
62
|
+
} finally {
|
|
63
|
+
await callback(state, options, ...rest);
|
|
64
|
+
}
|
|
65
|
+
};
|
|
66
|
+
}
|
|
67
|
+
/**
|
|
68
|
+
* Creates a middleware or interceptor that invokes a callback when the returned async
|
|
69
|
+
* iterator object throws an error while being consumed.
|
|
70
|
+
*
|
|
71
|
+
* This does not replace the `onError`. `onError` only fires on the
|
|
72
|
+
* initial call (before the interceptor returns the iterator), whereas this
|
|
73
|
+
* callback only fires while consuming the iterator. Use both together to
|
|
74
|
+
* catch all possible errors.
|
|
75
|
+
*/
|
|
76
|
+
function onAsyncIteratorObjectError(callback) {
|
|
77
|
+
return async (options, ...rest) => {
|
|
78
|
+
const output = await options.next();
|
|
79
|
+
if (!isAsyncIteratorObject(output)) return output;
|
|
80
|
+
/**
|
|
81
|
+
* @warning
|
|
82
|
+
* Remember use `override` for AsyncIteratorObject to remain other special properties
|
|
83
|
+
*/
|
|
84
|
+
return override(output, wrapAsyncIterator(output, { onError: (error) => callback(error, options, ...rest) }));
|
|
85
|
+
};
|
|
86
|
+
}
|
|
87
|
+
/**
|
|
88
|
+
* Creates an interceptor that invokes a callback when the returned readable
|
|
89
|
+
* stream errors while being consumed.
|
|
90
|
+
*
|
|
91
|
+
* This does not replace the `onError`. `onError` only fires on the
|
|
92
|
+
* initial call (before the interceptor returns the stream), whereas this
|
|
93
|
+
* callback only fires while consuming the stream. Use both together to catch
|
|
94
|
+
* all possible errors.
|
|
95
|
+
*/
|
|
96
|
+
function onReadableStreamError(callback) {
|
|
97
|
+
return async (options, ...rest) => {
|
|
98
|
+
const output = await options.next();
|
|
99
|
+
if (!(output instanceof ReadableStream)) return output;
|
|
100
|
+
/**
|
|
101
|
+
* @warning
|
|
102
|
+
* Remember use `override` for ReadableStream to remain other special properties
|
|
103
|
+
*/
|
|
104
|
+
return override(output, wrapReadableStream(output, { onError: (error) => callback(error, options, ...rest) }));
|
|
105
|
+
};
|
|
106
|
+
}
|
|
107
|
+
function intercept(interceptors, options, main) {
|
|
108
|
+
if (!interceptors?.length) return main(options);
|
|
109
|
+
const next = (options, index) => {
|
|
110
|
+
const interceptor = interceptors[index];
|
|
111
|
+
if (!interceptor) return main(options);
|
|
112
|
+
return interceptor({
|
|
113
|
+
...options,
|
|
114
|
+
next: (newOptions = options) => next(newOptions, index + 1)
|
|
115
|
+
});
|
|
116
|
+
};
|
|
117
|
+
return next(options, 0);
|
|
118
|
+
}
|
|
119
|
+
export { intercept, onAsyncIteratorObjectError, onError, onFinish, onReadableStreamError, onStart, onSuccess };
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
import { StartSpanOptions } from "./tracing.js";
|
|
2
|
+
import { PromiseWithError, ThrowableError } from "./types.js";
|
|
3
|
+
import { AsyncIteratorClass } from "@standard-server/shared";
|
|
4
|
+
import { Promisable } from "type-fest";
|
|
5
|
+
export interface WrapAsyncIteratorOptions<TYield, TReturn, TMappedYield, TMappedReturn> {
|
|
6
|
+
/**
|
|
7
|
+
* Any call to the original iterator will be executed inside this function.
|
|
8
|
+
* Useful when you want execution to happen within a specific context,
|
|
9
|
+
* such as AsyncLocalStorage.
|
|
10
|
+
*/
|
|
11
|
+
runWith?: (<T>(run: () => Promise<T>) => Promisable<T>) | undefined;
|
|
12
|
+
mapResult?: ((result: IteratorResult<TYield, TReturn>) => Promisable<IteratorResult<TMappedYield, TMappedReturn>>) | undefined;
|
|
13
|
+
mapError?: ((error: ThrowableError) => Promisable<ThrowableError>) | undefined;
|
|
14
|
+
onError?: ((error: ThrowableError) => Promisable<void>) | undefined;
|
|
15
|
+
/**
|
|
16
|
+
* Execute after the stream finishes or is cancelled.
|
|
17
|
+
*/
|
|
18
|
+
onFinish?: (() => Promisable<void>) | undefined;
|
|
19
|
+
}
|
|
20
|
+
export declare function wrapAsyncIterator<TYield, TReturn, TMappedYield = TYield, TMappedReturn = TReturn>(iterator: AsyncIterator<TYield, TReturn>, { runWith, mapResult, mapError, onError, onFinish }: WrapAsyncIteratorOptions<TYield, TReturn, TMappedYield, TMappedReturn>): NoInfer<AsyncIteratorClass<TMappedYield, TMappedReturn>>;
|
|
21
|
+
export declare function traceAsyncIterator<T, TReturn, TNext>(options: StartSpanOptions | string, iterator: AsyncIterator<T, TReturn, TNext>): AsyncIteratorClass<T, TReturn, TNext>;
|
|
22
|
+
export declare function replicateAsyncIterator<T, TReturn, TNext>(source: AsyncIterator<T, TReturn, TNext>, count: number): AsyncIteratorClass<T, TReturn, TNext>[];
|
|
23
|
+
export interface ConsumeAsyncIteratorOptions<T, TReturn, TError> {
|
|
24
|
+
/**
|
|
25
|
+
* Called on each event
|
|
26
|
+
*/
|
|
27
|
+
onEvent: (event: T) => void;
|
|
28
|
+
/**
|
|
29
|
+
* Called once error happens
|
|
30
|
+
*/
|
|
31
|
+
onError?: ((error: TError) => void) | undefined;
|
|
32
|
+
/**
|
|
33
|
+
* Called once AsyncIteratorObject is done
|
|
34
|
+
*
|
|
35
|
+
* @remarks
|
|
36
|
+
* **Note**: If iterator is canceled, `undefined` can be passed on success
|
|
37
|
+
*/
|
|
38
|
+
onSuccess?: ((value: TReturn | undefined) => void) | undefined;
|
|
39
|
+
/**
|
|
40
|
+
* Called once after onError or onSuccess
|
|
41
|
+
*
|
|
42
|
+
* @remarks
|
|
43
|
+
* **Note**: If iterator is canceled, `undefined` can be passed on success
|
|
44
|
+
*/
|
|
45
|
+
onFinish?: ((state: [error: TError, data: undefined, isSuccess: false] | [error: null, data: TReturn | undefined, isSuccess: true]) => void) | undefined;
|
|
46
|
+
}
|
|
47
|
+
/**
|
|
48
|
+
* Consumes an AsyncIteratorObject with lifecycle callbacks.
|
|
49
|
+
*
|
|
50
|
+
* @remarks
|
|
51
|
+
* **Warning**: If no `onError` or `onFinish` is provided, errors are thrown into the unhandled rejection channel.
|
|
52
|
+
*
|
|
53
|
+
* @returns An unsubscribe callback that stops consuming and cleans up the iterator.
|
|
54
|
+
* @see {@link https://orpc.dev/docs/client/async-iterator-object#using-consumeasynciterator | AsyncIteratorObject in Client - Using consumeAsyncIterator}
|
|
55
|
+
*/
|
|
56
|
+
export declare function consumeAsyncIterator<T, TReturn, TError = ThrowableError>(iterator: AsyncIterator<T, TReturn> | PromiseWithError<AsyncIterator<T, TReturn>, TError>, options: ConsumeAsyncIteratorOptions<T, TReturn, TError | ThrowableError>): () => Promise<void>;
|
package/dist/iterator.js
ADDED
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
import { once } from "./function.js";
|
|
2
|
+
import { AsyncIdQueue } from "./queue.js";
|
|
3
|
+
import { recordSpanError, runInSpanContext, startSpan } from "./tracing.js";
|
|
4
|
+
import { AsyncIteratorClass } from "@standard-server/shared";
|
|
5
|
+
// src/iterator.ts
|
|
6
|
+
function wrapAsyncIterator(iterator, { runWith, mapResult, mapError, onError, onFinish }) {
|
|
7
|
+
runWith ??= (run) => run();
|
|
8
|
+
let isDone;
|
|
9
|
+
return new AsyncIteratorClass(async () => {
|
|
10
|
+
try {
|
|
11
|
+
let result;
|
|
12
|
+
try {
|
|
13
|
+
result = await runWith(() => iterator.next());
|
|
14
|
+
isDone = result.done;
|
|
15
|
+
} catch (error) {
|
|
16
|
+
isDone = true;
|
|
17
|
+
throw error;
|
|
18
|
+
}
|
|
19
|
+
return mapResult ? await mapResult(result) : result;
|
|
20
|
+
} catch (error) {
|
|
21
|
+
await onError?.(error);
|
|
22
|
+
throw mapError ? await mapError(error) : error;
|
|
23
|
+
}
|
|
24
|
+
}, async (_state) => {
|
|
25
|
+
try {
|
|
26
|
+
if (!isDone) try {
|
|
27
|
+
await runWith(async () => iterator.return?.());
|
|
28
|
+
} catch (error) {
|
|
29
|
+
await onError?.(error);
|
|
30
|
+
throw error;
|
|
31
|
+
}
|
|
32
|
+
} finally {
|
|
33
|
+
await onFinish?.();
|
|
34
|
+
}
|
|
35
|
+
});
|
|
36
|
+
}
|
|
37
|
+
function traceAsyncIterator(options, iterator) {
|
|
38
|
+
const getSpan = once(() => startSpan(options));
|
|
39
|
+
return wrapAsyncIterator(iterator, {
|
|
40
|
+
runWith: (run) => runInSpanContext(getSpan(), run),
|
|
41
|
+
mapResult(result) {
|
|
42
|
+
getSpan()?.addEvent(result.done ? "completed" : "yielded");
|
|
43
|
+
return result;
|
|
44
|
+
},
|
|
45
|
+
onError(error) {
|
|
46
|
+
recordSpanError(getSpan(), error);
|
|
47
|
+
},
|
|
48
|
+
onFinish() {
|
|
49
|
+
getSpan()?.end();
|
|
50
|
+
}
|
|
51
|
+
});
|
|
52
|
+
}
|
|
53
|
+
function replicateAsyncIterator(source, count) {
|
|
54
|
+
const queue = new AsyncIdQueue();
|
|
55
|
+
const ids = Array.from({ length: count }, (_, i) => i.toString());
|
|
56
|
+
let isSourceFinished = false;
|
|
57
|
+
const start = once(async () => {
|
|
58
|
+
try {
|
|
59
|
+
while (true) {
|
|
60
|
+
const item = await source.next();
|
|
61
|
+
ids.forEach((id) => {
|
|
62
|
+
if (queue.isOpen(id)) queue.push(id, { next: item });
|
|
63
|
+
});
|
|
64
|
+
if (item.done) break;
|
|
65
|
+
}
|
|
66
|
+
} catch (error) {
|
|
67
|
+
ids.forEach((id) => {
|
|
68
|
+
if (queue.isOpen(id)) queue.push(id, { error });
|
|
69
|
+
});
|
|
70
|
+
} finally {
|
|
71
|
+
isSourceFinished = true;
|
|
72
|
+
}
|
|
73
|
+
});
|
|
74
|
+
return ids.map((id) => {
|
|
75
|
+
queue.open(id);
|
|
76
|
+
return new AsyncIteratorClass(async () => {
|
|
77
|
+
start();
|
|
78
|
+
const item = await queue.pull(id);
|
|
79
|
+
if (item.next) return item.next;
|
|
80
|
+
throw item.error;
|
|
81
|
+
}, async ({ kind, error }) => {
|
|
82
|
+
queue.close({
|
|
83
|
+
id,
|
|
84
|
+
reason: error
|
|
85
|
+
});
|
|
86
|
+
if (kind === "cancelled" && !queue.size && !isSourceFinished) {
|
|
87
|
+
isSourceFinished = true;
|
|
88
|
+
await source?.return?.();
|
|
89
|
+
}
|
|
90
|
+
});
|
|
91
|
+
});
|
|
92
|
+
}
|
|
93
|
+
/**
|
|
94
|
+
* Consumes an AsyncIteratorObject with lifecycle callbacks.
|
|
95
|
+
*
|
|
96
|
+
* @remarks
|
|
97
|
+
* **Warning**: If no `onError` or `onFinish` is provided, errors are thrown into the unhandled rejection channel.
|
|
98
|
+
*
|
|
99
|
+
* @returns An unsubscribe callback that stops consuming and cleans up the iterator.
|
|
100
|
+
* @see {@link https://orpc.dev/docs/client/async-iterator-object#using-consumeasynciterator | AsyncIteratorObject in Client - Using consumeAsyncIterator}
|
|
101
|
+
*/
|
|
102
|
+
function consumeAsyncIterator(iterator, options) {
|
|
103
|
+
(async () => {
|
|
104
|
+
let onFinishState;
|
|
105
|
+
try {
|
|
106
|
+
const resolvedIterator = await iterator;
|
|
107
|
+
while (true) {
|
|
108
|
+
const { done, value } = await resolvedIterator.next();
|
|
109
|
+
if (done) {
|
|
110
|
+
const realValue = value;
|
|
111
|
+
onFinishState = [
|
|
112
|
+
null,
|
|
113
|
+
realValue,
|
|
114
|
+
true
|
|
115
|
+
];
|
|
116
|
+
options.onSuccess?.(realValue);
|
|
117
|
+
break;
|
|
118
|
+
}
|
|
119
|
+
try {
|
|
120
|
+
options.onEvent(value);
|
|
121
|
+
} catch (error) {
|
|
122
|
+
await resolvedIterator.return?.();
|
|
123
|
+
throw error;
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
} catch (error) {
|
|
127
|
+
onFinishState = [
|
|
128
|
+
error,
|
|
129
|
+
void 0,
|
|
130
|
+
false
|
|
131
|
+
];
|
|
132
|
+
options.onError?.(error);
|
|
133
|
+
} finally {
|
|
134
|
+
options.onFinish?.(onFinishState);
|
|
135
|
+
}
|
|
136
|
+
})();
|
|
137
|
+
return async () => {
|
|
138
|
+
await (await iterator)?.return?.();
|
|
139
|
+
};
|
|
140
|
+
}
|
|
141
|
+
export { consumeAsyncIterator, replicateAsyncIterator, traceAsyncIterator, wrapAsyncIterator };
|
package/dist/object.d.ts
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import { AnyFunction } from "./function.js";
|
|
2
|
+
export type Segment = string | number;
|
|
3
|
+
export declare function findDeepMatches(check: (value: unknown) => boolean, payload: unknown, segments?: Segment[], maps?: Segment[][], values?: unknown[]): {
|
|
4
|
+
maps: Segment[][];
|
|
5
|
+
values: unknown[];
|
|
6
|
+
};
|
|
7
|
+
/**
|
|
8
|
+
* Get constructor of the value
|
|
9
|
+
*
|
|
10
|
+
*/
|
|
11
|
+
export declare function getConstructor(value: unknown): Function | null | undefined;
|
|
12
|
+
export declare function getConstructors(value: unknown): Generator<Function>;
|
|
13
|
+
/**
|
|
14
|
+
* Checks whether a value is a plain object, including objects created with
|
|
15
|
+
* `Object.create(null)`.
|
|
16
|
+
*/
|
|
17
|
+
export declare function isPlainObject(value: unknown): value is Record<PropertyKey, unknown>;
|
|
18
|
+
/**
|
|
19
|
+
* Checks whether a value is an array or a plain object, i.e. something whose keys can be walked.
|
|
20
|
+
*/
|
|
21
|
+
export declare function isPlainObjectOrArray(value: unknown): value is unknown[] | Record<PropertyKey, unknown>;
|
|
22
|
+
/**
|
|
23
|
+
* Returns `object[key]` only when it is an own property, so keys like
|
|
24
|
+
* `toString` do not resolve through the prototype chain.
|
|
25
|
+
*/
|
|
26
|
+
export declare function getOwn<T extends object>(object: T, key: PropertyKey): T[keyof T] | undefined;
|
|
27
|
+
export declare function get(object: unknown, path: readonly PropertyKey[]): unknown;
|
|
28
|
+
/**
|
|
29
|
+
* Sets a value at the given path, creating plain objects for intermediate keys as needed.
|
|
30
|
+
*/
|
|
31
|
+
export declare function set(root: object, path: [PropertyKey, ...PropertyKey[]] | [...PropertyKey[], PropertyKey], value: unknown): void;
|
|
32
|
+
/**
|
|
33
|
+
* Sets `object[key]`, defining `__proto__` as an own property instead of re-parenting the object.
|
|
34
|
+
*/
|
|
35
|
+
export declare function setOwn(object: object, key: PropertyKey, value: unknown): void;
|
|
36
|
+
/**
|
|
37
|
+
* Merges two values by copying the second over the first, repeating the merge one level deeper for
|
|
38
|
+
* nested plain objects. Anything that is not a pair of plain objects is replaced by the second one.
|
|
39
|
+
*/
|
|
40
|
+
export declare function mergeTwoLevels(first: unknown, second: unknown): unknown;
|
|
41
|
+
export declare function omit<T extends object, K extends keyof T>(obj: T, keys: readonly K[]): Omit<T, K>;
|
|
42
|
+
export declare function pick<T extends object, K extends keyof T>(obj: T, keys: readonly K[]): Pick<T, K>;
|
|
43
|
+
/**
|
|
44
|
+
* Deep clones arrays and plain objects, leaving every other value as is.
|
|
45
|
+
* Circular and shared references are preserved in the copy.
|
|
46
|
+
*/
|
|
47
|
+
export declare function clone<T>(value: T): T;
|
|
48
|
+
export declare function copyOnWrite(parent: object, key: PropertyKey, original: unknown): unknown;
|
|
49
|
+
export declare function isPropertyKey(value: unknown): value is PropertyKey;
|
|
50
|
+
export declare const NullProtoObj: {
|
|
51
|
+
new <T extends Record<PropertyKey, unknown>>(): T;
|
|
52
|
+
};
|
|
53
|
+
/**
|
|
54
|
+
* Returns an object containing all methods of the given object, with each
|
|
55
|
+
* method bound to the original object instance.
|
|
56
|
+
*
|
|
57
|
+
* Methods are collected from both the object itself and its prototype chain
|
|
58
|
+
* (excluding `Object.prototype` and the `constructor` property).
|
|
59
|
+
*/
|
|
60
|
+
export declare function bindMethods<T extends object>(obj: T, options?: {
|
|
61
|
+
unbound?: (keyof T)[];
|
|
62
|
+
}): Pick<T, { [K in keyof T]: T[K] extends AnyFunction ? K : never; }[keyof T]>;
|
package/dist/object.js
ADDED
|
@@ -0,0 +1,194 @@
|
|
|
1
|
+
import { getOrBind, isNonPrimitive } from "@standard-server/shared";
|
|
2
|
+
// src/object.ts
|
|
3
|
+
function findDeepMatches(check, payload, segments = [], maps = [], values = []) {
|
|
4
|
+
if (check(payload)) {
|
|
5
|
+
maps.push(segments);
|
|
6
|
+
values.push(payload);
|
|
7
|
+
} else if (Array.isArray(payload)) payload.forEach((v, i) => {
|
|
8
|
+
findDeepMatches(check, v, [...segments, i], maps, values);
|
|
9
|
+
});
|
|
10
|
+
else if (isPlainObject(payload)) for (const key of Object.keys(payload)) findDeepMatches(check, payload[key], [...segments, key], maps, values);
|
|
11
|
+
return {
|
|
12
|
+
maps,
|
|
13
|
+
values
|
|
14
|
+
};
|
|
15
|
+
}
|
|
16
|
+
/**
|
|
17
|
+
* Get constructor of the value
|
|
18
|
+
*
|
|
19
|
+
*/
|
|
20
|
+
function getConstructor(value) {
|
|
21
|
+
if (!isNonPrimitive(value)) return null;
|
|
22
|
+
return Object.getPrototypeOf(value)?.constructor;
|
|
23
|
+
}
|
|
24
|
+
function* getConstructors(value) {
|
|
25
|
+
if (!isNonPrimitive(value)) return;
|
|
26
|
+
let proto = Object.getPrototypeOf(value);
|
|
27
|
+
while (proto !== null) {
|
|
28
|
+
if (proto.constructor) yield proto.constructor;
|
|
29
|
+
proto = Object.getPrototypeOf(proto);
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
* Checks whether a value is a plain object, including objects created with
|
|
34
|
+
* `Object.create(null)`.
|
|
35
|
+
*/
|
|
36
|
+
function isPlainObject(value) {
|
|
37
|
+
if (!value || typeof value !== "object") return false;
|
|
38
|
+
const proto = Object.getPrototypeOf(value);
|
|
39
|
+
return proto === Object.prototype || !proto || !proto.constructor;
|
|
40
|
+
}
|
|
41
|
+
/**
|
|
42
|
+
* Checks whether a value is an array or a plain object, i.e. something whose keys can be walked.
|
|
43
|
+
*/
|
|
44
|
+
function isPlainObjectOrArray(value) {
|
|
45
|
+
return Array.isArray(value) || isPlainObject(value);
|
|
46
|
+
}
|
|
47
|
+
/**
|
|
48
|
+
* Returns `object[key]` only when it is an own property, so keys like
|
|
49
|
+
* `toString` do not resolve through the prototype chain.
|
|
50
|
+
*/
|
|
51
|
+
function getOwn(object, key) {
|
|
52
|
+
return Object.hasOwn(object, key) ? object[key] : void 0;
|
|
53
|
+
}
|
|
54
|
+
function get(object, path) {
|
|
55
|
+
let current = object;
|
|
56
|
+
for (const key of path) {
|
|
57
|
+
if (!isNonPrimitive(current)) return;
|
|
58
|
+
current = getOwn(current, key);
|
|
59
|
+
}
|
|
60
|
+
return current;
|
|
61
|
+
}
|
|
62
|
+
/**
|
|
63
|
+
* Sets a value at the given path, creating plain objects for intermediate keys as needed.
|
|
64
|
+
*/
|
|
65
|
+
function set(root, path, value) {
|
|
66
|
+
let current = root;
|
|
67
|
+
for (let i = 0; i < path.length - 1; i++) {
|
|
68
|
+
const key = path[i];
|
|
69
|
+
const next = getOwn(current, key);
|
|
70
|
+
if (!isNonPrimitive(next)) {
|
|
71
|
+
const child = {};
|
|
72
|
+
setOwn(current, key, child);
|
|
73
|
+
current = child;
|
|
74
|
+
} else current = next;
|
|
75
|
+
}
|
|
76
|
+
setOwn(current, path.at(-1), value);
|
|
77
|
+
}
|
|
78
|
+
/**
|
|
79
|
+
* Sets `object[key]`, defining `__proto__` as an own property instead of re-parenting the object.
|
|
80
|
+
*/
|
|
81
|
+
function setOwn(object, key, value) {
|
|
82
|
+
if (key === "__proto__") Object.defineProperty(object, key, {
|
|
83
|
+
value,
|
|
84
|
+
writable: true,
|
|
85
|
+
enumerable: true,
|
|
86
|
+
configurable: true
|
|
87
|
+
});
|
|
88
|
+
else object[key] = value;
|
|
89
|
+
}
|
|
90
|
+
/**
|
|
91
|
+
* Merges two values by copying the second over the first, repeating the merge one level deeper for
|
|
92
|
+
* nested plain objects. Anything that is not a pair of plain objects is replaced by the second one.
|
|
93
|
+
*/
|
|
94
|
+
function mergeTwoLevels(first, second) {
|
|
95
|
+
if (!isPlainObject(first) || !isPlainObject(second)) return second;
|
|
96
|
+
const result = {
|
|
97
|
+
...first,
|
|
98
|
+
...second
|
|
99
|
+
};
|
|
100
|
+
for (const key of Object.keys(second)) {
|
|
101
|
+
if (!Object.hasOwn(first, key)) continue;
|
|
102
|
+
const firstValue = first[key];
|
|
103
|
+
const secondValue = second[key];
|
|
104
|
+
if (isPlainObject(firstValue) && isPlainObject(secondValue)) result[key] = {
|
|
105
|
+
...firstValue,
|
|
106
|
+
...secondValue
|
|
107
|
+
};
|
|
108
|
+
}
|
|
109
|
+
return result;
|
|
110
|
+
}
|
|
111
|
+
function omit(obj, keys) {
|
|
112
|
+
const result = { ...obj };
|
|
113
|
+
for (const key of keys) delete result[key];
|
|
114
|
+
return result;
|
|
115
|
+
}
|
|
116
|
+
function pick(obj, keys) {
|
|
117
|
+
const result = {};
|
|
118
|
+
for (const key of keys) if (Object.hasOwn(obj, key)) result[key] = obj[key];
|
|
119
|
+
return result;
|
|
120
|
+
}
|
|
121
|
+
/**
|
|
122
|
+
* Deep clones arrays and plain objects, leaving every other value as is.
|
|
123
|
+
* Circular and shared references are preserved in the copy.
|
|
124
|
+
*/
|
|
125
|
+
function clone(value) {
|
|
126
|
+
return cloneWithVisited(value, /* @__PURE__ */ new WeakMap());
|
|
127
|
+
}
|
|
128
|
+
function cloneWithVisited(value, visited) {
|
|
129
|
+
if (Array.isArray(value)) {
|
|
130
|
+
const existing = visited.get(value);
|
|
131
|
+
if (existing) return existing;
|
|
132
|
+
const result = [];
|
|
133
|
+
visited.set(value, result);
|
|
134
|
+
for (const item of value) result.push(cloneWithVisited(item, visited));
|
|
135
|
+
return result;
|
|
136
|
+
}
|
|
137
|
+
if (isPlainObject(value)) {
|
|
138
|
+
const existing = visited.get(value);
|
|
139
|
+
if (existing) return existing;
|
|
140
|
+
const result = {};
|
|
141
|
+
visited.set(value, result);
|
|
142
|
+
for (const key of Object.keys(value)) setOwn(result, key, cloneWithVisited(value[key], visited));
|
|
143
|
+
for (const sym of Object.getOwnPropertySymbols(value)) setOwn(result, sym, cloneWithVisited(value[sym], visited));
|
|
144
|
+
return result;
|
|
145
|
+
}
|
|
146
|
+
return value;
|
|
147
|
+
}
|
|
148
|
+
function copyOnWrite(parent, key, original) {
|
|
149
|
+
const value = parent[key];
|
|
150
|
+
if (value !== original) return value;
|
|
151
|
+
let copy;
|
|
152
|
+
if (Array.isArray(value)) copy = value.slice();
|
|
153
|
+
else if (isPlainObject(value)) copy = { ...value };
|
|
154
|
+
else return value;
|
|
155
|
+
setOwn(parent, key, copy);
|
|
156
|
+
return copy;
|
|
157
|
+
}
|
|
158
|
+
function isPropertyKey(value) {
|
|
159
|
+
const type = typeof value;
|
|
160
|
+
return type === "string" || type === "number" || type === "symbol";
|
|
161
|
+
}
|
|
162
|
+
const NullProtoObj = /* @__PURE__ */ (() => {
|
|
163
|
+
const e = function() {};
|
|
164
|
+
e.prototype = Object.create(null);
|
|
165
|
+
Object.freeze(e.prototype);
|
|
166
|
+
return e;
|
|
167
|
+
})();
|
|
168
|
+
/**
|
|
169
|
+
* Returns an object containing all methods of the given object, with each
|
|
170
|
+
* method bound to the original object instance.
|
|
171
|
+
*
|
|
172
|
+
* Methods are collected from both the object itself and its prototype chain
|
|
173
|
+
* (excluding `Object.prototype` and the `constructor` property).
|
|
174
|
+
*/
|
|
175
|
+
function bindMethods(obj, options = {}) {
|
|
176
|
+
const unbound = new Set(options.unbound);
|
|
177
|
+
const methods = new NullProtoObj();
|
|
178
|
+
let current = obj;
|
|
179
|
+
while (current && current !== Object.prototype) {
|
|
180
|
+
for (const key of Object.getOwnPropertyNames(current)) {
|
|
181
|
+
if (key === "constructor" || key in methods) continue;
|
|
182
|
+
const val = getOrBind(obj, key, { bind: !unbound.has(key) });
|
|
183
|
+
if (typeof val === "function") methods[key] = val;
|
|
184
|
+
}
|
|
185
|
+
for (const sym of Object.getOwnPropertySymbols(current)) {
|
|
186
|
+
if (sym in methods) continue;
|
|
187
|
+
const val = getOrBind(obj, sym, { bind: !unbound.has(sym) });
|
|
188
|
+
if (typeof val === "function") methods[sym] = val;
|
|
189
|
+
}
|
|
190
|
+
current = Object.getPrototypeOf(current);
|
|
191
|
+
}
|
|
192
|
+
return methods;
|
|
193
|
+
}
|
|
194
|
+
export { NullProtoObj, bindMethods, clone, copyOnWrite, findDeepMatches, get, getConstructor, getConstructors, getOwn, isPlainObject, isPlainObjectOrArray, isPropertyKey, mergeTwoLevels, omit, pick, set, setOwn };
|
package/dist/plugin.d.ts
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
export interface OrderablePlugin {
|
|
2
|
+
/** Unique name of the plugin, used for ordering and identification. */
|
|
3
|
+
name: string;
|
|
4
|
+
/** Plugins this plugin should execute before. */
|
|
5
|
+
before?: string[] | undefined;
|
|
6
|
+
/** Plugins this plugin should execute after. */
|
|
7
|
+
after?: string[] | undefined;
|
|
8
|
+
}
|
|
9
|
+
/**
|
|
10
|
+
* Sorts plugins based on their `before` and `after` dependencies.
|
|
11
|
+
*/
|
|
12
|
+
export declare function sortPlugins<T extends OrderablePlugin>(plugins: T[]): T[];
|
package/dist/plugin.js
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
// src/plugin.ts
|
|
2
|
+
/**
|
|
3
|
+
* Sorts plugins based on their `before` and `after` dependencies.
|
|
4
|
+
*/
|
|
5
|
+
function sortPlugins(plugins) {
|
|
6
|
+
const pluginCount = plugins.length;
|
|
7
|
+
const pluginIdToIndices = /* @__PURE__ */ new Map();
|
|
8
|
+
for (let i = 0; i < pluginCount; i++) {
|
|
9
|
+
const plugin = plugins[i];
|
|
10
|
+
const indices = pluginIdToIndices.get(plugin.name);
|
|
11
|
+
if (indices === void 0) pluginIdToIndices.set(plugin.name, [i]);
|
|
12
|
+
else indices.push(i);
|
|
13
|
+
}
|
|
14
|
+
const dependencies = Array.from({ length: pluginCount }, () => []);
|
|
15
|
+
for (let i = 0; i < pluginCount; i++) {
|
|
16
|
+
const plugin = plugins[i];
|
|
17
|
+
if (plugin.before !== void 0) for (const beforeId of plugin.before) {
|
|
18
|
+
const beforeIndices = pluginIdToIndices.get(beforeId);
|
|
19
|
+
if (beforeIndices !== void 0) for (const beforeIndex of beforeIndices) dependencies[beforeIndex].push(i);
|
|
20
|
+
}
|
|
21
|
+
if (plugin.after !== void 0) for (const afterId of plugin.after) {
|
|
22
|
+
const afterIndices = pluginIdToIndices.get(afterId);
|
|
23
|
+
if (afterIndices !== void 0) for (const afterIndex of afterIndices) dependencies[i].push(afterIndex);
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
const sorted = [];
|
|
27
|
+
const placed = /* @__PURE__ */ new Set();
|
|
28
|
+
while (sorted.length < pluginCount) {
|
|
29
|
+
const next = plugins.findIndex((_, i) => !placed.has(i) && dependencies[i].every((dependency) => placed.has(dependency)));
|
|
30
|
+
if (next === -1) throw new Error(`Circular dependency detected involving plugin "${findCyclicPlugin(plugins, dependencies, placed).name}"`);
|
|
31
|
+
placed.add(next);
|
|
32
|
+
sorted.push(plugins[next]);
|
|
33
|
+
}
|
|
34
|
+
return sorted;
|
|
35
|
+
}
|
|
36
|
+
function findCyclicPlugin(plugins, dependencies, placed) {
|
|
37
|
+
const seen = /* @__PURE__ */ new Set();
|
|
38
|
+
let current = plugins.findIndex((_, i) => !placed.has(i));
|
|
39
|
+
while (!seen.has(current)) {
|
|
40
|
+
seen.add(current);
|
|
41
|
+
current = dependencies[current].find((dependency) => !placed.has(dependency));
|
|
42
|
+
}
|
|
43
|
+
return plugins[current];
|
|
44
|
+
}
|
|
45
|
+
export { sortPlugins };
|