@ahoo-wang/wow-client 10.0.0-alpha.5 → 10.0.0-alpha.7
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 +76 -23
- package/README.zh-CN.md +66 -19
- package/dist/commands.cjs +1 -1
- package/dist/commands.cjs.map +1 -1
- package/dist/commands.d.cts +131 -61
- package/dist/commands.d.ts +131 -61
- package/dist/commands.es.js +117 -59
- package/dist/commands.es.js.map +1 -1
- package/dist/developmentCaller.cjs +2 -0
- package/dist/developmentCaller.cjs.map +1 -0
- package/dist/developmentCaller.d.cts +61 -0
- package/dist/developmentCaller.d.ts +61 -0
- package/dist/developmentCaller.es.js +26 -0
- package/dist/developmentCaller.es.js.map +1 -0
- package/dist/dsl/aggregation/admit.cjs +1 -1
- package/dist/dsl/aggregation/admit.cjs.map +1 -1
- package/dist/dsl/aggregation/admit.es.js +93 -93
- package/dist/dsl/aggregation/admit.es.js.map +1 -1
- package/dist/dsl/aggregation/builders.cjs +1 -1
- package/dist/dsl/aggregation/builders.cjs.map +1 -1
- package/dist/dsl/aggregation/builders.d.cts +20 -20
- package/dist/dsl/aggregation/builders.d.ts +20 -20
- package/dist/dsl/aggregation/builders.es.js +88 -88
- package/dist/dsl/aggregation/builders.es.js.map +1 -1
- package/dist/dsl/aggregation/derived.cjs.map +1 -1
- package/dist/dsl/aggregation/derived.d.cts +8 -8
- package/dist/dsl/aggregation/derived.d.ts +8 -8
- package/dist/dsl/aggregation/derived.es.js +1 -2
- package/dist/dsl/aggregation/derived.es.js.map +1 -1
- package/dist/dsl/aggregation/expressionTrees.cjs.map +1 -1
- package/dist/dsl/aggregation/expressionTrees.es.js +1 -2
- package/dist/dsl/aggregation/having.cjs +1 -1
- package/dist/dsl/aggregation/having.cjs.map +1 -1
- package/dist/dsl/aggregation/having.d.cts +12 -12
- package/dist/dsl/aggregation/having.d.ts +12 -12
- package/dist/dsl/aggregation/having.es.js +33 -33
- package/dist/dsl/aggregation/having.es.js.map +1 -1
- package/dist/dsl/aggregation/sort.cjs.map +1 -1
- package/dist/dsl/aggregation/sort.es.js +1 -2
- package/dist/dsl/aggregation/types.cjs +1 -1
- package/dist/dsl/aggregation/types.cjs.map +1 -1
- package/dist/dsl/aggregation/types.d.cts +69 -69
- package/dist/dsl/aggregation/types.d.ts +69 -69
- package/dist/dsl/aggregation/types.es.js +15 -16
- package/dist/dsl/aggregation/types.es.js.map +1 -1
- package/dist/dsl/constantName.cjs +2 -0
- package/dist/dsl/constantName.cjs.map +1 -0
- package/dist/dsl/constantName.d.cts +9 -0
- package/dist/dsl/constantName.d.ts +9 -0
- package/dist/dsl/constantName.es.js +7 -0
- package/dist/dsl/constantName.es.js.map +1 -0
- package/dist/dsl/cursorQuery.cjs.map +1 -1
- package/dist/dsl/cursorQuery.es.js +1 -2
- package/dist/dsl/deletionState.cjs +1 -1
- package/dist/dsl/deletionState.cjs.map +1 -1
- package/dist/dsl/deletionState.d.cts +3 -3
- package/dist/dsl/deletionState.d.ts +3 -3
- package/dist/dsl/deletionState.es.js +2 -3
- package/dist/dsl/deletionState.es.js.map +1 -1
- package/dist/dsl/descriptor.cjs +1 -1
- package/dist/dsl/descriptor.cjs.map +1 -1
- package/dist/dsl/descriptor.d.cts +92 -42
- package/dist/dsl/descriptor.d.ts +92 -42
- package/dist/dsl/descriptor.es.js +36 -29
- package/dist/dsl/descriptor.es.js.map +1 -1
- package/dist/dsl/field.cjs.map +1 -1
- package/dist/dsl/field.es.js +1 -2
- package/dist/dsl/filter/builders.cjs +1 -1
- package/dist/dsl/filter/builders.cjs.map +1 -1
- package/dist/dsl/filter/builders.d.cts +53 -53
- package/dist/dsl/filter/builders.d.ts +53 -53
- package/dist/dsl/filter/builders.es.js +111 -111
- package/dist/dsl/filter/builders.es.js.map +1 -1
- package/dist/dsl/filter/datePattern.cjs.map +1 -1
- package/dist/dsl/filter/datePattern.es.js +1 -2
- package/dist/dsl/filter/operator.cjs +1 -1
- package/dist/dsl/filter/operator.cjs.map +1 -1
- package/dist/dsl/filter/operator.d.cts +57 -57
- package/dist/dsl/filter/operator.d.ts +57 -57
- package/dist/dsl/filter/operator.es.js +4 -5
- package/dist/dsl/filter/operator.es.js.map +1 -1
- package/dist/dsl/filter/scope.cjs +1 -1
- package/dist/dsl/filter/scope.cjs.map +1 -1
- package/dist/dsl/filter/scope.es.js +12 -12
- package/dist/dsl/filter/scope.es.js.map +1 -1
- package/dist/dsl/filter/validate.cjs +1 -1
- package/dist/dsl/filter/validate.cjs.map +1 -1
- package/dist/dsl/filter/validate.es.js +23 -23
- package/dist/dsl/filter/validate.es.js.map +1 -1
- package/dist/dsl/pagination.cjs.map +1 -1
- package/dist/dsl/pagination.es.js +1 -2
- package/dist/dsl/projection.cjs.map +1 -1
- package/dist/dsl/projection.d.cts +1 -1
- package/dist/dsl/projection.d.ts +1 -1
- package/dist/dsl/projection.es.js +1 -2
- package/dist/dsl/projection.es.js.map +1 -1
- package/dist/dsl/queryErrorCodes.cjs +1 -1
- package/dist/dsl/queryErrorCodes.cjs.map +1 -1
- package/dist/dsl/queryErrorCodes.d.cts +59 -48
- package/dist/dsl/queryErrorCodes.d.ts +59 -48
- package/dist/dsl/queryErrorCodes.es.js +51 -50
- package/dist/dsl/queryErrorCodes.es.js.map +1 -1
- package/dist/dsl/queryable.cjs +1 -1
- package/dist/dsl/queryable.cjs.map +1 -1
- package/dist/dsl/queryable.d.cts +25 -21
- package/dist/dsl/queryable.d.ts +25 -21
- package/dist/dsl/queryable.es.js +5 -5
- package/dist/dsl/queryable.es.js.map +1 -1
- package/dist/dsl/sort.cjs +1 -1
- package/dist/dsl/sort.cjs.map +1 -1
- package/dist/dsl/sort.d.cts +2 -2
- package/dist/dsl/sort.d.ts +2 -2
- package/dist/dsl/sort.es.js +4 -5
- package/dist/dsl/sort.es.js.map +1 -1
- package/dist/dsl.cjs +1 -1
- package/dist/dsl.es.js +3 -3
- package/dist/exactJson.cjs.map +1 -1
- package/dist/exactJson.d.cts +4 -4
- package/dist/exactJson.d.ts +4 -4
- package/dist/exactJson.es.js +1 -2
- package/dist/exactJson.es.js.map +1 -1
- package/dist/frameworkErrors.cjs +2 -0
- package/dist/frameworkErrors.cjs.map +1 -0
- package/dist/frameworkErrors.d.cts +121 -0
- package/dist/frameworkErrors.d.ts +121 -0
- package/dist/frameworkErrors.es.js +95 -0
- package/dist/frameworkErrors.es.js.map +1 -0
- package/dist/http.cjs +1 -1
- package/dist/http.cjs.map +1 -1
- package/dist/http.d.cts +4 -7
- package/dist/http.d.ts +4 -7
- package/dist/http.es.js +12 -20
- package/dist/http.es.js.map +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.d.cts +9 -7
- package/dist/index.d.ts +9 -7
- package/dist/index.es.js +11 -9
- package/dist/manifest.cjs +1 -1
- package/dist/manifest.cjs.map +1 -1
- package/dist/manifest.d.cts +33 -95
- package/dist/manifest.d.ts +33 -95
- package/dist/manifest.es.js +12 -7
- package/dist/manifest.es.js.map +1 -1
- package/dist/manifestTypes.d.cts +193 -0
- package/dist/manifestTypes.d.ts +193 -0
- package/dist/problem.cjs +1 -1
- package/dist/problem.cjs.map +1 -1
- package/dist/problem.d.cts +76 -111
- package/dist/problem.d.ts +76 -111
- package/dist/problem.es.js +45 -78
- package/dist/problem.es.js.map +1 -1
- package/dist/queries.cjs +1 -1
- package/dist/queries.cjs.map +1 -1
- package/dist/queries.d.cts +28 -51
- package/dist/queries.d.ts +28 -51
- package/dist/queries.es.js +49 -40
- package/dist/queries.es.js.map +1 -1
- package/dist/routes.cjs +2 -0
- package/dist/routes.cjs.map +1 -0
- package/dist/routes.d.cts +49 -0
- package/dist/routes.d.ts +49 -0
- package/dist/routes.es.js +33 -0
- package/dist/routes.es.js.map +1 -0
- package/dist/state.cjs +1 -1
- package/dist/state.cjs.map +1 -1
- package/dist/state.d.cts +56 -11
- package/dist/state.d.ts +56 -11
- package/dist/state.es.js +56 -21
- package/dist/state.es.js.map +1 -1
- package/dist/streams.cjs +1 -1
- package/dist/streams.cjs.map +1 -1
- package/dist/streams.d.cts +17 -13
- package/dist/streams.d.ts +17 -13
- package/dist/streams.es.js +50 -50
- package/dist/streams.es.js.map +1 -1
- package/dist/testing/wire.cjs +2 -0
- package/dist/testing/wire.cjs.map +1 -0
- package/dist/testing/wire.d.cts +29 -0
- package/dist/testing/wire.d.ts +29 -0
- package/dist/testing/wire.es.js +88 -0
- package/dist/testing/wire.es.js.map +1 -0
- package/dist/testing.cjs +1 -0
- package/dist/testing.d.cts +12 -0
- package/dist/testing.d.ts +12 -0
- package/dist/testing.es.js +3 -0
- package/dist/wait.cjs +1 -1
- package/dist/wait.cjs.map +1 -1
- package/dist/wait.d.cts +67 -18
- package/dist/wait.d.ts +67 -18
- package/dist/wait.es.js +59 -12
- package/dist/wait.es.js.map +1 -1
- package/dist/wire.cjs +1 -1
- package/dist/wire.cjs.map +1 -1
- package/dist/wire.d.cts +100 -50
- package/dist/wire.d.ts +100 -50
- package/dist/wire.es.js +17 -6
- package/dist/wire.es.js.map +1 -1
- package/package.json +26 -7
package/dist/problem.d.ts
CHANGED
|
@@ -1,93 +1,12 @@
|
|
|
1
|
-
import {
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
* each answered with the status of the Manifest's `errors` table. A domain
|
|
5
|
-
* rejection has a code of its own, answered with 422 unless the service
|
|
6
|
-
* configures another status.
|
|
7
|
-
*/
|
|
8
|
-
export declare const FrameworkErrorCodes: {
|
|
9
|
-
/** 401: the request carries no valid credentials. */
|
|
10
|
-
readonly AUTH_UNAUTHENTICATED: "wow.auth.unauthenticated";
|
|
11
|
-
/** 403: the caller may not send this command. */
|
|
12
|
-
readonly AUTH_FORBIDDEN: "wow.auth.forbidden";
|
|
13
|
-
/** 403: the aggregate is outside the caller's scope. */
|
|
14
|
-
readonly AGGREGATE_FORBIDDEN: "wow.aggregate.forbidden";
|
|
15
|
-
/** 400: the command body cannot be read as the command type. */
|
|
16
|
-
readonly COMMAND_MALFORMED: "wow.command.malformed";
|
|
17
|
-
/** 400: the command failed validation; the problem lists the violations. */
|
|
18
|
-
readonly COMMAND_INVALID: "wow.command.invalid";
|
|
19
|
-
/** 400: the wait is not a chain the runtime can follow. */
|
|
20
|
-
readonly WAIT_INVALID: "wow.wait.invalid";
|
|
21
|
-
/** 400: the aggregate does not handle this command. */
|
|
22
|
-
readonly COMMAND_UNHANDLED: "wow.command.unhandled";
|
|
23
|
-
/** 404: the aggregate does not exist. */
|
|
24
|
-
readonly AGGREGATE_NOT_FOUND: "wow.aggregate.not-found";
|
|
25
|
-
/** 409: the aggregate already exists. */
|
|
26
|
-
readonly AGGREGATE_EXISTS: "wow.aggregate.exists";
|
|
27
|
-
/** 409, or 412 with `If-Match`: the aggregate is not at the expected version. */
|
|
28
|
-
readonly AGGREGATE_VERSION_MISMATCH: "wow.aggregate.version-mismatch";
|
|
29
|
-
/** 409: the request id was used by another command. */
|
|
30
|
-
readonly COMMAND_REQUEST_ID_REUSED: "wow.command.request-id-reused";
|
|
31
|
-
/** 409: concurrent writers kept winning; retrying with the same request id is safe. */
|
|
32
|
-
readonly COMMAND_CONTENDED: "wow.command.contended";
|
|
33
|
-
/** 410: the aggregate is deleted; only RestoreAggregate applies. */
|
|
34
|
-
readonly AGGREGATE_DELETED: "wow.aggregate.deleted";
|
|
35
|
-
/** 429: the command was not taken, its aggregate or the node being busy; retry later. */
|
|
36
|
-
readonly COMMAND_BUSY: "wow.command.busy";
|
|
37
|
-
/** 503: whether the command committed is unknown; retrying with the same request id is safe. */
|
|
38
|
-
readonly COMMAND_UNKNOWN: "wow.command.unknown";
|
|
39
|
-
/** 500: the command's handling failed with an unexpected error; it committed nothing, and a retry fails alike. */
|
|
40
|
-
readonly COMMAND_FAILED: "wow.command.failed";
|
|
41
|
-
/** 503: the node is shutting down; retry on another node. */
|
|
42
|
-
readonly NODE_CLOSING: "wow.node.closing";
|
|
43
|
-
/** 503: the node is on standby until a migration's cut-over; it serves reads only. */
|
|
44
|
-
readonly NODE_STANDBY: "wow.node.standby";
|
|
45
|
-
/** 503, with `Retry-After`: a store could not be reached in time; retry later. */
|
|
46
|
-
readonly STORAGE_UNAVAILABLE: "wow.storage.unavailable";
|
|
47
|
-
/** 503: a scheduled command arrived too long before its due time; it is sent again later. */
|
|
48
|
-
readonly SCHEDULE_NOT_DUE: "wow.schedule.not-due";
|
|
49
|
-
/** 400: the job command does not fit its job or instance (decision D198). */
|
|
50
|
-
readonly SCHEDULE_JOB_INVALID: "wow.schedule.job-invalid";
|
|
51
|
-
/** 500: a subscription on the wait chain parked the aggregate. */
|
|
52
|
-
readonly SUBSCRIPTION_PARKED: "wow.subscription.parked";
|
|
53
|
-
/** 504: the wait ran out of time; the command may have committed. */
|
|
54
|
-
readonly WAIT_TIMEOUT: "wow.wait.timeout";
|
|
55
|
-
/** 400: the query body cannot be read as a query. */
|
|
56
|
-
readonly QUERY_MALFORMED: "wow.query.malformed";
|
|
57
|
-
/** 400: the query failed admission; each violation has its code. */
|
|
58
|
-
readonly QUERY_INVALID: "wow.query.invalid";
|
|
59
|
-
/** 500: the query backend failed to run the query. */
|
|
60
|
-
readonly QUERY_FAILED: "wow.query.failed";
|
|
61
|
-
/** 504: the query ran longer than its budget allows; not retried (decision D254 ③). */
|
|
62
|
-
readonly QUERY_TIMEOUT: "wow.query.timeout";
|
|
63
|
-
/** 429, with `Retry-After`: the query's store runs as many queries as it allows; retry later. */
|
|
64
|
-
readonly QUERY_BUSY: "wow.query.busy";
|
|
65
|
-
/**
|
|
66
|
-
* 404: a `single` query matched no record, whatever its model (review R4-Q,
|
|
67
|
-
* Q-4); a state read by id that finds none is `wow.aggregate.not-found`.
|
|
68
|
-
*/
|
|
69
|
-
readonly QUERY_NOT_FOUND: "wow.query.not-found";
|
|
70
|
-
/** 404: no dataset of that name is served to the caller. */
|
|
71
|
-
readonly QUERY_DATASET_NOT_FOUND: "wow.query.dataset-not-found";
|
|
72
|
-
/**
|
|
73
|
-
* 409, with `Retry-After`: a state read asked for a version (`minVersion`) the
|
|
74
|
-
* aggregate has not reached within the wait; the problem's `version` is its
|
|
75
|
-
* current one (review R4-Q, Q-13).
|
|
76
|
-
*/
|
|
77
|
-
readonly QUERY_MIN_VERSION_NOT_REACHED: "wow.query.min-version-not-reached";
|
|
78
|
-
/** 409: the dataset is served but cannot be queried now (it needs revision, decision D259). */
|
|
79
|
-
readonly QUERY_DATASET_UNAVAILABLE: "wow.query.dataset-unavailable";
|
|
80
|
-
/** 403: the calling service may not call this command (a synchronous call on the internal port, decision D226). */
|
|
81
|
-
readonly CALL_COMMAND_FORBIDDEN: "wow.call.command-forbidden";
|
|
82
|
-
};
|
|
83
|
-
/** A {@link FrameworkErrorCodes} value. */
|
|
84
|
-
export type FrameworkErrorCode = (typeof FrameworkErrorCodes)[keyof typeof FrameworkErrorCodes];
|
|
1
|
+
import { Retry } from './frameworkErrors.js';
|
|
2
|
+
import { RefusedResult, Violation } from './wire.js';
|
|
3
|
+
export { DEFAULT_RETRY, FRAMEWORK_RETRIES, type FrameworkRetry, type FrameworkErrorCode, FrameworkErrorCodes, type Retry, } from './frameworkErrors.js';
|
|
85
4
|
/** The prefix of every framework code, and of no domain code. */
|
|
86
5
|
export declare const FRAMEWORK_ERROR_PREFIX = "wow.";
|
|
87
6
|
/** The prefix of a problem's `type` that carries a Wow code. */
|
|
88
7
|
export declare const PROBLEM_TYPE_PREFIX = "urn:wow:error:";
|
|
89
8
|
/**
|
|
90
|
-
* An RFC 9457 problem as a Wow service writes it
|
|
9
|
+
* An RFC 9457 problem as a Wow service writes it:
|
|
91
10
|
* `type` is `urn:wow:error:<code>`, or `about:blank` for an error that is
|
|
92
11
|
* only HTTP's (a missing route, 406, 415).
|
|
93
12
|
*/
|
|
@@ -98,9 +17,17 @@ export interface Problem {
|
|
|
98
17
|
readonly detail?: string;
|
|
99
18
|
/** The Wow code; absent for an error that is only HTTP's. */
|
|
100
19
|
readonly code?: string;
|
|
20
|
+
/**
|
|
21
|
+
* What a retry may do, as the error catalog declares it for the code: every
|
|
22
|
+
* problem a Wow service writes carries it.
|
|
23
|
+
*/
|
|
24
|
+
readonly retry?: Retry;
|
|
101
25
|
readonly violations?: readonly Violation[];
|
|
102
|
-
/**
|
|
103
|
-
|
|
26
|
+
/**
|
|
27
|
+
* The whole result of a command that has a ref; its id is null when
|
|
28
|
+
* admission refused a creation before choosing one.
|
|
29
|
+
*/
|
|
30
|
+
readonly result?: RefusedResult;
|
|
104
31
|
/**
|
|
105
32
|
* The problem's extension members (RFC 9457): every member the server
|
|
106
33
|
* wrote besides the ones above and `instance`, such as a rejection's
|
|
@@ -109,26 +36,13 @@ export interface Problem {
|
|
|
109
36
|
readonly extensions?: Readonly<Record<string, unknown>>;
|
|
110
37
|
}
|
|
111
38
|
/**
|
|
112
|
-
* What a
|
|
113
|
-
*
|
|
114
|
-
*
|
|
115
|
-
*/
|
|
116
|
-
export interface RetryHint {
|
|
117
|
-
readonly retryable: boolean;
|
|
118
|
-
/** Retry with the same `Wow-Request-Id`: a commit is then answered as a duplicate. */
|
|
119
|
-
readonly sameRequestId: boolean;
|
|
120
|
-
/** The server's `Retry-After`, in milliseconds. */
|
|
121
|
-
readonly afterMs?: number;
|
|
122
|
-
}
|
|
123
|
-
/**
|
|
124
|
-
* The retry hint of a problem with `code` and `status`: a code of the
|
|
125
|
-
* retryable table, or a 503 without a code (a proxy's), may be retried.
|
|
39
|
+
* What a retry of `problem` may do: its `retry` member, which every problem a
|
|
40
|
+
* Wow service writes carries; else the error catalog's for its code; else, for
|
|
41
|
+
* a body that is no Wow problem (a proxy's 503 or 429), `same-request`.
|
|
126
42
|
*
|
|
127
|
-
* @param
|
|
128
|
-
* @param status - The HTTP status
|
|
129
|
-
* @param afterMs - The `Retry-After` the response carried, in milliseconds
|
|
43
|
+
* @param problem - The problem a request was answered with
|
|
130
44
|
*/
|
|
131
|
-
export declare function
|
|
45
|
+
export declare function retryOf(problem: Problem): Retry;
|
|
132
46
|
/**
|
|
133
47
|
* A request a Wow service answered with a problem: a non-2xx response, a
|
|
134
48
|
* command result that did not succeed, or the `error` event that ends a
|
|
@@ -143,16 +57,22 @@ export declare class WowProblemError extends Error {
|
|
|
143
57
|
/** The Wow code; absent for an error that is only HTTP's. */
|
|
144
58
|
readonly code?: string;
|
|
145
59
|
readonly violations: readonly Violation[];
|
|
146
|
-
/** The command's result, when the command had a ref. */
|
|
147
|
-
readonly result?:
|
|
148
|
-
/** What a
|
|
149
|
-
readonly retry:
|
|
60
|
+
/** The command's result, when the command had a ref ({@link RefusedResult}). */
|
|
61
|
+
readonly result?: RefusedResult;
|
|
62
|
+
/** What a retry may do ({@link retryOf}). */
|
|
63
|
+
readonly retry: Retry;
|
|
64
|
+
/**
|
|
65
|
+
* How long to wait before a retry, in milliseconds: the response's
|
|
66
|
+
* `Retry-After`, else the error catalog's for its code; none when no retry
|
|
67
|
+
* may get past it.
|
|
68
|
+
*/
|
|
69
|
+
readonly retryAfterMs?: number;
|
|
150
70
|
/** The error this one explains: the fetcher's, or the stream's. */
|
|
151
71
|
readonly cause?: unknown;
|
|
152
72
|
/**
|
|
153
73
|
* The request id (`Wow-Request-Id`) of the command this answers: its
|
|
154
74
|
* result's, else the one the client sent. Retry with it when
|
|
155
|
-
* {@link
|
|
75
|
+
* {@link WowProblemError.retry} is `same-request`.
|
|
156
76
|
*/
|
|
157
77
|
get requestId(): string | undefined;
|
|
158
78
|
/**
|
|
@@ -167,6 +87,51 @@ export declare class WowProblemError extends Error {
|
|
|
167
87
|
/** Whether the code is a framework one (`wow.*`) rather than the domain's. */
|
|
168
88
|
get isFramework(): boolean;
|
|
169
89
|
}
|
|
90
|
+
/**
|
|
91
|
+
* The command was rejected: its result's status is `rejected`, decided by
|
|
92
|
+
* its aggregate (a business outcome with the domain's code) or at admission
|
|
93
|
+
* (an unknown command, an invalid one, a caller the authorizer forbids).
|
|
94
|
+
* Sending it again with the same request id is rejected again. As Kotlin's
|
|
95
|
+
* `CommandRejectedException`. `send` and `wait` map what a command is
|
|
96
|
+
* answered by the result's status, not by where it was refused (Kotlin's
|
|
97
|
+
* `CommandClient` maps it the same way):
|
|
98
|
+
*
|
|
99
|
+
* - a result that succeeded: resolved;
|
|
100
|
+
* - a rejected result: a {@link CommandRejectedError};
|
|
101
|
+
* - a problem whose result is rejected, an admission refusal (an unknown
|
|
102
|
+
* command, an invalid one, a forbidden caller): a
|
|
103
|
+
* {@link CommandRejectedError}, its `problem` set;
|
|
104
|
+
* - a result of a status this client does not know, a newer service's: a
|
|
105
|
+
* {@link WowProblemError} `wow.command.failed`, not retryable;
|
|
106
|
+
* - any other problem, refused before admission (a body that does not
|
|
107
|
+
* parse), a technical failure (a busy or closing node, a store or a broker
|
|
108
|
+
* that is down, a wait that timed out) or a failed result: a
|
|
109
|
+
* {@link WowProblemError}, with its result when the service sent one, and
|
|
110
|
+
* what a retry may do ({@link WowProblemError.retry}).
|
|
111
|
+
*
|
|
112
|
+
* `stream` emits every result, whatever its status.
|
|
113
|
+
*/
|
|
114
|
+
export declare class CommandRejectedError extends Error {
|
|
115
|
+
readonly name = "CommandRejectedError";
|
|
116
|
+
/** The rejected result; its ref names no aggregate id when none was decided. */
|
|
117
|
+
readonly result: RefusedResult;
|
|
118
|
+
/** The problem the service answered with, when it answered one. */
|
|
119
|
+
readonly problem?: Problem;
|
|
120
|
+
/** The error this one explains. */
|
|
121
|
+
readonly cause?: unknown;
|
|
122
|
+
/**
|
|
123
|
+
* @param result - The rejected result
|
|
124
|
+
* @param options - The problem it came in, and the error this one explains
|
|
125
|
+
*/
|
|
126
|
+
constructor(result: RefusedResult, options?: {
|
|
127
|
+
problem?: Problem;
|
|
128
|
+
cause?: unknown;
|
|
129
|
+
});
|
|
130
|
+
/** The rejection's error code. */
|
|
131
|
+
get code(): string;
|
|
132
|
+
/** The request id (`Wow-Request-Id`) of the rejected command. */
|
|
133
|
+
get requestId(): string;
|
|
134
|
+
}
|
|
170
135
|
/**
|
|
171
136
|
* Remembers that the request that failed with `error` was sent with
|
|
172
137
|
* `requestId` (internal): {@link requestIdOf} answers it.
|
|
@@ -179,7 +144,7 @@ export declare function rememberRequestId(error: unknown, requestId: string): vo
|
|
|
179
144
|
* The request id (`Wow-Request-Id`) a command that failed with `error` was
|
|
180
145
|
* sent with: also after a failure no server answered (the network, a proxy,
|
|
181
146
|
* an abort), so the command can be retried with the same id and the service
|
|
182
|
-
* answers a commit that did happen as a duplicate
|
|
147
|
+
* answers a commit that did happen as a duplicate.
|
|
183
148
|
* Undefined for an error of no command the client sent.
|
|
184
149
|
*
|
|
185
150
|
* @param error - What a command rejected with
|
package/dist/problem.es.js
CHANGED
|
@@ -1,112 +1,80 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
AGGREGATE_FORBIDDEN: "wow.aggregate.forbidden",
|
|
6
|
-
COMMAND_MALFORMED: "wow.command.malformed",
|
|
7
|
-
COMMAND_INVALID: "wow.command.invalid",
|
|
8
|
-
WAIT_INVALID: "wow.wait.invalid",
|
|
9
|
-
COMMAND_UNHANDLED: "wow.command.unhandled",
|
|
10
|
-
AGGREGATE_NOT_FOUND: "wow.aggregate.not-found",
|
|
11
|
-
AGGREGATE_EXISTS: "wow.aggregate.exists",
|
|
12
|
-
AGGREGATE_VERSION_MISMATCH: "wow.aggregate.version-mismatch",
|
|
13
|
-
COMMAND_REQUEST_ID_REUSED: "wow.command.request-id-reused",
|
|
14
|
-
COMMAND_CONTENDED: "wow.command.contended",
|
|
15
|
-
AGGREGATE_DELETED: "wow.aggregate.deleted",
|
|
16
|
-
COMMAND_BUSY: "wow.command.busy",
|
|
17
|
-
COMMAND_UNKNOWN: "wow.command.unknown",
|
|
18
|
-
COMMAND_FAILED: "wow.command.failed",
|
|
19
|
-
NODE_CLOSING: "wow.node.closing",
|
|
20
|
-
NODE_STANDBY: "wow.node.standby",
|
|
21
|
-
STORAGE_UNAVAILABLE: "wow.storage.unavailable",
|
|
22
|
-
SCHEDULE_NOT_DUE: "wow.schedule.not-due",
|
|
23
|
-
SCHEDULE_JOB_INVALID: "wow.schedule.job-invalid",
|
|
24
|
-
SUBSCRIPTION_PARKED: "wow.subscription.parked",
|
|
25
|
-
WAIT_TIMEOUT: "wow.wait.timeout",
|
|
26
|
-
QUERY_MALFORMED: "wow.query.malformed",
|
|
27
|
-
QUERY_INVALID: "wow.query.invalid",
|
|
28
|
-
QUERY_FAILED: "wow.query.failed",
|
|
29
|
-
QUERY_TIMEOUT: "wow.query.timeout",
|
|
30
|
-
QUERY_BUSY: "wow.query.busy",
|
|
31
|
-
QUERY_NOT_FOUND: "wow.query.not-found",
|
|
32
|
-
QUERY_DATASET_NOT_FOUND: "wow.query.dataset-not-found",
|
|
33
|
-
QUERY_MIN_VERSION_NOT_REACHED: "wow.query.min-version-not-reached",
|
|
34
|
-
QUERY_DATASET_UNAVAILABLE: "wow.query.dataset-unavailable",
|
|
35
|
-
CALL_COMMAND_FORBIDDEN: "wow.call.command-forbidden"
|
|
36
|
-
}, t = "wow.", n = "urn:wow:error:", r = /* @__PURE__ */ new Set([
|
|
1
|
+
import { DEFAULT_RETRY as e, FRAMEWORK_RETRIES as t, FrameworkErrorCodes as n } from "./frameworkErrors.es.js";
|
|
2
|
+
import { CommandResultStatus as r } from "./wire.es.js";
|
|
3
|
+
// src/problem.ts
|
|
4
|
+
var i = "wow.", a = "urn:wow:error:", o = /* @__PURE__ */ new Set([
|
|
37
5
|
"type",
|
|
38
6
|
"title",
|
|
39
7
|
"status",
|
|
40
8
|
"detail",
|
|
41
9
|
"instance",
|
|
42
10
|
"code",
|
|
11
|
+
"retry",
|
|
43
12
|
"violations",
|
|
44
13
|
"result",
|
|
45
14
|
"extensions"
|
|
46
15
|
]);
|
|
47
|
-
function
|
|
16
|
+
function s(e) {
|
|
48
17
|
if (e.extensions !== void 0) return e;
|
|
49
|
-
let t = Object.fromEntries(Object.entries(e).filter(([e]) => !
|
|
18
|
+
let t = Object.fromEntries(Object.entries(e).filter(([e]) => !o.has(e)));
|
|
50
19
|
return Object.keys(t).length === 0 ? e : {
|
|
51
20
|
...e,
|
|
52
21
|
extensions: t
|
|
53
22
|
};
|
|
54
23
|
}
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
[e.STORAGE_UNAVAILABLE, !0],
|
|
60
|
-
[e.SCHEDULE_NOT_DUE, !0],
|
|
61
|
-
[e.COMMAND_BUSY, !0],
|
|
62
|
-
[e.QUERY_BUSY, !1],
|
|
63
|
-
[e.QUERY_MIN_VERSION_NOT_REACHED, !1],
|
|
64
|
-
[e.COMMAND_CONTENDED, !0],
|
|
65
|
-
[e.WAIT_TIMEOUT, !0]
|
|
66
|
-
]);
|
|
67
|
-
function o(e, t, n) {
|
|
68
|
-
let r = e === void 0 ? void 0 : a.get(e), i = r !== void 0 || e === void 0 && t === 503;
|
|
69
|
-
return {
|
|
70
|
-
retryable: i,
|
|
71
|
-
sameRequestId: r ?? i,
|
|
72
|
-
...n === void 0 ? {} : { afterMs: n }
|
|
73
|
-
};
|
|
24
|
+
function c(e) {
|
|
25
|
+
if (e.retry !== void 0) return e.retry;
|
|
26
|
+
let n = e.code === void 0 ? void 0 : t.get(e.code);
|
|
27
|
+
return n ? n.retry : e.code === void 0 && (e.status === 503 || e.status === 429) ? "same-request" : "none";
|
|
74
28
|
}
|
|
75
|
-
var
|
|
29
|
+
var l = class extends Error {
|
|
76
30
|
get requestId() {
|
|
77
|
-
return this.result?.requestId ??
|
|
31
|
+
return this.result?.requestId ?? d.get(this);
|
|
78
32
|
}
|
|
79
|
-
constructor(e,
|
|
80
|
-
super(e.code ? `[${e.code}] ${e.detail ?? e.title}` : `${e.status} ${e.detail ?? e.title}`), this.name = "WowProblemError", this.problem =
|
|
33
|
+
constructor(e, n = {}) {
|
|
34
|
+
super(e.code ? `[${e.code}] ${e.detail ?? e.title}` : `${e.status} ${e.detail ?? e.title}`), this.name = "WowProblemError", this.problem = s(e), this.status = e.status, e.code !== void 0 && (this.code = e.code), this.violations = e.violations ?? [], e.result !== void 0 && (this.result = e.result), this.retry = c(e);
|
|
35
|
+
let r = n.retryAfterMs ?? (e.code === void 0 ? void 0 : t.get(e.code)?.retryAfterMs);
|
|
36
|
+
this.retry !== "none" && r !== void 0 && (this.retryAfterMs = r), n.cause !== void 0 && (this.cause = n.cause);
|
|
81
37
|
}
|
|
82
38
|
get isFramework() {
|
|
83
39
|
return this.code?.startsWith("wow.") ?? !1;
|
|
84
40
|
}
|
|
85
|
-
},
|
|
86
|
-
|
|
87
|
-
|
|
41
|
+
}, u = class extends Error {
|
|
42
|
+
constructor(e, t = {}) {
|
|
43
|
+
let n = [e.error?.code, e.error?.message].filter(Boolean).join(" ");
|
|
44
|
+
if (super(`${e.ref.type.context}.${e.ref.type.name}/${e.ref.id ?? "(no id)"} rejected the command` + (n ? `: ${n}` : ".")), this.name = "CommandRejectedError", e.status !== r.REJECTED) throw TypeError(`A rejection has a rejected result, not ${e.status}.`);
|
|
45
|
+
this.result = e, t.problem !== void 0 && (this.problem = t.problem), t.cause !== void 0 && (this.cause = t.cause);
|
|
46
|
+
}
|
|
47
|
+
get code() {
|
|
48
|
+
return this.result.error?.code ?? "";
|
|
49
|
+
}
|
|
50
|
+
get requestId() {
|
|
51
|
+
return this.result.requestId;
|
|
52
|
+
}
|
|
53
|
+
}, d = /* @__PURE__ */ new WeakMap();
|
|
54
|
+
function f(e, t) {
|
|
55
|
+
(typeof e == "object" && e || typeof e == "function") && (d.has(e) || d.set(e, t));
|
|
88
56
|
}
|
|
89
|
-
function
|
|
90
|
-
return e instanceof
|
|
57
|
+
function p(e) {
|
|
58
|
+
return e instanceof l ? e.requestId : typeof e == "object" && e || typeof e == "function" ? d.get(e) : void 0;
|
|
91
59
|
}
|
|
92
|
-
function
|
|
60
|
+
function m(e) {
|
|
93
61
|
return typeof e == "object" && !!e && typeof e.status == "number";
|
|
94
62
|
}
|
|
95
|
-
function
|
|
63
|
+
function h(e, t = Date.now()) {
|
|
96
64
|
if (!e) return;
|
|
97
65
|
let n = e.trim();
|
|
98
66
|
if (/^\d+$/.test(n)) return Number(n) * 1e3;
|
|
99
67
|
let r = Date.parse(n);
|
|
100
68
|
return Number.isNaN(r) ? void 0 : Math.max(0, r - t);
|
|
101
69
|
}
|
|
102
|
-
async function
|
|
70
|
+
async function g(e) {
|
|
103
71
|
let t;
|
|
104
72
|
try {
|
|
105
73
|
t = await e.clone().json();
|
|
106
74
|
} catch {}
|
|
107
|
-
if (
|
|
75
|
+
if (m(t)) {
|
|
108
76
|
let n = t.code ?? (t.type?.startsWith("urn:wow:error:") ? t.type.slice(14) : void 0);
|
|
109
|
-
return
|
|
77
|
+
return s({
|
|
110
78
|
...t,
|
|
111
79
|
type: t.type ?? "about:blank",
|
|
112
80
|
title: t.title ?? e.statusText,
|
|
@@ -119,20 +87,19 @@ async function p(e) {
|
|
|
119
87
|
status: e.status
|
|
120
88
|
};
|
|
121
89
|
}
|
|
122
|
-
async function
|
|
123
|
-
if (e instanceof
|
|
90
|
+
async function _(e) {
|
|
91
|
+
if (e instanceof l) return e;
|
|
124
92
|
if (typeof e != "object" || !e) return;
|
|
125
93
|
let { exchange: t, cause: n } = e;
|
|
126
|
-
if (n instanceof
|
|
94
|
+
if (n instanceof l) return n;
|
|
127
95
|
let r = t?.response;
|
|
128
96
|
if (!r || r.ok) return;
|
|
129
|
-
let i = await
|
|
130
|
-
return new
|
|
97
|
+
let i = await g(r), a = h(r.headers.get("Retry-After"));
|
|
98
|
+
return new l(i, {
|
|
131
99
|
cause: e,
|
|
132
100
|
...a === void 0 ? {} : { retryAfterMs: a }
|
|
133
101
|
});
|
|
134
102
|
}
|
|
135
|
-
|
|
136
|
-
export { t as FRAMEWORK_ERROR_PREFIX, e as FrameworkErrorCodes, n as PROBLEM_TYPE_PREFIX, s as WowProblemError, d as isProblem, f as parseRetryAfter, p as readProblem, l as rememberRequestId, u as requestIdOf, o as retryHintOf, m as toWowProblemError };
|
|
103
|
+
export { u as CommandRejectedError, e as DEFAULT_RETRY, i as FRAMEWORK_ERROR_PREFIX, t as FRAMEWORK_RETRIES, n as FrameworkErrorCodes, a as PROBLEM_TYPE_PREFIX, l as WowProblemError, m as isProblem, h as parseRetryAfter, g as readProblem, f as rememberRequestId, p as requestIdOf, c as retryOf, _ as toWowProblemError };
|
|
137
104
|
|
|
138
105
|
//# sourceMappingURL=problem.es.js.map
|
package/dist/problem.es.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"problem.es.js","names":["FrameworkErrorCodes","FRAMEWORK_ERROR_PREFIX","PROBLEM_TYPE_PREFIX","PROBLEM_MEMBERS","withExtensions","problem","extensions","name","RETRYABLE","retryHintOf","sameRequestId","code","retryable","status","afterMs","WowProblemError","SENT_REQUEST_IDS","options","rememberRequestId","error","requestId","requestIdOf","isProblem","value","parseRetryAfter","trimmed","date","now","readProblem","body","response","toWowProblemError","cause","exchange","retryAfterMs"],"sources":["../src/problem.ts"],"sourcesContent":["/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type { CommandResult, Violation } from './wire.js';\n\n/**\n * The framework's error codes (design 05 §3, decisions D102, D103, D130),\n * each answered with the status of the Manifest's `errors` table. A domain\n * rejection has a code of its own, answered with 422 unless the service\n * configures another status.\n */\nexport const FrameworkErrorCodes = {\n /** 401: the request carries no valid credentials. */\n AUTH_UNAUTHENTICATED: 'wow.auth.unauthenticated',\n /** 403: the caller may not send this command. */\n AUTH_FORBIDDEN: 'wow.auth.forbidden',\n /** 403: the aggregate is outside the caller's scope. */\n AGGREGATE_FORBIDDEN: 'wow.aggregate.forbidden',\n /** 400: the command body cannot be read as the command type. */\n COMMAND_MALFORMED: 'wow.command.malformed',\n /** 400: the command failed validation; the problem lists the violations. */\n COMMAND_INVALID: 'wow.command.invalid',\n /** 400: the wait is not a chain the runtime can follow. */\n WAIT_INVALID: 'wow.wait.invalid',\n /** 400: the aggregate does not handle this command. */\n COMMAND_UNHANDLED: 'wow.command.unhandled',\n /** 404: the aggregate does not exist. */\n AGGREGATE_NOT_FOUND: 'wow.aggregate.not-found',\n /** 409: the aggregate already exists. */\n AGGREGATE_EXISTS: 'wow.aggregate.exists',\n /** 409, or 412 with `If-Match`: the aggregate is not at the expected version. */\n AGGREGATE_VERSION_MISMATCH: 'wow.aggregate.version-mismatch',\n /** 409: the request id was used by another command. */\n COMMAND_REQUEST_ID_REUSED: 'wow.command.request-id-reused',\n /** 409: concurrent writers kept winning; retrying with the same request id is safe. */\n COMMAND_CONTENDED: 'wow.command.contended',\n /** 410: the aggregate is deleted; only RestoreAggregate applies. */\n AGGREGATE_DELETED: 'wow.aggregate.deleted',\n /** 429: the command was not taken, its aggregate or the node being busy; retry later. */\n COMMAND_BUSY: 'wow.command.busy',\n /** 503: whether the command committed is unknown; retrying with the same request id is safe. */\n COMMAND_UNKNOWN: 'wow.command.unknown',\n /** 500: the command's handling failed with an unexpected error; it committed nothing, and a retry fails alike. */\n COMMAND_FAILED: 'wow.command.failed',\n /** 503: the node is shutting down; retry on another node. */\n NODE_CLOSING: 'wow.node.closing',\n /** 503: the node is on standby until a migration's cut-over; it serves reads only. */\n NODE_STANDBY: 'wow.node.standby',\n /** 503, with `Retry-After`: a store could not be reached in time; retry later. */\n STORAGE_UNAVAILABLE: 'wow.storage.unavailable',\n /** 503: a scheduled command arrived too long before its due time; it is sent again later. */\n SCHEDULE_NOT_DUE: 'wow.schedule.not-due',\n /** 400: the job command does not fit its job or instance (decision D198). */\n SCHEDULE_JOB_INVALID: 'wow.schedule.job-invalid',\n /** 500: a subscription on the wait chain parked the aggregate. */\n SUBSCRIPTION_PARKED: 'wow.subscription.parked',\n /** 504: the wait ran out of time; the command may have committed. */\n WAIT_TIMEOUT: 'wow.wait.timeout',\n /** 400: the query body cannot be read as a query. */\n QUERY_MALFORMED: 'wow.query.malformed',\n /** 400: the query failed admission; each violation has its code. */\n QUERY_INVALID: 'wow.query.invalid',\n /** 500: the query backend failed to run the query. */\n QUERY_FAILED: 'wow.query.failed',\n /** 504: the query ran longer than its budget allows; not retried (decision D254 ③). */\n QUERY_TIMEOUT: 'wow.query.timeout',\n /** 429, with `Retry-After`: the query's store runs as many queries as it allows; retry later. */\n QUERY_BUSY: 'wow.query.busy',\n /**\n * 404: a `single` query matched no record, whatever its model (review R4-Q,\n * Q-4); a state read by id that finds none is `wow.aggregate.not-found`.\n */\n QUERY_NOT_FOUND: 'wow.query.not-found',\n /** 404: no dataset of that name is served to the caller. */\n QUERY_DATASET_NOT_FOUND: 'wow.query.dataset-not-found',\n /**\n * 409, with `Retry-After`: a state read asked for a version (`minVersion`) the\n * aggregate has not reached within the wait; the problem's `version` is its\n * current one (review R4-Q, Q-13).\n */\n QUERY_MIN_VERSION_NOT_REACHED: 'wow.query.min-version-not-reached',\n /** 409: the dataset is served but cannot be queried now (it needs revision, decision D259). */\n QUERY_DATASET_UNAVAILABLE: 'wow.query.dataset-unavailable',\n /** 403: the calling service may not call this command (a synchronous call on the internal port, decision D226). */\n CALL_COMMAND_FORBIDDEN: 'wow.call.command-forbidden',\n} as const;\n\n/** A {@link FrameworkErrorCodes} value. */\nexport type FrameworkErrorCode =\n (typeof FrameworkErrorCodes)[keyof typeof FrameworkErrorCodes];\n\n/** The prefix of every framework code, and of no domain code. */\nexport const FRAMEWORK_ERROR_PREFIX = 'wow.';\n\n/** The prefix of a problem's `type` that carries a Wow code. */\nexport const PROBLEM_TYPE_PREFIX = 'urn:wow:error:';\n\n/**\n * An RFC 9457 problem as a Wow service writes it (decisions D101, D102):\n * `type` is `urn:wow:error:<code>`, or `about:blank` for an error that is\n * only HTTP's (a missing route, 406, 415).\n */\nexport interface Problem {\n readonly type: string;\n readonly title: string;\n readonly status: number;\n readonly detail?: string;\n /** The Wow code; absent for an error that is only HTTP's. */\n readonly code?: string;\n readonly violations?: readonly Violation[];\n /** The whole result of a command that has a ref. */\n readonly result?: CommandResult;\n /**\n * The problem's extension members (RFC 9457): every member the server\n * wrote besides the ones above and `instance`, such as a rejection's\n * structured data (decision D211). Absent when it wrote none.\n */\n readonly extensions?: Readonly<Record<string, unknown>>;\n}\n\n/** The members of a problem that are not extension members. */\nconst PROBLEM_MEMBERS: ReadonlySet<string> = new Set([\n 'type',\n 'title',\n 'status',\n 'detail',\n 'instance',\n 'code',\n 'violations',\n 'result',\n 'extensions',\n]);\n\n/**\n * `problem` with its extension members gathered as `extensions` (internal):\n * a problem read from the wire carries them as top-level members.\n */\nfunction withExtensions(problem: Problem): Problem {\n if (problem.extensions !== undefined) return problem;\n const extensions = Object.fromEntries(\n Object.entries(problem).filter(([name]) => !PROBLEM_MEMBERS.has(name)),\n );\n return Object.keys(extensions).length === 0\n ? problem\n : { ...problem, extensions };\n}\n\n/**\n * What a client may do about a failed request: whether retrying can succeed,\n * whether to keep the request id (`Wow-Request-Id`) so the server\n * deduplicates a command that did commit, and how long to wait first.\n */\nexport interface RetryHint {\n readonly retryable: boolean;\n /** Retry with the same `Wow-Request-Id`: a commit is then answered as a duplicate. */\n readonly sameRequestId: boolean;\n /** The server's `Retry-After`, in milliseconds. */\n readonly afterMs?: number;\n}\n\n/**\n * The codes a retry may get past, each with whether to keep the request id:\n * the 503s (`wow.command.unknown`, `wow.node.closing`, `wow.node.standby`,\n * `wow.storage.unavailable`, `wow.schedule.not-due`),\n * the 429s `wow.command.busy` and `wow.query.busy`, the 409s `wow.command.contended` and\n * `wow.query.min-version-not-reached` (once the command commits), and the 504\n * `wow.wait.timeout`, whose command may have committed.\n */\nconst RETRYABLE: ReadonlyMap<string, boolean> = new Map([\n [FrameworkErrorCodes.COMMAND_UNKNOWN, true],\n [FrameworkErrorCodes.NODE_CLOSING, true],\n [FrameworkErrorCodes.NODE_STANDBY, true],\n [FrameworkErrorCodes.STORAGE_UNAVAILABLE, true],\n [FrameworkErrorCodes.SCHEDULE_NOT_DUE, true],\n [FrameworkErrorCodes.COMMAND_BUSY, true],\n [FrameworkErrorCodes.QUERY_BUSY, false],\n [FrameworkErrorCodes.QUERY_MIN_VERSION_NOT_REACHED, false],\n [FrameworkErrorCodes.COMMAND_CONTENDED, true],\n [FrameworkErrorCodes.WAIT_TIMEOUT, true],\n]);\n\n/**\n * The retry hint of a problem with `code` and `status`: a code of the\n * retryable table, or a 503 without a code (a proxy's), may be retried.\n *\n * @param code - The problem's Wow code, if any\n * @param status - The HTTP status\n * @param afterMs - The `Retry-After` the response carried, in milliseconds\n */\nexport function retryHintOf(\n code: string | undefined,\n status: number,\n afterMs?: number,\n): RetryHint {\n const sameRequestId = code === undefined ? undefined : RETRYABLE.get(code);\n const retryable =\n sameRequestId !== undefined || (code === undefined && status === 503);\n return {\n retryable,\n sameRequestId: sameRequestId ?? retryable,\n ...(afterMs === undefined ? {} : { afterMs }),\n };\n}\n\n/**\n * A request a Wow service answered with a problem: a non-2xx response, a\n * command result that did not succeed, or the `error` event that ends a\n * streamed query.\n */\nexport class WowProblemError extends Error {\n override readonly name = 'WowProblemError';\n /** The problem as the server wrote it. */\n readonly problem: Problem;\n /** The HTTP status. */\n readonly status: number;\n /** The Wow code; absent for an error that is only HTTP's. */\n readonly code?: string;\n readonly violations: readonly Violation[];\n /** The command's result, when the command had a ref. */\n readonly result?: CommandResult;\n /** What a client may do about it. */\n readonly retry: RetryHint;\n /** The error this one explains: the fetcher's, or the stream's. */\n readonly cause?: unknown;\n\n /**\n * The request id (`Wow-Request-Id`) of the command this answers: its\n * result's, else the one the client sent. Retry with it when\n * {@link RetryHint.sameRequestId} says so.\n */\n get requestId(): string | undefined {\n return this.result?.requestId ?? SENT_REQUEST_IDS.get(this);\n }\n\n /**\n * @param problem - The problem the server answered with\n * @param options - The response's `Retry-After` in milliseconds, and the\n * error this one explains\n */\n constructor(\n problem: Problem,\n options: { retryAfterMs?: number; cause?: unknown } = {},\n ) {\n super(\n problem.code\n ? `[${problem.code}] ${problem.detail ?? problem.title}`\n : `${problem.status} ${problem.detail ?? problem.title}`,\n );\n this.problem = withExtensions(problem);\n this.status = problem.status;\n if (problem.code !== undefined) this.code = problem.code;\n this.violations = problem.violations ?? [];\n if (problem.result !== undefined) this.result = problem.result;\n this.retry = retryHintOf(\n problem.code,\n problem.status,\n options.retryAfterMs,\n );\n if (options.cause !== undefined) this.cause = options.cause;\n }\n\n /** Whether the code is a framework one (`wow.*`) rather than the domain's. */\n get isFramework(): boolean {\n return this.code?.startsWith(FRAMEWORK_ERROR_PREFIX) ?? false;\n }\n}\n\n/** The request ids the client sent, by the errors the requests failed with. */\nconst SENT_REQUEST_IDS = new WeakMap<object, string>();\n\n/**\n * Remembers that the request that failed with `error` was sent with\n * `requestId` (internal): {@link requestIdOf} answers it.\n *\n * @param error - What the request failed with\n * @param requestId - The `Wow-Request-Id` it was sent with\n */\nexport function rememberRequestId(error: unknown, requestId: string): void {\n if (\n (typeof error === 'object' && error !== null) ||\n typeof error === 'function'\n ) {\n if (!SENT_REQUEST_IDS.has(error)) SENT_REQUEST_IDS.set(error, requestId);\n }\n}\n\n/**\n * The request id (`Wow-Request-Id`) a command that failed with `error` was\n * sent with: also after a failure no server answered (the network, a proxy,\n * an abort), so the command can be retried with the same id and the service\n * answers a commit that did happen as a duplicate (decision D223).\n * Undefined for an error of no command the client sent.\n *\n * @param error - What a command rejected with\n */\nexport function requestIdOf(error: unknown): string | undefined {\n if (error instanceof WowProblemError) return error.requestId;\n return (typeof error === 'object' && error !== null) ||\n typeof error === 'function'\n ? SENT_REQUEST_IDS.get(error)\n : undefined;\n}\n\n/** Whether `value` reads as a problem: an object with a numeric `status`. */\nexport function isProblem(value: unknown): value is Problem {\n return (\n typeof value === 'object' &&\n value !== null &&\n typeof (value as { status?: unknown }).status === 'number'\n );\n}\n\n/**\n * The milliseconds of a `Retry-After` header: delay seconds or an HTTP date.\n *\n * @param value - The header's value\n * @param now - The current time, in epoch milliseconds\n */\nexport function parseRetryAfter(\n value: string | null | undefined,\n now: number = Date.now(),\n): number | undefined {\n if (!value) return undefined;\n const trimmed = value.trim();\n if (/^\\d+$/.test(trimmed)) return Number(trimmed) * 1000;\n const date = Date.parse(trimmed);\n return Number.isNaN(date) ? undefined : Math.max(0, date - now);\n}\n\n/**\n * The problem a response that did not succeed carries: its body when it is\n * a problem (or a code the `type` names), else one made of its status.\n *\n * @param response - A response that is not 2xx\n */\nexport async function readProblem(response: Response): Promise<Problem> {\n let body: unknown;\n try {\n body = await response.clone().json();\n } catch {\n // Not JSON, or already read: the status is all there is.\n }\n if (isProblem(body)) {\n const code =\n body.code ??\n (body.type?.startsWith(PROBLEM_TYPE_PREFIX)\n ? body.type.slice(PROBLEM_TYPE_PREFIX.length)\n : undefined);\n return withExtensions({\n ...body,\n type: body.type ?? 'about:blank',\n title: body.title ?? response.statusText,\n ...(code === undefined ? {} : { code }),\n });\n }\n return {\n type: 'about:blank',\n title: response.statusText,\n status: response.status,\n };\n}\n\ninterface ExchangeLike {\n exchange?: { response?: Response };\n cause?: unknown;\n}\n\n/**\n * The {@link WowProblemError} of an error a request rejected with: the\n * fetcher's `ExchangeError` of a response that is not 2xx, read as a problem.\n * Undefined for a failure no server answered (a network error, an abort).\n *\n * @param error - What the request rejected with\n */\nexport async function toWowProblemError(\n error: unknown,\n): Promise<WowProblemError | undefined> {\n if (error instanceof WowProblemError) return error;\n if (typeof error !== 'object' || error === null) return undefined;\n const { exchange, cause } = error as ExchangeLike;\n if (cause instanceof WowProblemError) return cause;\n const response = exchange?.response;\n if (!response || response.ok) return undefined;\n const problem = await readProblem(response);\n const retryAfterMs = parseRetryAfter(response.headers.get('Retry-After'));\n return new WowProblemError(problem, {\n cause: error,\n ...(retryAfterMs === undefined ? {} : { retryAfterMs }),\n });\n}\n"],"mappings":";AAqBA,IAAaA,IAAsB;CAEj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AAS,IAAI;CAC9B,IAAMzB,IAAU,MAAMuB,EAAYE,CAAQ,GACpCI,IAAeV,EAAgBM,EAAS,QAAQ,IAAI,aAAa,CAAC;CACxE,OAAO,IAAIf,EAAgBV,GAAS;EAClC,OAAOc;EACP,GAAIe,MAAiB,KAAA,IAAY,CAAC,IAAI,EAAE,gBAAa;CACvD,CAAC;AACH"}
|
|
1
|
+
{"version":3,"file":"problem.es.js","names":["FRAMEWORK_ERROR_PREFIX","PROBLEM_TYPE_PREFIX","PROBLEM_MEMBERS","withExtensions","problem","extensions","name","retryOf","known","FRAMEWORK_RETRIES","WowProblemError","SENT_REQUEST_IDS","retryAfterMs","options","CommandRejectedError","said","result","CommandResultStatus","rememberRequestId","error","requestId","requestIdOf","isProblem","value","parseRetryAfter","trimmed","date","now","readProblem","body","response","code","toWowProblemError","cause","exchange","DEFAULT_RETRY","FrameworkErrorCodes"],"sources":["../src/problem.ts"],"sourcesContent":["/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FRAMEWORK_RETRIES, type Retry } from './frameworkErrors.js';\nimport {\n CommandResultStatus,\n type RefusedResult,\n type Violation,\n} from './wire.js';\n\nexport {\n DEFAULT_RETRY,\n FRAMEWORK_RETRIES,\n type FrameworkRetry,\n type FrameworkErrorCode,\n FrameworkErrorCodes,\n type Retry,\n} from './frameworkErrors.js';\n\n/** The prefix of every framework code, and of no domain code. */\nexport const FRAMEWORK_ERROR_PREFIX = 'wow.';\n\n/** The prefix of a problem's `type` that carries a Wow code. */\nexport const PROBLEM_TYPE_PREFIX = 'urn:wow:error:';\n\n/**\n * An RFC 9457 problem as a Wow service writes it:\n * `type` is `urn:wow:error:<code>`, or `about:blank` for an error that is\n * only HTTP's (a missing route, 406, 415).\n */\nexport interface Problem {\n readonly type: string;\n readonly title: string;\n readonly status: number;\n readonly detail?: string;\n /** The Wow code; absent for an error that is only HTTP's. */\n readonly code?: string;\n /**\n * What a retry may do, as the error catalog declares it for the code: every\n * problem a Wow service writes carries it.\n */\n readonly retry?: Retry;\n readonly violations?: readonly Violation[];\n /**\n * The whole result of a command that has a ref; its id is null when\n * admission refused a creation before choosing one.\n */\n readonly result?: RefusedResult;\n /**\n * The problem's extension members (RFC 9457): every member the server\n * wrote besides the ones above and `instance`, such as a rejection's\n * structured data (decision D211). Absent when it wrote none.\n */\n readonly extensions?: Readonly<Record<string, unknown>>;\n}\n\n/** The members of a problem that are not extension members. */\nconst PROBLEM_MEMBERS: ReadonlySet<string> = new Set([\n 'type',\n 'title',\n 'status',\n 'detail',\n 'instance',\n 'code',\n 'retry',\n 'violations',\n 'result',\n 'extensions',\n]);\n\n/**\n * `problem` with its extension members gathered as `extensions` (internal):\n * a problem read from the wire carries them as top-level members.\n */\nfunction withExtensions(problem: Problem): Problem {\n if (problem.extensions !== undefined) return problem;\n const extensions = Object.fromEntries(\n Object.entries(problem).filter(([name]) => !PROBLEM_MEMBERS.has(name)),\n );\n return Object.keys(extensions).length === 0\n ? problem\n : { ...problem, extensions };\n}\n\n/**\n * What a retry of `problem` may do: its `retry` member, which every problem a\n * Wow service writes carries; else the error catalog's for its code; else, for\n * a body that is no Wow problem (a proxy's 503 or 429), `same-request`.\n *\n * @param problem - The problem a request was answered with\n */\nexport function retryOf(problem: Problem): Retry {\n if (problem.retry !== undefined) return problem.retry;\n const known =\n problem.code === undefined\n ? undefined\n : FRAMEWORK_RETRIES.get(problem.code);\n if (known) return known.retry;\n return problem.code === undefined &&\n (problem.status === 503 || problem.status === 429)\n ? 'same-request'\n : 'none';\n}\n\n/**\n * A request a Wow service answered with a problem: a non-2xx response, a\n * command result that did not succeed, or the `error` event that ends a\n * streamed query.\n */\nexport class WowProblemError extends Error {\n override readonly name = 'WowProblemError';\n /** The problem as the server wrote it. */\n readonly problem: Problem;\n /** The HTTP status. */\n readonly status: number;\n /** The Wow code; absent for an error that is only HTTP's. */\n readonly code?: string;\n readonly violations: readonly Violation[];\n /** The command's result, when the command had a ref ({@link RefusedResult}). */\n readonly result?: RefusedResult;\n /** What a retry may do ({@link retryOf}). */\n readonly retry: Retry;\n /**\n * How long to wait before a retry, in milliseconds: the response's\n * `Retry-After`, else the error catalog's for its code; none when no retry\n * may get past it.\n */\n readonly retryAfterMs?: number;\n /** The error this one explains: the fetcher's, or the stream's. */\n readonly cause?: unknown;\n\n /**\n * The request id (`Wow-Request-Id`) of the command this answers: its\n * result's, else the one the client sent. Retry with it when\n * {@link WowProblemError.retry} is `same-request`.\n */\n get requestId(): string | undefined {\n return this.result?.requestId ?? SENT_REQUEST_IDS.get(this);\n }\n\n /**\n * @param problem - The problem the server answered with\n * @param options - The response's `Retry-After` in milliseconds, and the\n * error this one explains\n */\n constructor(\n problem: Problem,\n options: { retryAfterMs?: number; cause?: unknown } = {},\n ) {\n super(\n problem.code\n ? `[${problem.code}] ${problem.detail ?? problem.title}`\n : `${problem.status} ${problem.detail ?? problem.title}`,\n );\n this.problem = withExtensions(problem);\n this.status = problem.status;\n if (problem.code !== undefined) this.code = problem.code;\n this.violations = problem.violations ?? [];\n if (problem.result !== undefined) this.result = problem.result;\n this.retry = retryOf(problem);\n const retryAfterMs =\n options.retryAfterMs ??\n (problem.code === undefined\n ? undefined\n : FRAMEWORK_RETRIES.get(problem.code)?.retryAfterMs);\n if (this.retry !== 'none' && retryAfterMs !== undefined) {\n this.retryAfterMs = retryAfterMs;\n }\n if (options.cause !== undefined) this.cause = options.cause;\n }\n\n /** Whether the code is a framework one (`wow.*`) rather than the domain's. */\n get isFramework(): boolean {\n return this.code?.startsWith(FRAMEWORK_ERROR_PREFIX) ?? false;\n }\n}\n\n/**\n * The command was rejected: its result's status is `rejected`, decided by\n * its aggregate (a business outcome with the domain's code) or at admission\n * (an unknown command, an invalid one, a caller the authorizer forbids).\n * Sending it again with the same request id is rejected again. As Kotlin's\n * `CommandRejectedException`. `send` and `wait` map what a command is\n * answered by the result's status, not by where it was refused (Kotlin's\n * `CommandClient` maps it the same way):\n *\n * - a result that succeeded: resolved;\n * - a rejected result: a {@link CommandRejectedError};\n * - a problem whose result is rejected, an admission refusal (an unknown\n * command, an invalid one, a forbidden caller): a\n * {@link CommandRejectedError}, its `problem` set;\n * - a result of a status this client does not know, a newer service's: a\n * {@link WowProblemError} `wow.command.failed`, not retryable;\n * - any other problem, refused before admission (a body that does not\n * parse), a technical failure (a busy or closing node, a store or a broker\n * that is down, a wait that timed out) or a failed result: a\n * {@link WowProblemError}, with its result when the service sent one, and\n * what a retry may do ({@link WowProblemError.retry}).\n *\n * `stream` emits every result, whatever its status.\n */\nexport class CommandRejectedError extends Error {\n override readonly name = 'CommandRejectedError';\n /** The rejected result; its ref names no aggregate id when none was decided. */\n readonly result: RefusedResult;\n /** The problem the service answered with, when it answered one. */\n readonly problem?: Problem;\n /** The error this one explains. */\n readonly cause?: unknown;\n\n /**\n * @param result - The rejected result\n * @param options - The problem it came in, and the error this one explains\n */\n constructor(\n result: RefusedResult,\n options: { problem?: Problem; cause?: unknown } = {},\n ) {\n const said = [result.error?.code, result.error?.message]\n .filter(Boolean)\n .join(' ');\n super(\n `${result.ref.type.context}.${result.ref.type.name}/${result.ref.id ?? '(no id)'} rejected the command` +\n (said ? `: ${said}` : '.'),\n );\n if (result.status !== CommandResultStatus.REJECTED) {\n throw new TypeError(\n `A rejection has a rejected result, not ${result.status}.`,\n );\n }\n this.result = result;\n if (options.problem !== undefined) this.problem = options.problem;\n if (options.cause !== undefined) this.cause = options.cause;\n }\n\n /** The rejection's error code. */\n get code(): string {\n return this.result.error?.code ?? '';\n }\n\n /** The request id (`Wow-Request-Id`) of the rejected command. */\n get requestId(): string {\n return this.result.requestId;\n }\n}\n\n/** The request ids the client sent, by the errors the requests failed with. */\nconst SENT_REQUEST_IDS = new WeakMap<object, string>();\n\n/**\n * Remembers that the request that failed with `error` was sent with\n * `requestId` (internal): {@link requestIdOf} answers it.\n *\n * @param error - What the request failed with\n * @param requestId - The `Wow-Request-Id` it was sent with\n */\nexport function rememberRequestId(error: unknown, requestId: string): void {\n if (\n (typeof error === 'object' && error !== null) ||\n typeof error === 'function'\n ) {\n if (!SENT_REQUEST_IDS.has(error)) SENT_REQUEST_IDS.set(error, requestId);\n }\n}\n\n/**\n * The request id (`Wow-Request-Id`) a command that failed with `error` was\n * sent with: also after a failure no server answered (the network, a proxy,\n * an abort), so the command can be retried with the same id and the service\n * answers a commit that did happen as a duplicate.\n * Undefined for an error of no command the client sent.\n *\n * @param error - What a command rejected with\n */\nexport function requestIdOf(error: unknown): string | undefined {\n if (error instanceof WowProblemError) return error.requestId;\n return (typeof error === 'object' && error !== null) ||\n typeof error === 'function'\n ? SENT_REQUEST_IDS.get(error)\n : undefined;\n}\n\n/** Whether `value` reads as a problem: an object with a numeric `status`. */\nexport function isProblem(value: unknown): value is Problem {\n return (\n typeof value === 'object' &&\n value !== null &&\n typeof (value as { status?: unknown }).status === 'number'\n );\n}\n\n/**\n * The milliseconds of a `Retry-After` header: delay seconds or an HTTP date.\n *\n * @param value - The header's value\n * @param now - The current time, in epoch milliseconds\n */\nexport function parseRetryAfter(\n value: string | null | undefined,\n now: number = Date.now(),\n): number | undefined {\n if (!value) return undefined;\n const trimmed = value.trim();\n if (/^\\d+$/.test(trimmed)) return Number(trimmed) * 1000;\n const date = Date.parse(trimmed);\n return Number.isNaN(date) ? undefined : Math.max(0, date - now);\n}\n\n/**\n * The problem a response that did not succeed carries: its body when it is\n * a problem (or a code the `type` names), else one made of its status.\n *\n * @param response - A response that is not 2xx\n */\nexport async function readProblem(response: Response): Promise<Problem> {\n let body: unknown;\n try {\n body = await response.clone().json();\n } catch {\n // Not JSON, or already read: the status is all there is.\n }\n if (isProblem(body)) {\n const code =\n body.code ??\n (body.type?.startsWith(PROBLEM_TYPE_PREFIX)\n ? body.type.slice(PROBLEM_TYPE_PREFIX.length)\n : undefined);\n return withExtensions({\n ...body,\n type: body.type ?? 'about:blank',\n title: body.title ?? response.statusText,\n ...(code === undefined ? {} : { code }),\n });\n }\n return {\n type: 'about:blank',\n title: response.statusText,\n status: response.status,\n };\n}\n\ninterface ExchangeLike {\n exchange?: { response?: Response };\n cause?: unknown;\n}\n\n/**\n * The {@link WowProblemError} of an error a request rejected with: the\n * fetcher's `ExchangeError` of a response that is not 2xx, read as a problem.\n * Undefined for a failure no server answered (a network error, an abort).\n *\n * @param error - What the request rejected with\n */\nexport async function toWowProblemError(\n error: unknown,\n): Promise<WowProblemError | undefined> {\n if (error instanceof WowProblemError) return error;\n if (typeof error !== 'object' || error === null) return undefined;\n const { exchange, cause } = error as ExchangeLike;\n if (cause instanceof WowProblemError) return cause;\n const response = exchange?.response;\n if (!response || response.ok) return undefined;\n const problem = await readProblem(response);\n const retryAfterMs = parseRetryAfter(response.headers.get('Retry-After'));\n return new WowProblemError(problem, {\n cause: error,\n ...(retryAfterMs === undefined ? {} : { retryAfterMs }),\n });\n}\n"],"mappings":";;;AA8BA,IAAaA,IAAyB,QAGzBC,IAAsB,kBAkC7BC,oBAAuC,IAAI,IAAI;CACnD;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC;AAMD,SAASC,EAAe,GAA2B;CACjD,IAAIC,EAAQ,eAAe,KAAA,GAAW,OAAOA;CAC7C,IAAMC,IAAa,OAAO,YACxB,OAAO,QAAQD,CAAO,CAAC,CAAC,QAAQ,CAACE,OAAU,CAACJ,EAAgB,IAAII,CAAI,CAAC,CACvE;CACA,OAAO,OAAO,KAAKD,CAAU,CAAC,CAAC,WAAW,IACtCD,IACA;EAAE,GAAGA;EAAS;CAAW;AAC/B;AASA,SAAgBG,EAAQ,GAAyB;CAC/C,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Y,KAAK,IAAI,GAAGA,IAAOC,CAAG;AAChE;AAQA,eAAsBC,EAAY,GAAsC;CACtE,IAAIC;CACJ,IAAI;EACF,IAAO,MAAMC,EAAS,MAAM,CAAC,CAAC,KAAK;CACrC,QAAQ,CAER;CACA,IAAIR,EAAUO,CAAI,GAAG;EACnB,IAAME,IACJF,EAAK,SACJA,EAAK,MAAM,WAAA,gBAA8B,IACtCA,EAAK,KAAK,MAAM,EAA0B,IAC1C,KAAA;EACN,OAAO1B,EAAe;GACpB,GAAG0B;GACH,MAAMA,EAAK,QAAQ;GACnB,OAAOA,EAAK,SAASC,EAAS;GAC9B,GAAIC,MAAS,KAAA,IAAY,CAAC,IAAI,EAAE,QAAK;EACvC,CAAC;CACH;CACA,OAAO;EACL,MAAM;EACN,OAAOD,EAAS;EAChB,QAAQA,EAAS;CACnB;AACF;AAcA,eAAsBE,EACpB,GACsC;CACtC,IAAIb,aAAiBT,GAAiB,OAAOS;CAC7C,IAAI,OAAOA,KAAU,aAAYA,GAAgB;CACjD,IAAM,EAAE,aAAU,aAAUA;CAC5B,IAAIc,aAAiBvB,GAAiB,OAAOuB;CAC7C,IAAMH,IAAWI,GAAU;CAC3B,IAAI,CAACJ,KAAYA,EAAS,IAAI;CAC9B,IAAM1B,IAAU,MAAMwB,EAAYE,CAAQ,GACpClB,IAAeY,EAAgBM,EAAS,QAAQ,IAAI,aAAa,CAAC;CACxE,OAAO,IAAIpB,EAAgBN,GAAS;EAClC,OAAOe;EACP,GAAIP,MAAiB,KAAA,IAAY,CAAC,IAAI,EAAE,gBAAa;CACvD,CAAC;AACH"}
|
package/dist/queries.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
const e=require("./exactJson.cjs"),t=require("./
|
|
1
|
+
const e=require("./exactJson.cjs"),t=require("./frameworkErrors.cjs"),n=require("./problem.cjs"),r=require("./http.cjs"),i=require("./streams.cjs");var a=class{constructor(e,t={},n){this.path=e,this.client=t,this.numbers=n}get listNumbers(){return this.numbers===void 0?void 0:{"*":this.numbers}}get pageNumbers(){return this.numbers===void 0?void 0:{list:{"*":this.numbers}}}async list(e,t){return r.json(await this.post(`list`,e,t),this.listNumbers)}async stream(e,t){return(await this.streamRows(e,t)).pipeThrough(new TransformStream({transform(e,t){t.enqueue(e.row)}}))}async streamRows(e,t={}){let n=t.resume===!1?{maxRetries:0}:t.resume,r=e.limit,a=(n,i)=>this.post(`list`,r===void 0?e:{...e,limit:r-i},t,`text/event-stream`,n),o=await a(n?.lastEventId,0);return i.resumableQueryRows(o,(e,t)=>r!==void 0&&t>=r?Promise.resolve(void 0):a(e,t),{...n,...t.signal===void 0?{}:{signal:t.signal},...this.numbers===void 0?{}:{numbers:this.numbers}})}async paged(e,t){return r.json(await this.post(`paged`,e,t),this.pageNumbers)}async cursor(e,t){return r.json(await this.post(`cursor`,e,t),this.pageNumbers)}async single(e,t){try{return r.json(await this.post(`single`,e,t),this.numbers)}catch(e){if(o(e))return;throw e}}async count(e,t){return r.json(await this.post(`count`,e,t))}async aggregate(e,t){return r.json(await this.post(`aggregate`,e,t))}async describe(e,t){let n=await r.send(this.client,{method:`GET`,path:this.path,headers:{[r.WowHeaders.IF_NONE_MATCH]:e===void 0?void 0:`"${e}"`},options:t,notModified:!0}),i=r.entityTag(n);return n.status===304?{notModified:!0,version:i??e??``}:{notModified:!1,...i===void 0?{}:{version:i},descriptor:await r.json(n)}}post(e,t,n,i,a){return r.send(this.client,{method:`POST`,path:this.path,headers:{Accept:i,[r.WowHeaders.LAST_EVENT_ID]:a},body:{...t,kind:e},options:n})}};function o(e){return e instanceof n.WowProblemError&&e.status===404&&(e.code===t.FrameworkErrorCodes.QUERY_NOT_FOUND||e.code===t.FrameworkErrorCodes.AGGREGATE_NOT_FOUND)}function s(e,t){return`/${e.context}/${e.name}/${t}/query`}var c=class extends a{constructor(e,t){super(s(e,`snapshot`),t,e.textNumbers?.state===void 0?void 0:{state:e.textNumbers.state}),this.type=e}},l=class extends a{constructor(t,n){let r=e.eventNumbers(t);super(s(t,`events`),n,r===void 0?void 0:{events:{"*":r}}),this.type=t}},u=class{constructor(e={}){this.client=e}async list(e){return r.json(await r.send(this.client,{method:`GET`,path:`/wow/dataset`,options:e}))}dataset(e,t){return new a(`/wow/dataset/${encodeURIComponent(e)}/${encodeURIComponent(t)}/query`,this.client)}};exports.DatasetClient=u,exports.EventQueryClient=l,exports.QueryModelClient=a,exports.SnapshotQueryClient=c,exports.queryPath=s;
|
|
2
2
|
//# sourceMappingURL=queries.cjs.map
|
package/dist/queries.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"queries.cjs","names":["json","resumableQueryRows","send","WowHeaders","entityTag","eventNumbers","require_exactJson","require_http","require_streams","QueryModelClient","path","client","numbers","query","options","controller","row","resume","limit","open","received","lastEventId","first","response","version","tag","accept","queryPath","type","model","SnapshotQueryClient","EventQueryClient","events","DatasetClient","context","dataset"],"sources":["../src/queries.ts"],"sourcesContent":["/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type { AggregationQuery } from './dsl/aggregation/index.js';\nimport type { CursorPage, CursorQuery } from './dsl/cursorQuery.js';\nimport type { Projected } from './dsl/projection.js';\nimport { eventNumbers, type TextNumbers } from './exactJson.js';\nimport type { QueryModelDescriptor } from './dsl/descriptor.js';\nimport type { FilterCapable } from './dsl/filter/index.js';\nimport type {\n FilterListQuery,\n FilterPagedQuery,\n FilterSingleQuery,\n} from './dsl/queryable.js';\nimport {\n entityTag,\n json,\n type RequestOptions,\n send,\n type WowClientOptions,\n WowHeaders,\n} from './http.js';\nimport type {\n AggregateType,\n DatasetEntry,\n EventStreamField,\n EventStreamRecord,\n EventView,\n SnapshotRecord,\n SnapshotSystemField,\n} from './wire.js';\nimport {\n resumableQueryRows,\n type StreamedRow,\n type StreamResumeOptions,\n} from './streams.js';\n\n/** How a list is streamed: the request's options, and how it resumes. */\nexport interface ListStreamOptions extends RequestOptions {\n /** How the stream resumes (decision D253); `false` never resumes it. */\n readonly resume?: StreamResumeOptions | false;\n}\n\n/** How a paged query counts its total (`TotalMode`, decision D150). */\nexport type TotalMode = 'EXACT' | 'BOUNDED' | 'NONE';\n\n/** A paged query of a query route: a page, and how its total is counted. */\nexport interface PagedQuery<\n FIELDS extends string = string,\n> extends FilterPagedQuery<FIELDS> {\n /** `BOUNDED` (the server's default) counts up to the budget's limit. */\n total?: TotalMode;\n}\n\n/** A count of a query route (decision D150). */\nexport interface CountQuery<\n FIELDS extends string = string,\n> extends FilterCapable<FIELDS> {\n /** The most matches to count; the budget's default when absent. */\n limit?: number;\n}\n\n/** What a count answers: exact below its limit, else the limit itself. */\nexport interface CountResult {\n readonly count: number;\n readonly exact: boolean;\n}\n\n/**\n * A page of a paged query: `total` is exact when `exact`, a lower bound\n * otherwise, and null for `TotalMode.NONE`.\n */\nexport interface PagedResult<T> {\n readonly total: number | null;\n readonly exact: boolean;\n readonly list: readonly T[];\n}\n\n/**\n * A query model's capability descriptor and its version, the `ETag` of\n * `GET …/query`; `notModified` when the version given is still current.\n */\nexport type DescriptorResult =\n | {\n readonly notModified: false;\n readonly version?: string;\n readonly descriptor: QueryModelDescriptor;\n }\n | { readonly notModified: true; readonly version: string };\n\n/**\n * Queries one query model of a Wow service: `POST {path}` with a body\n * whose `kind` names the operation, `GET {path}` for the capability\n * descriptor (decisions D127, D145). A query written with literal `include`\n * paths answers records narrowed to them ({@link Projected}, review R4-Q,\n * Q-14).\n *\n * @typeParam R - The record's type.\n * @typeParam FIELDS - The field paths a filter, sort or projection takes.\n */\nexport class QueryModelClient<R, FIELDS extends string = string> {\n /**\n * @param path - The query route, `/{context}/{aggregate}/{model}/query`\n * @param client - How the service is reached\n * @param numbers - The numbers of each record read as their exact text\n * (review R4-Q, Q-9)\n */\n constructor(\n readonly path: string,\n readonly client: WowClientOptions = {},\n readonly numbers?: TextNumbers,\n ) {}\n\n /** The marks of a list of records. */\n private get listNumbers(): TextNumbers | undefined {\n return this.numbers === undefined ? undefined : { '*': this.numbers };\n }\n\n /** The marks of a page of records. */\n private get pageNumbers(): TextNumbers | undefined {\n return this.numbers === undefined\n ? undefined\n : { list: { '*': this.numbers } };\n }\n\n /** The records that match, at most `limit` (the server's default when absent). */\n list<const INCLUDE extends FIELDS>(\n query: Including<FilterListQuery<FIELDS>, INCLUDE>,\n options?: RequestOptions,\n ): Promise<Projected<R, INCLUDE>[]>;\n list(query: FilterListQuery<FIELDS>, options?: RequestOptions): Promise<R[]>;\n async list(\n query: FilterListQuery<FIELDS>,\n options?: RequestOptions,\n ): Promise<unknown> {\n return json<R[]>(await this.post('list', query, options), this.listNumbers);\n }\n\n /**\n * The records that match, as server-sent events read one at a time; a\n * failure after the first record errors the stream with its problem. The\n * stream resumes where it stopped (decision D253) when the server ends it\n * to be resumed, when it is cut off and when it fails with a retryable\n * problem: see {@link StreamResumeOptions}. A `limit` counts every record\n * read, resumed or not.\n */\n listStream<const INCLUDE extends FIELDS>(\n query: Including<FilterListQuery<FIELDS>, INCLUDE>,\n options?: ListStreamOptions,\n ): Promise<ReadableStream<Projected<R, INCLUDE>>>;\n listStream(\n query: FilterListQuery<FIELDS>,\n options?: ListStreamOptions,\n ): Promise<ReadableStream<R>>;\n async listStream(\n query: FilterListQuery<FIELDS>,\n options?: ListStreamOptions,\n ): Promise<unknown> {\n return (await this.listStreamRows(query, options)).pipeThrough(\n new TransformStream<StreamedRow<R>, R>({\n transform(row, controller) {\n controller.enqueue(row.record);\n },\n }),\n );\n }\n\n /**\n * The records that match as {@link listStream} reads them, each with its\n * position: keep the last one read to resume the stream later\n * ({@link StreamResumeOptions.lastEventId}), on another page or after a\n * restart.\n */\n listStreamRows<const INCLUDE extends FIELDS>(\n query: Including<FilterListQuery<FIELDS>, INCLUDE>,\n options?: ListStreamOptions,\n ): Promise<ReadableStream<StreamedRow<Projected<R, INCLUDE>>>>;\n listStreamRows(\n query: FilterListQuery<FIELDS>,\n options?: ListStreamOptions,\n ): Promise<ReadableStream<StreamedRow<R>>>;\n async listStreamRows(\n query: FilterListQuery<FIELDS>,\n options: ListStreamOptions = {},\n ): Promise<ReadableStream<StreamedRow<R>>> {\n const resume =\n options.resume === false ? { maxRetries: 0 } : options.resume;\n const limit = query.limit ?? 0;\n const open = (lastEventId: string | undefined, received: number) => {\n return this.post(\n 'list',\n limit > 0 ? { ...query, limit: limit - received } : query,\n options,\n 'text/event-stream',\n lastEventId,\n );\n };\n const first = await open(resume?.lastEventId, 0);\n return resumableQueryRows<R>(\n first,\n (lastEventId, received) =>\n limit > 0 && received >= limit\n ? Promise.resolve(undefined)\n : open(lastEventId, received),\n {\n ...resume,\n ...(options.signal === undefined ? {} : { signal: options.signal }),\n ...(this.numbers === undefined ? {} : { numbers: this.numbers }),\n },\n );\n }\n\n /** One page of the records that match, and their total. */\n paged<const INCLUDE extends FIELDS>(\n query: Including<PagedQuery<FIELDS>, INCLUDE>,\n options?: RequestOptions,\n ): Promise<PagedResult<Projected<R, INCLUDE>>>;\n paged(\n query: PagedQuery<FIELDS>,\n options?: RequestOptions,\n ): Promise<PagedResult<R>>;\n async paged(\n query: PagedQuery<FIELDS>,\n options?: RequestOptions,\n ): Promise<unknown> {\n return json<PagedResult<R>>(\n await this.post('paged', query, options),\n this.pageNumbers,\n );\n }\n\n /** One page of a forward-only cursor over the records that match. */\n cursor<const INCLUDE extends FIELDS>(\n query: Including<CursorQuery<FIELDS>, INCLUDE>,\n options?: RequestOptions,\n ): Promise<CursorPage<Projected<R, INCLUDE>>>;\n cursor(\n query: CursorQuery<FIELDS>,\n options?: RequestOptions,\n ): Promise<CursorPage<R>>;\n async cursor(\n query: CursorQuery<FIELDS>,\n options?: RequestOptions,\n ): Promise<unknown> {\n return json<CursorPage<R>>(\n await this.post('cursor', query, options),\n this.pageNumbers,\n );\n }\n\n /** The first record that matches; rejects with 404 `wow.query.not-found` when none does. */\n single<const INCLUDE extends FIELDS>(\n query: Including<FilterSingleQuery<FIELDS>, INCLUDE>,\n options?: RequestOptions,\n ): Promise<Projected<R, INCLUDE>>;\n single(\n query: FilterSingleQuery<FIELDS>,\n options?: RequestOptions,\n ): Promise<R>;\n async single(\n query: FilterSingleQuery<FIELDS>,\n options?: RequestOptions,\n ): Promise<unknown> {\n return json<R>(await this.post('single', query, options), this.numbers);\n }\n\n /** How many records match, bounded by the count's limit. */\n async count(\n query: CountQuery<FIELDS>,\n options?: RequestOptions,\n ): Promise<CountResult> {\n return json<CountResult>(await this.post('count', query, options));\n }\n\n /** The groups and metrics of an aggregation, one row per group. */\n async aggregate<ROW = Record<string, unknown>>(\n query: AggregationQuery<FIELDS, string>,\n options?: RequestOptions,\n ): Promise<ROW[]> {\n return json<ROW[]>(await this.post('aggregate', query, options));\n }\n\n /**\n * The model's capability descriptor; with the `version` already held, a\n * 304 answers `notModified`.\n */\n async describe(\n version?: string,\n options?: RequestOptions,\n ): Promise<DescriptorResult> {\n const response = await send(this.client, {\n method: 'GET',\n path: this.path,\n headers: {\n [WowHeaders.IF_NONE_MATCH]:\n version === undefined ? undefined : `\"${version}\"`,\n },\n options,\n notModified: true,\n });\n const tag = entityTag(response);\n if (response.status === 304) {\n return { notModified: true, version: tag ?? version ?? '' };\n }\n return {\n notModified: false,\n ...(tag === undefined ? {} : { version: tag }),\n descriptor: await json<QueryModelDescriptor>(response),\n };\n }\n\n private post(\n kind: string,\n query: object,\n options?: RequestOptions,\n accept?: string,\n lastEventId?: string,\n ): Promise<Response> {\n return send(this.client, {\n method: 'POST',\n path: this.path,\n headers: { Accept: accept, [WowHeaders.LAST_EVENT_ID]: lastEventId },\n body: { ...query, kind },\n options,\n });\n }\n}\n\n/**\n * A query whose projection includes the literal paths `INCLUDE`: a query\n * client narrows its records to them ({@link Projected}).\n */\nexport type Including<Q, INCLUDE extends string> = Q & {\n readonly projection: { readonly include: readonly INCLUDE[] };\n};\n\n/** The query route of a model of an aggregate type. */\nexport function queryPath(type: AggregateType, model: string): string {\n return `/${type.context}/${type.name}/${model}/query`;\n}\n\n/**\n * Queries an aggregate type's snapshots (decision D128), the default read\n * model; only where the aggregate keeps them.\n *\n * @typeParam S - The state's type.\n * @typeParam STATE_FIELDS - The `state.*` paths of the state.\n */\nexport class SnapshotQueryClient<\n S = unknown,\n STATE_FIELDS extends string = `state.${string}`,\n> extends QueryModelClient<\n SnapshotRecord<S>,\n SnapshotSystemField | STATE_FIELDS\n> {\n /**\n * @param type - The aggregate type\n * @param client - How the service is reached\n */\n constructor(\n readonly type: AggregateType,\n client?: WowClientOptions,\n ) {\n super(\n queryPath(type, 'snapshot'),\n client,\n type.textNumbers?.state === undefined\n ? undefined\n : { state: type.textNumbers.state },\n );\n }\n}\n\n/**\n * Queries an aggregate type's event streams (decision D235) on the same\n * engine as its snapshots: one record per commit, `count` counts commits, a\n * condition on an event is an `elementMatch` on `events`, and per-event\n * analytics expand `events` in an aggregation (`elements`). A filter need\n * not name the aggregate, but one that does not reads the log the service\n * appends to: the budget bounds it.\n *\n * @typeParam E - The events' type.\n */\nexport class EventQueryClient<\n E extends EventView = EventView,\n> extends QueryModelClient<EventStreamRecord<E>, EventStreamField> {\n /**\n * @param type - The aggregate type\n * @param client - How the service is reached\n */\n constructor(\n readonly type: AggregateType,\n client?: WowClientOptions,\n ) {\n const events = eventNumbers(type);\n super(\n queryPath(type, 'events'),\n client,\n events === undefined ? undefined : { events: { '*': events } },\n );\n }\n}\n\n/**\n * The datasets of a Wow service (decisions D75, D145): registered at run\n * time, so not in the Manifest. Lists those the caller sees and queries\n * each as a snapshot model is queried.\n */\nexport class DatasetClient {\n /** @param client - How the service is reached */\n constructor(readonly client: WowClientOptions = {}) {}\n\n /** The datasets the caller sees, by name. */\n async list(options?: RequestOptions): Promise<DatasetEntry[]> {\n return json<DatasetEntry[]>(\n await send(this.client, { method: 'GET', path: '/wow/dataset', options }),\n );\n }\n\n /**\n * The query client of the dataset `context.dataset`.\n *\n * @typeParam R - The row's type.\n * @typeParam FIELDS - The dataset's field paths.\n */\n dataset<R = Record<string, unknown>, FIELDS extends string = string>(\n context: string,\n dataset: string,\n ): QueryModelClient<R, FIELDS> {\n return new QueryModelClient<R, FIELDS>(\n `/wow/dataset/${encodeURIComponent(context)}/${encodeURIComponent(dataset)}/query`,\n this.client,\n );\n }\n}\n"],"mappings":"sFA8GA,IAAaS,EAAb,KAAiE,CAO/D,YACE,EACA,EAAoC,CAAC,EACrC,EACA,CAHS,KAAA,KAAAC,EACA,KAAA,OAAAC,EACA,KAAA,QAAAC,CACR,CAGH,IAAY,aAAuC,CACjD,OAAO,KAAK,UAAY,IAAA,GAAY,IAAA,GAAY,CAAE,IAAK,KAAK,OAAQ,CACtE,CAGA,IAAY,aAAuC,CACjD,OAAO,KAAK,UAAY,IAAA,GACpB,IAAA,GACA,CAAE,KAAM,CAAE,IAAK,KAAK,OAAQ,CAAE,CACpC,CAQA,MAAM,KACJ,EACA,EACkB,CAClB,OAAOZ,EAAAA,KAAU,MAAM,KAAK,KAAK,OAAQa,EAAOC,CAAO,EAAG,KAAK,WAAW,CAC5E,CAkBA,MAAM,WACJ,EACA,EACkB,CAClB,OAAQ,MAAM,KAAK,eAAeD,EAAOC,CAAO,EAAA,CAAG,YACjD,IAAI,gBAAmC,CACrC,UAAU,EAAK,EAAY,CACzBC,EAAW,QAAQC,EAAI,MAAM,CAC/B,CACF,CAAC,CACH,CACF,CAgBA,MAAM,eACJ,EACA,EAA6B,CAAC,EACW,CACzC,IAAMC,EACJH,EAAQ,SAAW,GAAQ,CAAE,WAAY,CAAE,EAAIA,EAAQ,OACnDI,EAAQL,EAAM,OAAS,EACvBM,GAAQ,EAAiC,IACtC,KA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Q,MAAO,KAAM,eAAgB,SAAQ,CAAC,CAC1E,CACF,CAQA,QACE,EACA,EAC6B,CAC7B,OAAO,IAAIO,EACT,gBAAgB,mBAAmByB,CAAO,EAAE,GAAG,mBAAmBC,CAAO,EAAE,QAC3E,KAAK,MACP,CACF,CACF"}
|
|
1
|
+
{"version":3,"file":"queries.cjs","names":["json","resumableQueryRows","send","WowHeaders","entityTag","WowProblemError","FrameworkErrorCodes","eventNumbers","require_exactJson","require_frameworkErrors","require_problem","require_http","require_streams","QueryModelClient","path","client","numbers","query","options","controller","positioned","resume","limit","open","received","lastEventId","first","error","isNoMatch","response","version","tag","accept","queryPath","type","model","SnapshotQueryClient","EventQueryClient","events","DatasetClient","context","dataset"],"sources":["../src/queries.ts"],"sourcesContent":["/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type { AggregationQuery } from './dsl/aggregation/index.js';\nimport type { CursorPage, CursorQuery } from './dsl/cursorQuery.js';\nimport type { Projected } from './dsl/projection.js';\nimport { eventNumbers, type TextNumbers } from './exactJson.js';\nimport type {\n DescriptorResult,\n QueryModelDescriptor,\n} from './dsl/descriptor.js';\nimport type { FilterCapable } from './dsl/filter/index.js';\nimport { FrameworkErrorCodes, WowProblemError } from './problem.js';\nimport type {\n FilterListQuery,\n FilterSingleQuery,\n PagedQuery,\n PagedList,\n} from './dsl/queryable.js';\nimport {\n entityTag,\n json,\n type RequestOptions,\n send,\n type WowClientOptions,\n WowHeaders,\n} from './http.js';\nimport type {\n AggregateType,\n DatasetEntry,\n EventStreamField,\n EventStream,\n CommittedEvent,\n Snapshot,\n SnapshotSystemField,\n} from './wire.js';\nimport {\n resumableQueryRows,\n type Positioned,\n type StreamResumeOptions,\n} from './streams.js';\n\n/** How a list is streamed: the request's options, and how it resumes. */\nexport interface StreamOptions extends RequestOptions {\n /** How the stream resumes (decision D253); `false` never resumes it. */\n readonly resume?: StreamResumeOptions | false;\n}\n\n/** A count of a query route. */\nexport interface CountQuery<\n FIELDS extends string = string,\n> extends FilterCapable<FIELDS> {\n /** The most matches to count; the budget's default when absent. */\n limit?: number;\n}\n\n/** What a count answers: exact below its limit, else the limit itself. */\nexport interface CountResult {\n readonly count: number;\n readonly exact: boolean;\n}\n\n/**\n * Queries one query model of a Wow service: `POST {path}` with a body\n * whose `kind` names the operation, `GET {path}` for the capability\n * descriptor. A query written with literal `include`\n * paths answers records narrowed to them ({@link Projected}, review R4-Q,\n * Q-14).\n *\n * @typeParam R - The record's type.\n * @typeParam FIELDS - The field paths a filter, sort or projection takes.\n */\nexport class QueryModelClient<R, FIELDS extends string = string> {\n /**\n * @param path - The query route, `/{context}/{aggregate}/{model}/query`\n * @param client - How the service is reached\n * @param numbers - The numbers of each record read as their exact text\n * (review R4-Q, Q-9)\n */\n constructor(\n readonly path: string,\n readonly client: WowClientOptions = {},\n readonly numbers?: TextNumbers,\n ) {}\n\n /** The marks of a list of records. */\n private get listNumbers(): TextNumbers | undefined {\n return this.numbers === undefined ? undefined : { '*': this.numbers };\n }\n\n /** The marks of a page of records. */\n private get pageNumbers(): TextNumbers | undefined {\n return this.numbers === undefined\n ? undefined\n : { list: { '*': this.numbers } };\n }\n\n /** The records that match, at most `limit` (the server's default when absent). */\n list<const INCLUDE extends FIELDS>(\n query: Including<FilterListQuery<FIELDS>, INCLUDE>,\n options?: RequestOptions,\n ): Promise<Projected<R, INCLUDE>[]>;\n list(query: FilterListQuery<FIELDS>, options?: RequestOptions): Promise<R[]>;\n async list(\n query: FilterListQuery<FIELDS>,\n options?: RequestOptions,\n ): Promise<unknown> {\n return json<R[]>(await this.post('list', query, options), this.listNumbers);\n }\n\n /**\n * The records that match, as server-sent events read one at a time; a\n * failure after the first record errors the stream with its problem. The\n * stream resumes where it stopped (decision D253) when the server ends it\n * to be resumed, when it is cut off and when it fails with a retryable\n * problem: see {@link StreamResumeOptions}. A `limit` counts every record\n * read, resumed or not.\n */\n stream<const INCLUDE extends FIELDS>(\n query: Including<FilterListQuery<FIELDS>, INCLUDE>,\n options?: StreamOptions,\n ): Promise<ReadableStream<Projected<R, INCLUDE>>>;\n stream(\n query: FilterListQuery<FIELDS>,\n options?: StreamOptions,\n ): Promise<ReadableStream<R>>;\n async stream(\n query: FilterListQuery<FIELDS>,\n options?: StreamOptions,\n ): Promise<unknown> {\n return (await this.streamRows(query, options)).pipeThrough(\n new TransformStream<Positioned<R>, R>({\n transform(positioned, controller) {\n controller.enqueue(positioned.row);\n },\n }),\n );\n }\n\n /**\n * The records that match as {@link stream} reads them, each with its\n * position: keep the last one read to resume the stream later\n * ({@link StreamResumeOptions.lastEventId}), on another page or after a\n * restart. Kotlin's `RowQueries.stream` answers these rows (`Positioned`).\n */\n streamRows<const INCLUDE extends FIELDS>(\n query: Including<FilterListQuery<FIELDS>, INCLUDE>,\n options?: StreamOptions,\n ): Promise<ReadableStream<Positioned<Projected<R, INCLUDE>>>>;\n streamRows(\n query: FilterListQuery<FIELDS>,\n options?: StreamOptions,\n ): Promise<ReadableStream<Positioned<R>>>;\n async streamRows(\n query: FilterListQuery<FIELDS>,\n options: StreamOptions = {},\n ): Promise<ReadableStream<Positioned<R>>> {\n const resume =\n options.resume === false ? { maxRetries: 0 } : options.resume;\n const limit = query.limit;\n const open = (lastEventId: string | undefined, received: number) => {\n return this.post(\n 'list',\n limit === undefined ? query : { ...query, limit: limit - received },\n options,\n 'text/event-stream',\n lastEventId,\n );\n };\n const first = await open(resume?.lastEventId, 0);\n return resumableQueryRows<R>(\n first,\n (lastEventId, received) =>\n limit !== undefined && received >= limit\n ? Promise.resolve(undefined)\n : open(lastEventId, received),\n {\n ...resume,\n ...(options.signal === undefined ? {} : { signal: options.signal }),\n ...(this.numbers === undefined ? {} : { numbers: this.numbers }),\n },\n );\n }\n\n /** One page of the records that match, and their total. */\n paged<const INCLUDE extends FIELDS>(\n query: Including<PagedQuery<FIELDS>, INCLUDE>,\n options?: RequestOptions,\n ): Promise<PagedList<Projected<R, INCLUDE>>>;\n paged(\n query: PagedQuery<FIELDS>,\n options?: RequestOptions,\n ): Promise<PagedList<R>>;\n async paged(\n query: PagedQuery<FIELDS>,\n options?: RequestOptions,\n ): Promise<unknown> {\n return json<PagedList<R>>(\n await this.post('paged', query, options),\n this.pageNumbers,\n );\n }\n\n /** One page of a forward-only cursor over the records that match. */\n cursor<const INCLUDE extends FIELDS>(\n query: Including<CursorQuery<FIELDS>, INCLUDE>,\n options?: RequestOptions,\n ): Promise<CursorPage<Projected<R, INCLUDE>>>;\n cursor(\n query: CursorQuery<FIELDS>,\n options?: RequestOptions,\n ): Promise<CursorPage<R>>;\n async cursor(\n query: CursorQuery<FIELDS>,\n options?: RequestOptions,\n ): Promise<unknown> {\n return json<CursorPage<R>>(\n await this.post('cursor', query, options),\n this.pageNumbers,\n );\n }\n\n /**\n * The first record that matches, or `undefined` when none does: the\n * service's 404 `wow.query.not-found`, as Kotlin's `QueryApi.single`\n * answers `null`. Any other 404, of a dataset or a route that does not\n * exist, still rejects.\n */\n single<const INCLUDE extends FIELDS>(\n query: Including<FilterSingleQuery<FIELDS>, INCLUDE>,\n options?: RequestOptions,\n ): Promise<Projected<R, INCLUDE> | undefined>;\n single(\n query: FilterSingleQuery<FIELDS>,\n options?: RequestOptions,\n ): Promise<R | undefined>;\n async single(\n query: FilterSingleQuery<FIELDS>,\n options?: RequestOptions,\n ): Promise<unknown> {\n try {\n return json<R>(await this.post('single', query, options), this.numbers);\n } catch (error) {\n if (isNoMatch(error)) return undefined;\n throw error;\n }\n }\n\n /** How many records match, bounded by the count's limit. */\n async count(\n query: CountQuery<FIELDS>,\n options?: RequestOptions,\n ): Promise<CountResult> {\n return json<CountResult>(await this.post('count', query, options));\n }\n\n /** The groups and metrics of an aggregation, one row per group. */\n async aggregate<ROW = Record<string, unknown>>(\n query: AggregationQuery<FIELDS, string>,\n options?: RequestOptions,\n ): Promise<ROW[]> {\n return json<ROW[]>(await this.post('aggregate', query, options));\n }\n\n /**\n * The model's capability descriptor; with the `version` already held, a\n * 304 answers `notModified`.\n */\n async describe(\n version?: string,\n options?: RequestOptions,\n ): Promise<DescriptorResult> {\n const response = await send(this.client, {\n method: 'GET',\n path: this.path,\n headers: {\n [WowHeaders.IF_NONE_MATCH]:\n version === undefined ? undefined : `\"${version}\"`,\n },\n options,\n notModified: true,\n });\n const tag = entityTag(response);\n if (response.status === 304) {\n return { notModified: true, version: tag ?? version ?? '' };\n }\n return {\n notModified: false,\n ...(tag === undefined ? {} : { version: tag }),\n descriptor: await json<QueryModelDescriptor>(response),\n };\n }\n\n private post(\n kind: string,\n query: object,\n options?: RequestOptions,\n accept?: string,\n lastEventId?: string,\n ): Promise<Response> {\n return send(this.client, {\n method: 'POST',\n path: this.path,\n headers: { Accept: accept, [WowHeaders.LAST_EVENT_ID]: lastEventId },\n body: { ...query, kind },\n options,\n });\n }\n}\n\n/**\n * Whether `error` is a 404 that answers \"no match\": a query that found no\n * record, or an aggregate that does not exist. A 404 of another code, or of\n * none (a route that does not exist), is a mistake the caller must hear of.\n */\nfunction isNoMatch(error: unknown): boolean {\n return (\n error instanceof WowProblemError &&\n error.status === 404 &&\n (error.code === FrameworkErrorCodes.QUERY_NOT_FOUND ||\n error.code === FrameworkErrorCodes.AGGREGATE_NOT_FOUND)\n );\n}\n\n/**\n * A query whose projection includes the literal paths `INCLUDE`: a query\n * client narrows its records to them ({@link Projected}).\n */\nexport type Including<Q, INCLUDE extends string> = Q & {\n readonly projection: { readonly include: readonly INCLUDE[] };\n};\n\n/** The query route of a model of an aggregate type. */\nexport function queryPath(type: AggregateType, model: string): string {\n return `/${type.context}/${type.name}/${model}/query`;\n}\n\n/**\n * Queries an aggregate type's snapshots, the default read\n * model; only where the aggregate keeps them.\n *\n * @typeParam S - The state's type.\n * @typeParam STATE_FIELDS - The `state.*` paths of the state.\n */\nexport class SnapshotQueryClient<\n S = unknown,\n STATE_FIELDS extends string = `state.${string}`,\n> extends QueryModelClient<Snapshot<S>, SnapshotSystemField | STATE_FIELDS> {\n /**\n * @param type - The aggregate type\n * @param client - How the service is reached\n */\n constructor(\n readonly type: AggregateType,\n client?: WowClientOptions,\n ) {\n super(\n queryPath(type, 'snapshot'),\n client,\n type.textNumbers?.state === undefined\n ? undefined\n : { state: type.textNumbers.state },\n );\n }\n}\n\n/**\n * Queries an aggregate type's event streams on the same\n * engine as its snapshots: one record per commit, `count` counts commits, a\n * condition on an event is an `elementMatch` on `events`, and per-event\n * analytics expand `events` in an aggregation (`elements`). A filter need\n * not name the aggregate, but one that does not reads the log the service\n * appends to: the budget bounds it.\n *\n * @typeParam E - The events' type.\n */\nexport class EventQueryClient<\n E extends CommittedEvent = CommittedEvent,\n> extends QueryModelClient<EventStream<E>, EventStreamField> {\n /**\n * @param type - The aggregate type\n * @param client - How the service is reached\n */\n constructor(\n readonly type: AggregateType,\n client?: WowClientOptions,\n ) {\n const events = eventNumbers(type);\n super(\n queryPath(type, 'events'),\n client,\n events === undefined ? undefined : { events: { '*': events } },\n );\n }\n}\n\n/**\n * The datasets of a Wow service: registered at run\n * time, so not in the Manifest. Lists those the caller sees and queries\n * each as a snapshot model is queried.\n */\nexport class DatasetClient {\n /** @param client - How the service is reached */\n constructor(readonly client: WowClientOptions = {}) {}\n\n /** The datasets the caller sees, by name. */\n async list(options?: RequestOptions): Promise<DatasetEntry[]> {\n return json<DatasetEntry[]>(\n await send(this.client, { method: 'GET', path: '/wow/dataset', options }),\n );\n }\n\n /**\n * The query client of the dataset `context.dataset`.\n *\n * @typeParam R - The row's type.\n * @typeParam FIELDS - The dataset's field paths.\n */\n dataset<R = Record<string, unknown>, FIELDS extends string = string>(\n context: string,\n dataset: string,\n ): QueryModelClient<R, FIELDS> {\n return new QueryModelClient<R, FIELDS>(\n `/wow/dataset/${encodeURIComponent(context)}/${encodeURIComponent(dataset)}/query`,\n this.client,\n );\n }\n}\n"],"mappings":"A,oJAkFA,IAAaa,EAAb,KAAiE,CAO/D,YACE,EACA,EAAoC,CAAC,EACrC,EACA,CAHS,KAAA,KAAAC,EACA,KAAA,OAAAC,EACA,KAAA,QAAAC,CACR,CAGH,IAAY,aAAuC,CACjD,OAAO,KAAK,UAAY,IAAA,GAAY,IAAA,GAAY,CAAE,IAAK,KAAK,OAAQ,CACtE,CAGA,IAAY,aAAuC,CACjD,OAAO,KAAK,UAAY,IAAA,GACpB,IAAA,GACA,CAAE,KAAM,CAAE,IAAK,KAAK,OAAQ,CAAE,CACpC,CAQA,MAAM,KACJ,EACA,EACkB,CAClB,OAAOhB,EAAAA,KAAU,MAAM,KAAK,KAAK,OAAQiB,EAAOC,CAAO,EAAG,KAAK,WAAW,CAC5E,CAkBA,MAAM,OACJ,EACA,EACkB,CAClB,OAAQ,MAAM,KAAK,WAAWD,EAAOC,CAAO,EAAA,CAAG,YAC7C,IAAI,gBAAkC,CACpC,UAAU,EAAY,EAAY,CAChCC,EAAW,QAAQC,EAAW,GAAG,CACnC,CACF,CAAC,CACH,CACF,CAgBA,MAAM,WACJ,EACA,EAAyB,CAAC,EACc,CACxC,IAAMC,EACJH,EAAQ,SAAW,GAAQ,CAAE,WAAY,CAAE,EAAIA,EAAQ,OACnDI,EAAQL,EAAM,MACdM,GAAQ,EAAiC,IACtC,KAAK,KACV,OACAD,IAAU,IAAA,GAAYL,EAAQ,CAAE,GAAGA,EAAO,MAAOK,EAAQE,CAAS,EAClEN,EACA,oBACAO,CACF,EAEIC,EAAQ,MAAMH,EAAKF,GAAQ,YAAa,CAAC,EAC/C,OAAOpB,EAAAA,mBACLyB,GACC,EAAa,IACZJ,IAAU,IAAA,IAAaE,GAAYF,EAC/B,QAAQ,QAAQ,IAAA,E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