@distilled.cloud/core 1.0.0-rc.2 → 1.0.0-rc.20
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/LICENSE +201 -0
- package/lib/_bundle/aws.js +2 -0
- package/lib/_bundle/aws.js.map +1 -0
- package/lib/_bundle/base.js +5 -0
- package/lib/_bundle/base.js.map +1 -0
- package/lib/_bundle/graphql.js +3 -0
- package/lib/_bundle/graphql.js.map +1 -0
- package/lib/_bundle/grpc.js +2 -0
- package/lib/_bundle/grpc.js.map +1 -0
- package/lib/_bundle/rest.js +2 -0
- package/lib/_bundle/rest.js.map +1 -0
- package/lib/_bundle/xml.js +4 -0
- package/lib/_bundle/xml.js.map +1 -0
- package/lib/annotations.d.ts +17 -0
- package/lib/annotations.d.ts.map +1 -0
- package/lib/annotations.js +2 -0
- package/lib/annotations.js.map +1 -0
- package/lib/api.d.ts +174 -18
- package/lib/api.d.ts.map +1 -1
- package/lib/api.js +1 -178
- package/lib/category.d.ts +4 -4
- package/lib/category.d.ts.map +1 -1
- package/lib/category.js +1 -280
- package/lib/chunks.d.ts +3 -0
- package/lib/chunks.d.ts.map +1 -0
- package/lib/chunks.js +1 -0
- package/lib/config.d.ts +68 -0
- package/lib/config.d.ts.map +1 -0
- package/lib/config.js +1 -0
- package/lib/crypto.d.ts +76 -0
- package/lib/crypto.d.ts.map +1 -0
- package/lib/crypto.js +1 -0
- package/lib/error-category.d.ts +1 -1
- package/lib/error-category.d.ts.map +1 -1
- package/lib/error-category.js +1 -46
- package/lib/errors.d.ts +64 -72
- package/lib/errors.d.ts.map +1 -1
- package/lib/errors.js +1 -186
- package/lib/graphql.d.ts +403 -0
- package/lib/graphql.d.ts.map +1 -0
- package/lib/graphql.js +1 -0
- package/lib/graphql.types.d.ts +12 -0
- package/lib/graphql.types.d.ts.map +1 -0
- package/lib/graphql.types.js +1 -0
- package/lib/grpc-transport-cloudflare-http2.d.ts +7 -0
- package/lib/grpc-transport-cloudflare-http2.d.ts.map +1 -0
- package/lib/grpc-transport-cloudflare-http2.js +6 -0
- package/lib/grpc-transport-cloudflare-http2.js.map +1 -0
- package/lib/grpc-transport-cloudflare-sockets.d.ts +7 -0
- package/lib/grpc-transport-cloudflare-sockets.d.ts.map +1 -0
- package/lib/grpc-transport-cloudflare-sockets.js +5 -0
- package/lib/grpc-transport-cloudflare-sockets.js.map +1 -0
- package/lib/grpc-transport-node-http2.d.ts +19 -0
- package/lib/grpc-transport-node-http2.d.ts.map +1 -0
- package/lib/grpc-transport-node-http2.js +2 -0
- package/lib/grpc-transport-node-http2.js.map +1 -0
- package/lib/grpc-transport.d.ts +76 -0
- package/lib/grpc-transport.d.ts.map +1 -0
- package/lib/grpc-transport.js +1 -0
- package/lib/hpack.d.ts +34 -0
- package/lib/hpack.d.ts.map +1 -0
- package/lib/hpack.js +2 -0
- package/lib/hpack.js.map +1 -0
- package/lib/index.d.ts +32 -0
- package/lib/index.d.ts.map +1 -0
- package/lib/index.js +17 -0
- package/lib/pagination.d.ts +101 -24
- package/lib/pagination.d.ts.map +1 -1
- package/lib/pagination.js +1 -182
- package/lib/plain-values.d.ts +10 -0
- package/lib/plain-values.d.ts.map +1 -0
- package/lib/plain-values.js +2 -0
- package/lib/plain-values.js.map +1 -0
- package/lib/protobuf.d.ts +92 -0
- package/lib/protobuf.d.ts.map +1 -0
- package/lib/protobuf.js +1 -0
- package/lib/protocol-grpc.d.ts +86 -0
- package/lib/protocol-grpc.d.ts.map +1 -0
- package/lib/protocol-grpc.js +1 -0
- package/lib/protocol-http.d.ts +102 -23
- package/lib/protocol-http.d.ts.map +1 -1
- package/lib/protocol-http.js +1 -554
- package/lib/protocol-rest.d.ts +120 -50
- package/lib/protocol-rest.d.ts.map +1 -1
- package/lib/protocol-rest.js +1 -242
- package/lib/query.d.ts +29 -0
- package/lib/query.d.ts.map +1 -0
- package/lib/query.js +1 -0
- package/lib/response-validation-strict.d.ts +48 -0
- package/lib/response-validation-strict.d.ts.map +1 -0
- package/lib/response-validation-strict.js +1 -0
- package/lib/response-validation.d.ts +86 -0
- package/lib/response-validation.d.ts.map +1 -0
- package/lib/response-validation.js +1 -0
- package/lib/retry-after.d.ts +3 -3
- package/lib/retry-after.d.ts.map +1 -1
- package/lib/retry-after.js +1 -112
- package/lib/retry.d.ts +48 -29
- package/lib/retry.d.ts.map +1 -1
- package/lib/retry.js +1 -210
- package/lib/schema-lite-impl.d.ts +158 -0
- package/lib/schema-lite-impl.d.ts.map +1 -0
- package/lib/schema-lite-impl.js +1 -0
- package/lib/schema-lite-typed.d.ts +41 -0
- package/lib/schema-lite-typed.d.ts.map +1 -0
- package/lib/schema-lite-typed.js +1 -0
- package/lib/schema-lite.d.ts +40 -0
- package/lib/schema-lite.d.ts.map +1 -0
- package/lib/schema-lite.js +1 -0
- package/lib/schema.d.ts +21 -7
- package/lib/schema.d.ts.map +1 -1
- package/lib/schema.js +1 -48
- package/lib/sdk-error.d.ts +27 -0
- package/lib/sdk-error.d.ts.map +1 -0
- package/lib/sdk-error.js +1 -0
- package/lib/sensitive.d.ts +28 -0
- package/lib/sensitive.d.ts.map +1 -0
- package/lib/sensitive.js +2 -0
- package/lib/sensitive.js.map +1 -0
- package/lib/telemetry-debug.d.ts +6 -0
- package/lib/telemetry-debug.d.ts.map +1 -0
- package/lib/telemetry-debug.js +2 -0
- package/lib/telemetry-debug.js.map +1 -0
- package/lib/telemetry-hooks.d.ts +32 -0
- package/lib/telemetry-hooks.d.ts.map +1 -0
- package/lib/telemetry-hooks.js +2 -0
- package/lib/telemetry-hooks.js.map +1 -0
- package/lib/telemetry-host-rules.d.ts +23 -0
- package/lib/telemetry-host-rules.d.ts.map +1 -0
- package/lib/telemetry-host-rules.js +2 -0
- package/lib/telemetry-host-rules.js.map +1 -0
- package/lib/telemetry-lambda-context.d.ts +17 -0
- package/lib/telemetry-lambda-context.d.ts.map +1 -0
- package/lib/telemetry-lambda-context.js +2 -0
- package/lib/telemetry-lambda-context.js.map +1 -0
- package/lib/telemetry-message-context.d.ts +52 -0
- package/lib/telemetry-message-context.d.ts.map +1 -0
- package/lib/telemetry-message-context.js +2 -0
- package/lib/telemetry-message-context.js.map +1 -0
- package/lib/telemetry-metrics.d.ts +6 -0
- package/lib/telemetry-metrics.d.ts.map +1 -0
- package/lib/telemetry-metrics.js +2 -0
- package/lib/telemetry-metrics.js.map +1 -0
- package/lib/telemetry-name-template.d.ts +13 -0
- package/lib/telemetry-name-template.d.ts.map +1 -0
- package/lib/telemetry-name-template.js +2 -0
- package/lib/telemetry-name-template.js.map +1 -0
- package/lib/telemetry-stream.d.ts +11 -0
- package/lib/telemetry-stream.d.ts.map +1 -0
- package/lib/telemetry-stream.js +2 -0
- package/lib/telemetry-stream.js.map +1 -0
- package/lib/telemetry-xray.d.ts +28 -0
- package/lib/telemetry-xray.d.ts.map +1 -0
- package/lib/telemetry-xray.js +2 -0
- package/lib/telemetry-xray.js.map +1 -0
- package/lib/telemetry.d.ts +288 -0
- package/lib/telemetry.d.ts.map +1 -0
- package/lib/telemetry.js +3 -0
- package/lib/telemetry.js.map +1 -0
- package/lib/trait.d.ts +71 -20
- package/lib/trait.d.ts.map +1 -1
- package/lib/trait.js +1 -107
- package/lib/unknown-error.d.ts +18 -0
- package/lib/unknown-error.d.ts.map +1 -0
- package/lib/unknown-error.js +1 -0
- package/lib/xml.d.ts +44 -0
- package/lib/xml.d.ts.map +1 -0
- package/lib/xml.js +1 -0
- package/package.json +13 -13
- package/src/annotations.ts +53 -0
- package/src/api.ts +1370 -200
- package/src/category.ts +76 -106
- package/src/chunks.ts +30 -0
- package/src/config.ts +245 -0
- package/src/crypto.ts +202 -0
- package/src/error-category.ts +16 -29
- package/src/errors.ts +75 -75
- package/src/graphql.ts +1778 -0
- package/src/graphql.types.ts +105 -0
- package/src/grpc-transport-cloudflare-http2.ts +494 -0
- package/src/grpc-transport-cloudflare-sockets.ts +299 -0
- package/src/grpc-transport-node-http2.ts +234 -0
- package/src/grpc-transport.ts +118 -0
- package/src/hpack.ts +331 -0
- package/src/index.ts +31 -0
- package/src/pagination.ts +368 -94
- package/src/plain-values.ts +41 -0
- package/src/protobuf.ts +1332 -0
- package/src/protocol-grpc.ts +641 -0
- package/src/protocol-http.ts +622 -322
- package/src/protocol-rest.ts +440 -227
- package/src/query.ts +39 -0
- package/src/response-validation-strict.ts +327 -0
- package/src/response-validation.ts +161 -0
- package/src/retry-after.ts +7 -13
- package/src/retry.ts +96 -110
- package/src/schema-lite-impl.ts +550 -0
- package/src/schema-lite-typed.ts +44 -0
- package/src/schema-lite.ts +44 -0
- package/src/schema.ts +259 -15
- package/src/sdk-error.ts +33 -0
- package/src/sensitive.ts +154 -0
- package/src/telemetry-debug.ts +179 -0
- package/src/telemetry-hooks.ts +33 -0
- package/src/telemetry-host-rules.ts +39 -0
- package/src/telemetry-lambda-context.ts +46 -0
- package/src/telemetry-message-context.ts +170 -0
- package/src/telemetry-metrics.ts +69 -0
- package/src/telemetry-name-template.ts +26 -0
- package/src/telemetry-stream.ts +100 -0
- package/src/telemetry-xray.ts +66 -0
- package/src/telemetry.ts +832 -0
- package/src/trait.ts +106 -67
- package/src/unknown-error.ts +38 -0
- package/src/xml.ts +346 -0
- package/lib/api.js.map +0 -1
- package/lib/category.js.map +0 -1
- package/lib/codegen/cli.d.ts +0 -29
- package/lib/codegen/cli.d.ts.map +0 -1
- package/lib/codegen/cli.js +0 -165
- package/lib/codegen/cli.js.map +0 -1
- package/lib/codegen/emit.d.ts +0 -129
- package/lib/codegen/emit.d.ts.map +0 -1
- package/lib/codegen/emit.js +0 -105
- package/lib/codegen/emit.js.map +0 -1
- package/lib/codegen/format.d.ts +0 -23
- package/lib/codegen/format.d.ts.map +0 -1
- package/lib/codegen/format.js +0 -28
- package/lib/codegen/format.js.map +0 -1
- package/lib/codegen/generator.d.ts +0 -334
- package/lib/codegen/generator.d.ts.map +0 -1
- package/lib/codegen/generator.js +0 -691
- package/lib/codegen/generator.js.map +0 -1
- package/lib/codegen/graph.d.ts +0 -36
- package/lib/codegen/graph.d.ts.map +0 -1
- package/lib/codegen/graph.js +0 -136
- package/lib/codegen/graph.js.map +0 -1
- package/lib/codegen/members.d.ts +0 -25
- package/lib/codegen/members.d.ts.map +0 -1
- package/lib/codegen/members.js +0 -55
- package/lib/codegen/members.js.map +0 -1
- package/lib/codegen/naming.d.ts +0 -29
- package/lib/codegen/naming.d.ts.map +0 -1
- package/lib/codegen/naming.js +0 -74
- package/lib/codegen/naming.js.map +0 -1
- package/lib/codegen/openapi-cli.d.ts +0 -38
- package/lib/codegen/openapi-cli.d.ts.map +0 -1
- package/lib/codegen/openapi-cli.js +0 -107
- package/lib/codegen/openapi-cli.js.map +0 -1
- package/lib/codegen/openapi.d.ts +0 -115
- package/lib/codegen/openapi.d.ts.map +0 -1
- package/lib/codegen/openapi.js +0 -1220
- package/lib/codegen/openapi.js.map +0 -1
- package/lib/codegen/operations.d.ts +0 -24
- package/lib/codegen/operations.d.ts.map +0 -1
- package/lib/codegen/operations.js +0 -56
- package/lib/codegen/operations.js.map +0 -1
- package/lib/codegen/pagination.d.ts +0 -39
- package/lib/codegen/pagination.d.ts.map +0 -1
- package/lib/codegen/pagination.js +0 -33
- package/lib/codegen/pagination.js.map +0 -1
- package/lib/codegen/prelude.d.ts +0 -15
- package/lib/codegen/prelude.d.ts.map +0 -1
- package/lib/codegen/prelude.js +0 -60
- package/lib/codegen/prelude.js.map +0 -1
- package/lib/error-category.js.map +0 -1
- package/lib/errors.js.map +0 -1
- package/lib/json-patch.d.ts +0 -44
- package/lib/json-patch.d.ts.map +0 -1
- package/lib/json-patch.js +0 -174
- package/lib/json-patch.js.map +0 -1
- package/lib/pagination.js.map +0 -1
- package/lib/protocol-http.js.map +0 -1
- package/lib/protocol-rest.js.map +0 -1
- package/lib/retry-after.js.map +0 -1
- package/lib/retry.js.map +0 -1
- package/lib/schema.js.map +0 -1
- package/lib/trait.js.map +0 -1
- package/src/codegen/cli.ts +0 -268
- package/src/codegen/emit.ts +0 -207
- package/src/codegen/format.ts +0 -47
- package/src/codegen/generator.ts +0 -1153
- package/src/codegen/graph.ts +0 -151
- package/src/codegen/members.ts +0 -71
- package/src/codegen/naming.ts +0 -86
- package/src/codegen/openapi-cli.ts +0 -166
- package/src/codegen/openapi.ts +0 -1450
- package/src/codegen/operations.ts +0 -76
- package/src/codegen/pagination.ts +0 -71
- package/src/codegen/prelude.ts +0 -70
- package/src/json-patch.ts +0 -222
package/src/api.ts
CHANGED
|
@@ -1,20 +1,33 @@
|
|
|
1
1
|
import * as Context from "effect/Context";
|
|
2
|
+
import type * as Duration from "effect/Duration";
|
|
2
3
|
import * as Effect from "effect/Effect";
|
|
4
|
+
import * as Exit from "effect/Exit";
|
|
5
|
+
import * as HttpClient from "effect/http/HttpClient";
|
|
6
|
+
import type * as HttpClientError from "effect/http/HttpClientError";
|
|
7
|
+
import type * as HttpClientRequest from "effect/http/HttpClientRequest";
|
|
8
|
+
import type * as HttpClientResponse from "effect/http/HttpClientResponse";
|
|
3
9
|
import * as Layer from "effect/Layer";
|
|
4
10
|
import * as Option from "effect/Option";
|
|
5
|
-
import * as S from "effect/Schema";
|
|
6
|
-
import type * as AST from "effect/SchemaAST";
|
|
7
11
|
import { pipeArguments } from "effect/Pipeable";
|
|
8
12
|
import * as Ref from "effect/Ref";
|
|
13
|
+
import * as S from "effect/Schema";
|
|
14
|
+
import type * as AST from "effect/SchemaAST";
|
|
9
15
|
import * as Scope from "effect/Scope";
|
|
10
|
-
import
|
|
16
|
+
import * as Stream from "effect/Stream";
|
|
11
17
|
import { SingleShotGen } from "effect/Utils";
|
|
18
|
+
import { getAnn, rawResponseRootSymbol } from "./annotations.ts";
|
|
19
|
+
import { isThrottling } from "./category.ts";
|
|
12
20
|
import * as Pagination from "./pagination.ts";
|
|
13
|
-
import {
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
21
|
+
import {
|
|
22
|
+
type Backoff,
|
|
23
|
+
defaultOptions,
|
|
24
|
+
type Options as RetryOptions,
|
|
25
|
+
type Policy as RetryPolicy,
|
|
26
|
+
resolveServerRetryHintCapMs,
|
|
27
|
+
serverHintMillis,
|
|
28
|
+
} from "./retry.ts";
|
|
29
|
+
import { SdkError } from "./sdk-error.ts";
|
|
30
|
+
import * as Telemetry from "./telemetry.ts";
|
|
18
31
|
|
|
19
32
|
//#region Protocol
|
|
20
33
|
|
|
@@ -51,34 +64,85 @@ export interface ProtocolOperationConfig {
|
|
|
51
64
|
*
|
|
52
65
|
* Swap implementations by providing a different `Layer<Protocol>`.
|
|
53
66
|
*/
|
|
54
|
-
export class Protocol
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
readonly
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
readonly
|
|
65
|
-
|
|
67
|
+
export class Protocol
|
|
68
|
+
extends /*@__PURE__*/ Context.Service<
|
|
69
|
+
Protocol,
|
|
70
|
+
{
|
|
71
|
+
readonly encode: (args: {
|
|
72
|
+
readonly input: unknown;
|
|
73
|
+
readonly inputAst: AST.AST;
|
|
74
|
+
/** The operation's config (memoized per operation -- see {@link ProtocolOperationConfig}). */
|
|
75
|
+
readonly config: ProtocolOperationConfig;
|
|
76
|
+
}) => Effect.Effect<HttpClientRequest.HttpClientRequest>;
|
|
77
|
+
readonly decode: (args: {
|
|
78
|
+
readonly response: HttpClientResponse.HttpClientResponse;
|
|
79
|
+
readonly outputAst: AST.AST;
|
|
80
|
+
/**
|
|
81
|
+
* The operation's declared error classes (from `OperationConfig.errors`).
|
|
82
|
+
* Protocols use these to surface wire failures as the operation's typed
|
|
83
|
+
* errors -- e.g. by consulting matcher metadata stamped on the class.
|
|
84
|
+
*/
|
|
85
|
+
readonly errors: ReadonlyArray<ApiErrorClass>;
|
|
86
|
+
/** The operation's config (memoized per operation -- see {@link ProtocolOperationConfig}). */
|
|
87
|
+
readonly config: ProtocolOperationConfig;
|
|
88
|
+
}) => Effect.Effect<unknown>;
|
|
66
89
|
/**
|
|
67
|
-
*
|
|
68
|
-
*
|
|
69
|
-
*
|
|
90
|
+
* Optional whole-call implementation. When present, `API.make` runs a
|
|
91
|
+
* call as `call(operation, input)` instead of encode -> HttpClient ->
|
|
92
|
+
* decode, so a protocol can read the context once, build the request
|
|
93
|
+
* synchronously and decode the response without intermediate effects.
|
|
94
|
+
* It must read the `HttpClient` from the calling fiber's context and
|
|
95
|
+
* produce the same request, result and errors as encode/decode.
|
|
70
96
|
*/
|
|
71
|
-
readonly
|
|
72
|
-
/**
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
97
|
+
readonly call?: (operation: PreparedOperation, input: unknown) => Effect.Effect<unknown>;
|
|
98
|
+
/**
|
|
99
|
+
* Server streaming (see {@link makeStreaming}): each response message
|
|
100
|
+
* as it arrives, decoded as one element of the output's `items`.
|
|
101
|
+
* Ending the stream early cancels the call. Protocols that can't
|
|
102
|
+
* stream leave it out.
|
|
103
|
+
*/
|
|
104
|
+
readonly stream?: (
|
|
105
|
+
operation: PreparedOperation,
|
|
106
|
+
input: unknown,
|
|
107
|
+
) => Stream.Stream<unknown, unknown>;
|
|
108
|
+
}
|
|
109
|
+
>()("Protocol") {}
|
|
110
|
+
|
|
111
|
+
/** The service a protocol layer provides. */
|
|
112
|
+
export type ProtocolShape = (typeof Protocol)["Service"];
|
|
113
|
+
|
|
114
|
+
/**
|
|
115
|
+
* One operation as a protocol's {@link Protocol.call} sees it. Built once per
|
|
116
|
+
* operation on its first call; the same object is passed on every call.
|
|
117
|
+
*/
|
|
118
|
+
export interface PreparedOperation {
|
|
119
|
+
readonly config: ProtocolOperationConfig;
|
|
120
|
+
readonly inputAst: AST.AST;
|
|
121
|
+
readonly outputAst: AST.AST;
|
|
122
|
+
readonly errors: ReadonlyArray<ApiErrorClass>;
|
|
123
|
+
/** Per-operation slot owned by the operation's protocol (compiled codecs). */
|
|
124
|
+
compiled?: unknown;
|
|
125
|
+
}
|
|
77
126
|
|
|
78
127
|
//#endregion
|
|
79
128
|
|
|
80
129
|
//#region Make
|
|
81
130
|
|
|
131
|
+
/**
|
|
132
|
+
* Run `f` on the value of `effect` -- directly when `effect` is already a
|
|
133
|
+
* successful `Exit` (e.g. a `Credentials` service holding
|
|
134
|
+
* `Effect.succeed(config)`), so a resolved value costs no fiber step.
|
|
135
|
+
*/
|
|
136
|
+
export const withValue = <A, B>(
|
|
137
|
+
effect: Effect.Effect<A, any, any>,
|
|
138
|
+
f: (a: A) => Effect.Effect<B, any, any>,
|
|
139
|
+
): Effect.Effect<B, any, any> =>
|
|
140
|
+
Exit.isExit(effect)
|
|
141
|
+
? Exit.isSuccess(effect)
|
|
142
|
+
? f(effect.value as A)
|
|
143
|
+
: (effect as unknown as Effect.Effect<never, any>)
|
|
144
|
+
: Effect.flatMap(effect, f);
|
|
145
|
+
|
|
82
146
|
export type ApiErrorClass = {
|
|
83
147
|
new (...args: any[]): {
|
|
84
148
|
readonly _tag: string;
|
|
@@ -87,11 +151,11 @@ export type ApiErrorClass = {
|
|
|
87
151
|
};
|
|
88
152
|
|
|
89
153
|
/**
|
|
90
|
-
* The shape of a generated SDK operation
|
|
154
|
+
* The shape of a generated SDK operation -- usable two ways (mirrors the
|
|
91
155
|
* distilled repo's OperationMethod):
|
|
92
156
|
*
|
|
93
|
-
* 1. Direct call: `yield* operation(input)`
|
|
94
|
-
* 2. Yield first: `const fn = yield* operation`
|
|
157
|
+
* 1. Direct call: `yield* operation(input)` -- an Effect with requirements.
|
|
158
|
+
* 2. Yield first: `const fn = yield* operation` -- captures the current
|
|
95
159
|
* context and returns a requirement-free call function.
|
|
96
160
|
*
|
|
97
161
|
* Generated service files annotate every exported operation with this type
|
|
@@ -103,11 +167,22 @@ export type OperationMethod<I, O, E, R> = Effect.Effect<
|
|
|
103
167
|
never,
|
|
104
168
|
R
|
|
105
169
|
> &
|
|
106
|
-
((input: I) => Effect.Effect<O, E, R>)
|
|
170
|
+
((input: I) => Effect.Effect<O, E, R>) &
|
|
171
|
+
OperationSchemas<I, O>;
|
|
172
|
+
|
|
173
|
+
/**
|
|
174
|
+
* An operation's request and response schemas, built on first access.
|
|
175
|
+
* Generated modules export operations, errors and types; the schemas
|
|
176
|
+
* themselves are module-private, so this is how to reach them as values.
|
|
177
|
+
*/
|
|
178
|
+
export interface OperationSchemas<I, O> {
|
|
179
|
+
readonly input: S.Codec<I, any>;
|
|
180
|
+
readonly output: S.Codec<O, any>;
|
|
181
|
+
}
|
|
107
182
|
|
|
108
183
|
// NOTE: request/response ASTs are handed to the protocol RAW (Suspend nodes
|
|
109
184
|
// included). Pre-resolving Suspends here would drop annotations that sit on
|
|
110
|
-
// intermediate nodes
|
|
185
|
+
// intermediate nodes -- e.g. a bare-payload response whose payload type is
|
|
111
186
|
// itself a suspended schema carries its EnvelopePayloadRoot marker on the
|
|
112
187
|
// inner Suspend, and unwrapping it silently degrades decode to the struct
|
|
113
188
|
// path. The protocol helpers (core/protocol-http getAnn/getProps) descend
|
|
@@ -116,19 +191,19 @@ export type OperationMethod<I, O, E, R> = Effect.Effect<
|
|
|
116
191
|
|
|
117
192
|
/**
|
|
118
193
|
* Protocol layers are built once per process and shared by every operation
|
|
119
|
-
* call (keyed by layer value identity
|
|
194
|
+
* call (keyed by layer value identity -- generated operations all reference the
|
|
120
195
|
* same module-level layer const). The build runs against a process-lifetime
|
|
121
196
|
* scope, and concurrent first calls are deduplicated through a private
|
|
122
197
|
* MemoMap.
|
|
123
198
|
*
|
|
124
199
|
* Contract for protocol implementations: the layer build must not capture
|
|
125
|
-
* per-call context. Anything call-dependent
|
|
126
|
-
* options
|
|
200
|
+
* per-call context. Anything call-dependent -- credentials, per-request
|
|
201
|
+
* options -- must be resolved inside `encode`/`decode`, which execute on the
|
|
127
202
|
* calling fiber and therefore see the caller's services on every request.
|
|
128
203
|
*/
|
|
129
|
-
const protocolMemoMap = Layer.makeMemoMapUnsafe();
|
|
130
|
-
const protocolScope = Scope.makeUnsafe();
|
|
131
|
-
const protocolContexts = new WeakMap<
|
|
204
|
+
const protocolMemoMap = /*@__PURE__*/ Layer.makeMemoMapUnsafe();
|
|
205
|
+
const protocolScope = /*@__PURE__*/ Scope.makeUnsafe();
|
|
206
|
+
const protocolContexts = /*@__PURE__*/ new WeakMap<
|
|
132
207
|
Layer.Layer<Protocol, any, any>,
|
|
133
208
|
Context.Context<Protocol>
|
|
134
209
|
>();
|
|
@@ -138,13 +213,10 @@ const protocolContext = <PE, PR>(
|
|
|
138
213
|
): Effect.Effect<Context.Context<Protocol>, PE, PR> => {
|
|
139
214
|
const cached = protocolContexts.get(layer);
|
|
140
215
|
if (cached) return Effect.succeed(cached);
|
|
141
|
-
return Effect.map(
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
return ctx;
|
|
146
|
-
},
|
|
147
|
-
);
|
|
216
|
+
return Effect.map(Layer.buildWithMemoMap(layer, protocolMemoMap, protocolScope), (ctx) => {
|
|
217
|
+
protocolContexts.set(layer, ctx);
|
|
218
|
+
return ctx;
|
|
219
|
+
});
|
|
148
220
|
};
|
|
149
221
|
|
|
150
222
|
export interface OperationConfig<
|
|
@@ -160,7 +232,7 @@ export interface OperationConfig<
|
|
|
160
232
|
/**
|
|
161
233
|
* The protocol layer that knows how to encode/decode this operation's wire
|
|
162
234
|
* format. Built once per process and shared across all operations that
|
|
163
|
-
* reference the same layer value
|
|
235
|
+
* reference the same layer value -- it must resolve call-dependent services
|
|
164
236
|
* (credentials etc.) inside encode/decode, not at build time.
|
|
165
237
|
*/
|
|
166
238
|
protocol: Layer.Layer<Protocol, PE, PR>;
|
|
@@ -180,37 +252,362 @@ export interface OperationConfig<
|
|
|
180
252
|
* {@link ProtocolOperationConfig.endpointHostPrefix}).
|
|
181
253
|
*/
|
|
182
254
|
endpointHostPrefix?: string;
|
|
255
|
+
/** The service's `com.distilled.telemetry#service` trait (a module const). */
|
|
256
|
+
telemetry?: Telemetry.ServiceTelemetry;
|
|
257
|
+
/**
|
|
258
|
+
* The operation's `com.distilled.telemetry#operation` trait, with its
|
|
259
|
+
* input rules; only what differs from the service's rules when it names
|
|
260
|
+
* its `op` (a string is just the op).
|
|
261
|
+
*/
|
|
262
|
+
span?: Telemetry.SpanConfig | string;
|
|
183
263
|
}
|
|
184
264
|
|
|
185
265
|
/**
|
|
186
266
|
* Wrap one operation call with the caller-provided retry policy, if the
|
|
187
267
|
* operation declares a retry tag and the context carries a policy for it.
|
|
188
268
|
*/
|
|
269
|
+
/** Delay before retry `attempt` (0-based) under `b`, in milliseconds. */
|
|
270
|
+
const backoffDelay = (b: Backoff, attempt: number, error: unknown): Effect.Effect<number> => {
|
|
271
|
+
const base = Math.min(b.baseMs * b.factor ** attempt, b.capMs);
|
|
272
|
+
const jitter = () => Math.random() * (b.jitterMs ?? 0);
|
|
273
|
+
if (b.serverHint && (error as { retryAfter?: unknown } | null)?.retryAfter !== undefined) {
|
|
274
|
+
return Effect.map(resolveServerRetryHintCapMs(), (capMs) => {
|
|
275
|
+
const hint = serverHintMillis(error, capMs);
|
|
276
|
+
return (hint ?? base) + jitter();
|
|
277
|
+
});
|
|
278
|
+
}
|
|
279
|
+
const floored =
|
|
280
|
+
b.minThrottleMs !== undefined && base < b.minThrottleMs && isThrottling(error)
|
|
281
|
+
? b.minThrottleMs
|
|
282
|
+
: base;
|
|
283
|
+
return Effect.succeed(floored + jitter());
|
|
284
|
+
};
|
|
285
|
+
|
|
286
|
+
const NO_BACKOFF: Backoff = { baseMs: 0, factor: 1, capMs: 0 };
|
|
287
|
+
|
|
288
|
+
/**
|
|
289
|
+
* BRAINSTORM: the sleep before retry `attempt` (1-based). The retry is
|
|
290
|
+
* recorded on the operation span; debug mode also makes the sleep a span.
|
|
291
|
+
*/
|
|
292
|
+
const backoffSleep = (
|
|
293
|
+
delay: Duration.Input,
|
|
294
|
+
attempt: number,
|
|
295
|
+
error: unknown,
|
|
296
|
+
): Effect.Effect<void> =>
|
|
297
|
+
Effect.withFiber((fiber) => {
|
|
298
|
+
const context = fiber.context as Context.Context<any>;
|
|
299
|
+
const delayMs = typeof delay === "number" ? delay : 0;
|
|
300
|
+
Telemetry.retried(context, attempt, error, delayMs);
|
|
301
|
+
return Telemetry.phase(context, "distilled.retry.backoff", Effect.sleep(delay), {
|
|
302
|
+
"distilled.retry.attempt": attempt,
|
|
303
|
+
"distilled.retry.delay_ms": Math.round(delayMs),
|
|
304
|
+
"distilled.retry.reason": (error as { _tag?: string } | null)?._tag,
|
|
305
|
+
});
|
|
306
|
+
});
|
|
307
|
+
|
|
308
|
+
/**
|
|
309
|
+
* Wrap one operation call with the caller-provided retry policy, if the
|
|
310
|
+
* operation declares a retry tag. The call runs once with no retry
|
|
311
|
+
* machinery; the policy is read only after a failure. Built-in policies are
|
|
312
|
+
* {@link Backoff} data run by a small loop; a caller-supplied `schedule`
|
|
313
|
+
* runs under `Effect.retry`, with the first failure replayed as attempt one
|
|
314
|
+
* so delays and counts match running the whole call under it.
|
|
315
|
+
*
|
|
316
|
+
* With `TelemetryDebug.layer`, every try runs as `Attempt` span n.
|
|
317
|
+
*/
|
|
189
318
|
const applyRetry = (
|
|
190
319
|
base: Effect.Effect<any, any, any>,
|
|
191
320
|
retryKey: Context.Key<any, RetryPolicy> | undefined,
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
...(opts.schedule ? { schedule: opts.schedule as any } : {}),
|
|
210
|
-
}),
|
|
321
|
+
debug: Telemetry.DebugHooks | undefined,
|
|
322
|
+
): Effect.Effect<any, any, any> => {
|
|
323
|
+
const first = debug === undefined ? base : debug.attempt(base, 1);
|
|
324
|
+
return retryKey === undefined
|
|
325
|
+
? first
|
|
326
|
+
: Effect.catch(first, (error) =>
|
|
327
|
+
Effect.flatMap(Effect.serviceOption(retryKey), (opt) => {
|
|
328
|
+
if (Option.isNone(opt)) return retryWith(base, defaultOptions, error, debug);
|
|
329
|
+
const policy = opt.value;
|
|
330
|
+
if (typeof policy !== "function") return retryWith(base, policy, error, debug);
|
|
331
|
+
return Effect.flatMap(Ref.make<unknown>(error), (lastError) =>
|
|
332
|
+
retryWith(
|
|
333
|
+
Effect.tapError(base, (e) => Ref.set(lastError, e)),
|
|
334
|
+
policy(lastError),
|
|
335
|
+
error,
|
|
336
|
+
debug,
|
|
337
|
+
),
|
|
211
338
|
);
|
|
212
339
|
}),
|
|
213
340
|
);
|
|
341
|
+
};
|
|
342
|
+
|
|
343
|
+
const retryWith = (
|
|
344
|
+
base: Effect.Effect<any, any, any>,
|
|
345
|
+
opts: RetryOptions,
|
|
346
|
+
error: unknown,
|
|
347
|
+
debug: Telemetry.DebugHooks | undefined,
|
|
348
|
+
): Effect.Effect<any, any, any> => {
|
|
349
|
+
const keepGoing = opts.while;
|
|
350
|
+
if (!keepGoing || !keepGoing(error)) return Effect.fail(error);
|
|
351
|
+
// Attempt n (2, 3, ...) of the call.
|
|
352
|
+
const again = (n: number) => (debug === undefined ? base : debug.attempt(base, n));
|
|
353
|
+
if (opts.schedule) {
|
|
354
|
+
// Drive the caller's schedule through its own `step`, as Effect.retry
|
|
355
|
+
// does, without importing the Schedule module into every bundle: the
|
|
356
|
+
// first failure is the schedule's first input; a step that fails means
|
|
357
|
+
// the schedule is done.
|
|
358
|
+
const schedule = opts.schedule as unknown as {
|
|
359
|
+
readonly step: Effect.Effect<
|
|
360
|
+
(now: number, input: unknown) => Effect.Effect<readonly [unknown, Duration.Input], unknown>
|
|
361
|
+
>;
|
|
362
|
+
};
|
|
363
|
+
return Effect.flatMap(schedule.step, (next) => {
|
|
364
|
+
let attempt = 0;
|
|
365
|
+
const loop = (e: unknown): Effect.Effect<any, any, any> =>
|
|
366
|
+
!keepGoing(e)
|
|
367
|
+
? Effect.fail(e)
|
|
368
|
+
: Effect.clockWith((clock) =>
|
|
369
|
+
Effect.matchEffect(next(clock.currentTimeMillisUnsafe(), e), {
|
|
370
|
+
onFailure: () => Effect.fail(e),
|
|
371
|
+
onSuccess: ([, delay]) =>
|
|
372
|
+
Effect.flatMap(backoffSleep(delay, ++attempt, e), () =>
|
|
373
|
+
Effect.catch(again(attempt + 1), loop),
|
|
374
|
+
),
|
|
375
|
+
}),
|
|
376
|
+
);
|
|
377
|
+
return loop(error);
|
|
378
|
+
});
|
|
379
|
+
}
|
|
380
|
+
const b = opts.backoff ?? NO_BACKOFF;
|
|
381
|
+
const step = (e: unknown, n: number): Effect.Effect<any, any, any> =>
|
|
382
|
+
!keepGoing(e) || (b.maxRetries !== undefined && n >= b.maxRetries)
|
|
383
|
+
? Effect.fail(e)
|
|
384
|
+
: Effect.flatMap(backoffDelay(b, n, e), (ms) =>
|
|
385
|
+
Effect.flatMap(backoffSleep(ms, n + 1, e), () =>
|
|
386
|
+
Effect.catch(again(n + 2), (next) => step(next, n + 1)),
|
|
387
|
+
),
|
|
388
|
+
);
|
|
389
|
+
return step(error, 0);
|
|
390
|
+
};
|
|
391
|
+
|
|
392
|
+
/**
|
|
393
|
+
* Per-operation state. Kept to one small object per exported operation:
|
|
394
|
+
* importing a service module creates every operation in it, so anything
|
|
395
|
+
* allocated here is paid hundreds of times per import (EC2 has 807
|
|
396
|
+
* operations) whether or not the operation is ever called.
|
|
397
|
+
*/
|
|
398
|
+
interface OperationState {
|
|
399
|
+
readonly configFn: () => OperationConfig<any, any, any, any, any>;
|
|
400
|
+
prepared?: Prepared;
|
|
401
|
+
/** Paginated operations only. */
|
|
402
|
+
readonly strategy?: Pagination.PaginationStrategy;
|
|
403
|
+
}
|
|
404
|
+
|
|
405
|
+
interface Prepared extends PreparedOperation {
|
|
406
|
+
readonly cfg: OperationConfig<any, any, any, any, any>;
|
|
407
|
+
/** The built protocol service, once its layer has been built. */
|
|
408
|
+
service?: ProtocolShape;
|
|
409
|
+
/** The operation span's facts, from the telemetry traits; built on the first traced call. */
|
|
410
|
+
info?: Telemetry.OperationInfo;
|
|
411
|
+
}
|
|
412
|
+
|
|
413
|
+
const infoOf = (p: Prepared): Telemetry.OperationInfo =>
|
|
414
|
+
(p.info ??= Telemetry.operationInfo(
|
|
415
|
+
p.cfg.telemetry,
|
|
416
|
+
p.cfg.span,
|
|
417
|
+
p.cfg.operationName,
|
|
418
|
+
p.inputAst,
|
|
419
|
+
));
|
|
420
|
+
|
|
421
|
+
const stateKey = /*@__PURE__*/ Symbol.for("@distilled.cloud/core/api/OperationState");
|
|
422
|
+
|
|
423
|
+
// Lazily resolve the operation config + schema ASTs on first call, not at
|
|
424
|
+
// module-load time. Generated SDKs wrap each request/response schema in
|
|
425
|
+
// `Schema.suspend(() => ...)`; forcing them here (rather than when the
|
|
426
|
+
// `export const` is evaluated) keeps importing a service module cheap and
|
|
427
|
+
// only pays the schema-construction cost for operations that are actually
|
|
428
|
+
// called. Memoized so subsequent calls are free.
|
|
429
|
+
const prepare = (state: OperationState): Prepared => {
|
|
430
|
+
if (state.prepared) return state.prepared;
|
|
431
|
+
const cfg = state.configFn();
|
|
432
|
+
return (state.prepared = {
|
|
433
|
+
cfg,
|
|
434
|
+
config: cfg,
|
|
435
|
+
inputAst: cfg.input!.ast,
|
|
436
|
+
outputAst: cfg.output!.ast,
|
|
437
|
+
errors: cfg.errors ?? [],
|
|
438
|
+
compiled: undefined,
|
|
439
|
+
service: undefined,
|
|
440
|
+
});
|
|
441
|
+
};
|
|
442
|
+
|
|
443
|
+
/**
|
|
444
|
+
* {@link prepare} for the call paths: a config that can't be built (a
|
|
445
|
+
* generated config that throws, a lazy service whose module doesn't match
|
|
446
|
+
* its stub) fails the call with {@link SdkError} instead of crashing it.
|
|
447
|
+
*/
|
|
448
|
+
const prepareOr = (state: OperationState): Prepared | SdkError => {
|
|
449
|
+
if (state.prepared) return state.prepared;
|
|
450
|
+
try {
|
|
451
|
+
return prepare(state);
|
|
452
|
+
} catch (cause) {
|
|
453
|
+
return new SdkError({
|
|
454
|
+
message: `the operation could not be loaded: ${cause instanceof Error ? cause.message : String(cause)}`,
|
|
455
|
+
});
|
|
456
|
+
}
|
|
457
|
+
};
|
|
458
|
+
|
|
459
|
+
const stateOf = (op: unknown): OperationState => (op as Record<symbol, OperationState>)[stateKey]!;
|
|
460
|
+
|
|
461
|
+
/**
|
|
462
|
+
* The span facts an operation's calls carry (name, kind, fixed attributes,
|
|
463
|
+
* input rules), as the runtime builds them from its generated config. For
|
|
464
|
+
* tests and tooling.
|
|
465
|
+
*/
|
|
466
|
+
export const describeOperation = (op: unknown): Telemetry.OperationInfo =>
|
|
467
|
+
infoOf(prepare(stateOf(op)));
|
|
468
|
+
|
|
469
|
+
const defineState = (op: unknown, state: OperationState): OperationState => {
|
|
470
|
+
Object.defineProperty(op, stateKey, { value: state });
|
|
471
|
+
return state;
|
|
472
|
+
};
|
|
473
|
+
|
|
474
|
+
const runWith = (
|
|
475
|
+
p: Prepared,
|
|
476
|
+
protocol: ProtocolShape,
|
|
477
|
+
input: unknown,
|
|
478
|
+
): Effect.Effect<any, any, any> => {
|
|
479
|
+
if (protocol.call !== undefined) return protocol.call(p, input);
|
|
480
|
+
const { cfg, inputAst, outputAst, errors } = p;
|
|
481
|
+
return Effect.withFiber((fiber) => {
|
|
482
|
+
const context = fiber.context as Context.Context<any>;
|
|
483
|
+
const client = Context.get(context, HttpClient.HttpClient);
|
|
484
|
+
return Effect.flatMap(protocol.encode({ input, inputAst, config: cfg }), (request) =>
|
|
485
|
+
Effect.flatMap(Telemetry.execute(context, client, request), (response) =>
|
|
486
|
+
protocol.decode({ response, outputAst, errors, config: cfg }),
|
|
487
|
+
),
|
|
488
|
+
);
|
|
489
|
+
});
|
|
490
|
+
};
|
|
491
|
+
|
|
492
|
+
const callUntraced = (
|
|
493
|
+
state: OperationState,
|
|
494
|
+
input: unknown,
|
|
495
|
+
debug: Telemetry.DebugHooks | undefined,
|
|
496
|
+
): Effect.Effect<any, any, any> => {
|
|
497
|
+
// Warm path: the operation is prepared and its protocol built, so the call
|
|
498
|
+
// is whatever the protocol returns, with no wrapper effects around it.
|
|
499
|
+
const p = state.prepared;
|
|
500
|
+
if (p?.service !== undefined) return applyRetry(runWith(p, p.service, input), p.cfg.retry, debug);
|
|
501
|
+
return Effect.suspend(() => {
|
|
502
|
+
const prepared = prepareOr(state);
|
|
503
|
+
if (prepared instanceof SdkError) return Effect.fail(prepared);
|
|
504
|
+
const call = Effect.flatMap(
|
|
505
|
+
debug === undefined
|
|
506
|
+
? protocolContext(prepared.cfg.protocol)
|
|
507
|
+
: debug.phase("distilled.setup", protocolContext(prepared.cfg.protocol), {
|
|
508
|
+
"distilled.setup.first_call": true,
|
|
509
|
+
}),
|
|
510
|
+
(protocolCtx) => {
|
|
511
|
+
const service = (prepared.service = Context.get(protocolCtx, Protocol));
|
|
512
|
+
return runWith(prepared, service, input);
|
|
513
|
+
},
|
|
514
|
+
);
|
|
515
|
+
return applyRetry(call, prepared.cfg.retry, debug);
|
|
516
|
+
});
|
|
517
|
+
};
|
|
518
|
+
|
|
519
|
+
/**
|
|
520
|
+
* BRAINSTORM: the call in its operation span (recorded only when an
|
|
521
|
+
* exporter is installed), whose stack frame is the caller (captured here,
|
|
522
|
+
* synchronously, while the caller is still on the JS stack).
|
|
523
|
+
*/
|
|
524
|
+
const callOperation = (
|
|
525
|
+
state: OperationState,
|
|
526
|
+
input: unknown,
|
|
527
|
+
entry: Function,
|
|
528
|
+
): Effect.Effect<any, any, any> => {
|
|
529
|
+
const callSite = Telemetry.captureCallSite(entry);
|
|
530
|
+
return Effect.withFiber((fiber) => {
|
|
531
|
+
const debug = fiber.getRef(Telemetry.Debug);
|
|
532
|
+
const prepared = prepareOr(state);
|
|
533
|
+
if (prepared instanceof SdkError) return Effect.fail(prepared);
|
|
534
|
+
return Telemetry.operationSpan(
|
|
535
|
+
fiber,
|
|
536
|
+
debug,
|
|
537
|
+
infoOf(prepared),
|
|
538
|
+
callSite,
|
|
539
|
+
input,
|
|
540
|
+
(sent) => callUntraced(state, sent, debug),
|
|
541
|
+
debug === undefined ? undefined : { input: prepared.inputAst, output: prepared.outputAst },
|
|
542
|
+
);
|
|
543
|
+
});
|
|
544
|
+
};
|
|
545
|
+
|
|
546
|
+
/**
|
|
547
|
+
* `const fn = yield* operation`: a requirement-free call function over the
|
|
548
|
+
* current context. The captured context is a FALLBACK, not a snapshot:
|
|
549
|
+
* entries present on the calling fiber at call time win, so per-call
|
|
550
|
+
* overrides -- e.g. providing `Endpoint` with a discovered data-plane address
|
|
551
|
+
* around one invocation -- take effect instead of being shadowed by the
|
|
552
|
+
* context captured at yield time.
|
|
553
|
+
*/
|
|
554
|
+
const bindContext = (op: (input: unknown) => Effect.Effect<any, any, any>) =>
|
|
555
|
+
Effect.map(
|
|
556
|
+
Effect.context(),
|
|
557
|
+
(context) => (input: unknown) =>
|
|
558
|
+
// `Context` is contravariant, so `Context<never>` is not assignable
|
|
559
|
+
// to the `Context<any>` updateContext expects -- the widening cast is
|
|
560
|
+
// sound (the merge only ever adds entries).
|
|
561
|
+
Effect.updateContext(op(input), (current): Context.Context<any> =>
|
|
562
|
+
Context.merge(context, current),
|
|
563
|
+
),
|
|
564
|
+
);
|
|
565
|
+
|
|
566
|
+
/**
|
|
567
|
+
* Shared by every operation function (its prototype; it inherits from
|
|
568
|
+
* `Function.prototype`, so operations stay ordinary callables). Makes the
|
|
569
|
+
* operation yieldable -- `yield* operation` returns a requirement-free call
|
|
570
|
+
* function, mirroring the distilled repo's OperationMethod -- and carries the
|
|
571
|
+
* debug/introspection surface (`op.input` / `.output` / `.errors` /
|
|
572
|
+
* `.operationName` / `.pagination`) as lazy getters, so importing a service
|
|
573
|
+
* module doesn't force its suspended schemas.
|
|
574
|
+
*/
|
|
575
|
+
const OperationProto: object = /*@__PURE__*/ Object.setPrototypeOf(
|
|
576
|
+
{
|
|
577
|
+
[Symbol.iterator](this: any) {
|
|
578
|
+
return new SingleShotGen(this.asEffect());
|
|
579
|
+
},
|
|
580
|
+
pipe(this: any) {
|
|
581
|
+
return pipeArguments(this.asEffect(), arguments);
|
|
582
|
+
},
|
|
583
|
+
asEffect(this: any) {
|
|
584
|
+
return bindContext(this);
|
|
585
|
+
},
|
|
586
|
+
get input() {
|
|
587
|
+
return prepare(stateOf(this)).cfg.input;
|
|
588
|
+
},
|
|
589
|
+
get output() {
|
|
590
|
+
return prepare(stateOf(this)).cfg.output;
|
|
591
|
+
},
|
|
592
|
+
get errors() {
|
|
593
|
+
return prepare(stateOf(this)).cfg.errors ?? [];
|
|
594
|
+
},
|
|
595
|
+
get operationName() {
|
|
596
|
+
return prepare(stateOf(this)).cfg.operationName;
|
|
597
|
+
},
|
|
598
|
+
get pagination() {
|
|
599
|
+
return (prepare(stateOf(this)).cfg as PaginatedOperationConfig<any, any, any, any>)
|
|
600
|
+
.pagination;
|
|
601
|
+
},
|
|
602
|
+
},
|
|
603
|
+
Function.prototype,
|
|
604
|
+
);
|
|
605
|
+
|
|
606
|
+
const makeOperation = (state: OperationState, proto: object): any => {
|
|
607
|
+
const fn = (input: unknown) => callOperation(state, input, fn);
|
|
608
|
+
defineState(fn, state);
|
|
609
|
+
return Object.setPrototypeOf(fn, proto);
|
|
610
|
+
};
|
|
214
611
|
|
|
215
612
|
export function make<
|
|
216
613
|
I extends S.Top,
|
|
@@ -226,95 +623,7 @@ export function make<
|
|
|
226
623
|
InstanceType<E[number]> | PE | HttpClientError.HttpClientError,
|
|
227
624
|
PR | HttpClient.HttpClient
|
|
228
625
|
> {
|
|
229
|
-
|
|
230
|
-
// module-load time. Generated SDKs wrap each request/response schema in
|
|
231
|
-
// `Schema.suspend(() => ...)`; forcing them here (rather than when the
|
|
232
|
-
// `export const` is evaluated) keeps importing a service module cheap and
|
|
233
|
-
// only pays the schema-construction cost for operations that are actually
|
|
234
|
-
// called. Memoized so subsequent calls are free.
|
|
235
|
-
interface Prepared {
|
|
236
|
-
readonly cfg: OperationConfig<I, O, PE, PR, E>;
|
|
237
|
-
readonly inputAst: AST.AST;
|
|
238
|
-
readonly outputAst: AST.AST;
|
|
239
|
-
}
|
|
240
|
-
let prepared: Prepared | undefined;
|
|
241
|
-
const prepare = (): Prepared => {
|
|
242
|
-
if (prepared) return prepared;
|
|
243
|
-
const cfg = configFn();
|
|
244
|
-
prepared = {
|
|
245
|
-
cfg,
|
|
246
|
-
inputAst: cfg.input!.ast,
|
|
247
|
-
outputAst: cfg.output!.ast,
|
|
248
|
-
};
|
|
249
|
-
return prepared;
|
|
250
|
-
};
|
|
251
|
-
const fn = (input: unknown) =>
|
|
252
|
-
Effect.suspend(() => {
|
|
253
|
-
const { cfg, inputAst, outputAst } = prepare();
|
|
254
|
-
const call = Effect.flatMap(
|
|
255
|
-
protocolContext(cfg.protocol),
|
|
256
|
-
(protocolCtx) =>
|
|
257
|
-
Effect.gen(function* () {
|
|
258
|
-
const protocol = yield* Protocol;
|
|
259
|
-
const client = yield* HttpClient.HttpClient;
|
|
260
|
-
const request = yield* protocol.encode({
|
|
261
|
-
input,
|
|
262
|
-
inputAst,
|
|
263
|
-
config: cfg,
|
|
264
|
-
});
|
|
265
|
-
const response = yield* client.execute(request);
|
|
266
|
-
return yield* protocol.decode({
|
|
267
|
-
response,
|
|
268
|
-
outputAst,
|
|
269
|
-
errors: cfg.errors ?? [],
|
|
270
|
-
config: cfg,
|
|
271
|
-
});
|
|
272
|
-
}).pipe(Effect.provideContext(protocolCtx)),
|
|
273
|
-
);
|
|
274
|
-
return applyRetry(call, cfg.retry);
|
|
275
|
-
});
|
|
276
|
-
|
|
277
|
-
// Make the operation itself yieldable: `yield* operation` captures the
|
|
278
|
-
// current context and returns a requirement-free call function (mirrors
|
|
279
|
-
// the distilled repo's OperationMethod).
|
|
280
|
-
const Proto = {
|
|
281
|
-
[Symbol.iterator](this: any) {
|
|
282
|
-
return new SingleShotGen(this.asEffect());
|
|
283
|
-
},
|
|
284
|
-
pipe(this: any) {
|
|
285
|
-
return pipeArguments(this.asEffect(), arguments);
|
|
286
|
-
},
|
|
287
|
-
asEffect() {
|
|
288
|
-
return Effect.map(
|
|
289
|
-
Effect.context(),
|
|
290
|
-
(context) => (input: unknown) =>
|
|
291
|
-
Effect.provideContext(fn(input), context),
|
|
292
|
-
);
|
|
293
|
-
},
|
|
294
|
-
};
|
|
295
|
-
Object.assign(fn, Proto);
|
|
296
|
-
|
|
297
|
-
// Debug/introspection surface carried over from the distilled client:
|
|
298
|
-
// the operation's metadata is readable off the exported callable
|
|
299
|
-
// (e.g. `iam.listRoles.input` / `.output` / `.errors` / `.operationName`
|
|
300
|
-
// / `.pagination`). Lazy getters, so importing a service module doesn't
|
|
301
|
-
// force its suspended schemas.
|
|
302
|
-
Object.defineProperties(fn, {
|
|
303
|
-
input: { get: () => prepare().cfg.input, configurable: true },
|
|
304
|
-
output: { get: () => prepare().cfg.output, configurable: true },
|
|
305
|
-
errors: { get: () => prepare().cfg.errors ?? [], configurable: true },
|
|
306
|
-
operationName: {
|
|
307
|
-
get: () => prepare().cfg.operationName,
|
|
308
|
-
configurable: true,
|
|
309
|
-
},
|
|
310
|
-
pagination: {
|
|
311
|
-
get: () =>
|
|
312
|
-
(prepare().cfg as PaginatedOperationConfig<I, O, PE, PR, E>).pagination,
|
|
313
|
-
configurable: true,
|
|
314
|
-
},
|
|
315
|
-
});
|
|
316
|
-
|
|
317
|
-
return fn as any;
|
|
626
|
+
return makeOperation({ configFn }, OperationProto);
|
|
318
627
|
}
|
|
319
628
|
|
|
320
629
|
//#endregion
|
|
@@ -326,7 +635,7 @@ export function make<
|
|
|
326
635
|
* element of the page response itself, or of its `result` member.
|
|
327
636
|
*
|
|
328
637
|
* It can only see shapes it was taught, so any other envelope
|
|
329
|
-
* (`{ branches: [
|
|
638
|
+
* (`{ branches: [...] }`, `{ data: [...] }`, ...) lands on `unknown` -- which is
|
|
330
639
|
* why generators pass the item type EXPLICITLY as
|
|
331
640
|
* {@link PaginatedOperationMethod}'s `Item` argument, resolved from the
|
|
332
641
|
* pagination trait's `items` path against the response shape. This default
|
|
@@ -346,7 +655,7 @@ export type PaginatedItem<A> =
|
|
|
346
655
|
* `.pages(input)` streaming every page response and `.items(input)` streaming
|
|
347
656
|
* the individual items across pages.
|
|
348
657
|
*
|
|
349
|
-
* Used twice in {@link PaginatedOperationMethod}
|
|
658
|
+
* Used twice in {@link PaginatedOperationMethod} -- once with the operation's
|
|
350
659
|
* requirements (`R`) for the direct-call style, once with `R = never` for the
|
|
351
660
|
* value `yield* operation` hands back, which has the caller's context baked in.
|
|
352
661
|
*/
|
|
@@ -358,18 +667,17 @@ export interface PaginatedCall<I, O, E, R, Item> {
|
|
|
358
667
|
|
|
359
668
|
/**
|
|
360
669
|
* A paginated operation: usable both ways an {@link OperationMethod} is, with
|
|
361
|
-
* `.pages` / `.items` on BOTH
|
|
670
|
+
* `.pages` / `.items` on BOTH -- the operation object for
|
|
362
671
|
* `yield* op.items(input)`, and the requirement-free call function for
|
|
363
672
|
* `const op = yield* operation; yield* op.items(input)` (distilled #145).
|
|
364
673
|
*/
|
|
365
|
-
export type PaginatedOperationMethod<
|
|
366
|
-
I,
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
Item
|
|
371
|
-
|
|
372
|
-
PaginatedCall<I, O, E, R, Item>;
|
|
674
|
+
export type PaginatedOperationMethod<I, O, E, R, Item = PaginatedItem<O>> = Effect.Effect<
|
|
675
|
+
PaginatedCall<I, O, E, never, Item>,
|
|
676
|
+
never,
|
|
677
|
+
R
|
|
678
|
+
> &
|
|
679
|
+
PaginatedCall<I, O, E, R, Item> &
|
|
680
|
+
OperationSchemas<I, O>;
|
|
373
681
|
|
|
374
682
|
export interface PaginatedOperationConfig<
|
|
375
683
|
I extends S.Top,
|
|
@@ -382,6 +690,65 @@ export interface PaginatedOperationConfig<
|
|
|
382
690
|
pagination: Pagination.PaginatedTrait;
|
|
383
691
|
}
|
|
384
692
|
|
|
693
|
+
/** `.pages` / `.items` over any call function (the operation itself or a context-bound one). */
|
|
694
|
+
const streamsOf = (state: OperationState, call: (input: any) => Effect.Effect<any, any, any>) => {
|
|
695
|
+
const pagesOf = (prepared: Prepared, input: Record<string, unknown>) => {
|
|
696
|
+
const cfg = prepared.cfg as PaginatedOperationConfig<any, any, any, any> & {
|
|
697
|
+
strategy?: Pagination.PaginationStrategy;
|
|
698
|
+
};
|
|
699
|
+
// Data operations carry their strategy in the config.
|
|
700
|
+
const paginate = state.strategy ?? cfg.strategy ?? Pagination.paginateWithDefaults;
|
|
701
|
+
return paginate(call, input, cfg.pagination);
|
|
702
|
+
};
|
|
703
|
+
const pages = (input: Record<string, unknown>): Stream.Stream<any, any, any> => {
|
|
704
|
+
const prepared = prepareOr(state);
|
|
705
|
+
return prepared instanceof SdkError ? Stream.fail(prepared) : pagesOf(prepared, input);
|
|
706
|
+
};
|
|
707
|
+
const items = (input: Record<string, unknown>): Stream.Stream<any, any, any> => {
|
|
708
|
+
const prepared = prepareOr(state);
|
|
709
|
+
if (prepared instanceof SdkError) return Stream.fail(prepared);
|
|
710
|
+
const p = (prepared.cfg as PaginatedOperationConfig<any, any, any, any>).pagination;
|
|
711
|
+
if (!p.items) return pagesOf(prepared, input);
|
|
712
|
+
// A bare-array response's schema is its sole member's value
|
|
713
|
+
// (`RawResponseRoot`), so the member `items` names is the page itself.
|
|
714
|
+
return getAnn(prepared.outputAst, rawResponseRootSymbol) !== undefined
|
|
715
|
+
? Pagination.extractArrayItems(pagesOf(prepared, input))
|
|
716
|
+
: Pagination.extractItems(pagesOf(prepared, input), p.items);
|
|
717
|
+
};
|
|
718
|
+
return { pages, items };
|
|
719
|
+
};
|
|
720
|
+
|
|
721
|
+
/**
|
|
722
|
+
* `.pages` / `.items` are getters that build the stream functions on first
|
|
723
|
+
* access and cache them on the operation, so they cost nothing until used
|
|
724
|
+
* and stay detachable (`const { items } = op` works).
|
|
725
|
+
*/
|
|
726
|
+
const streamGetter = (name: "pages" | "items") =>
|
|
727
|
+
function (this: any) {
|
|
728
|
+
const fns = streamsOf(stateOf(this), this);
|
|
729
|
+
Object.defineProperties(this, {
|
|
730
|
+
pages: { value: fns.pages, configurable: true },
|
|
731
|
+
items: { value: fns.items, configurable: true },
|
|
732
|
+
});
|
|
733
|
+
return fns[name];
|
|
734
|
+
};
|
|
735
|
+
|
|
736
|
+
const PaginatedOperationProto: object = /*@__PURE__*/ Object.create(OperationProto, {
|
|
737
|
+
pages: { get: /*@__PURE__*/ streamGetter("pages"), configurable: true },
|
|
738
|
+
items: { get: /*@__PURE__*/ streamGetter("items"), configurable: true },
|
|
739
|
+
// `yield* operation` returns a fresh context-bound function; give it
|
|
740
|
+
// `.pages` / `.items` too (distilled #145). Same fallback (not snapshot)
|
|
741
|
+
// semantics as the plain operation.
|
|
742
|
+
asEffect: {
|
|
743
|
+
value(this: any) {
|
|
744
|
+
const state = stateOf(this);
|
|
745
|
+
return Effect.map(bindContext(this), (call) => Object.assign(call, streamsOf(state, call)));
|
|
746
|
+
},
|
|
747
|
+
configurable: true,
|
|
748
|
+
writable: true,
|
|
749
|
+
},
|
|
750
|
+
});
|
|
751
|
+
|
|
385
752
|
/**
|
|
386
753
|
* Like {@link make}, plus `.pages()` / `.items()` streaming built on the
|
|
387
754
|
* operation's pagination trait. The SDK can pass a provider-specific
|
|
@@ -404,43 +771,846 @@ export function makePaginated<
|
|
|
404
771
|
InstanceType<E[number]> | PE | HttpClientError.HttpClientError,
|
|
405
772
|
PR | HttpClient.HttpClient
|
|
406
773
|
> {
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
774
|
+
return makeOperation(strategy ? { configFn, strategy } : { configFn }, PaginatedOperationProto);
|
|
775
|
+
}
|
|
776
|
+
|
|
777
|
+
//#endregion
|
|
778
|
+
|
|
779
|
+
//#region MakeStreaming
|
|
780
|
+
|
|
781
|
+
/** The message type of a server-streaming output, `{ items: Message[] }`. */
|
|
782
|
+
export type StreamedItem<O> = O extends { readonly items: ReadonlyArray<infer Item> }
|
|
783
|
+
? Item
|
|
784
|
+
: O extends { readonly items?: ReadonlyArray<infer Item> | undefined }
|
|
785
|
+
? Item
|
|
786
|
+
: unknown;
|
|
787
|
+
|
|
788
|
+
/**
|
|
789
|
+
* The callable half of a server-streaming operation: the call, which
|
|
790
|
+
* collects the whole stream into `{ items }`, plus `.stream(input)`, which
|
|
791
|
+
* emits each message as it arrives.
|
|
792
|
+
*/
|
|
793
|
+
export interface StreamingCall<I, O, E, R, Item> {
|
|
794
|
+
(input: I): Effect.Effect<O, E, R>;
|
|
795
|
+
readonly stream: (input: I) => Stream.Stream<Item, E, R>;
|
|
796
|
+
}
|
|
797
|
+
|
|
798
|
+
/**
|
|
799
|
+
* A server-streaming operation: usable both ways an {@link OperationMethod}
|
|
800
|
+
* is, with `.stream` on both the operation and the requirement-free call
|
|
801
|
+
* function `yield* operation` returns.
|
|
802
|
+
*/
|
|
803
|
+
export type StreamingOperationMethod<I, O, E, R, Item = StreamedItem<O>> = Effect.Effect<
|
|
804
|
+
StreamingCall<I, O, E, never, Item>,
|
|
805
|
+
never,
|
|
806
|
+
R
|
|
807
|
+
> &
|
|
808
|
+
StreamingCall<I, O, E, R, Item> &
|
|
809
|
+
OperationSchemas<I, O>;
|
|
810
|
+
|
|
811
|
+
/** `.stream(input)` over an operation's protocol. */
|
|
812
|
+
const streamCall =
|
|
813
|
+
(state: OperationState) =>
|
|
814
|
+
(input: unknown): Stream.Stream<any, any, any> =>
|
|
815
|
+
Stream.unwrap(
|
|
816
|
+
Effect.suspend(() => {
|
|
817
|
+
const prepared = prepareOr(state);
|
|
818
|
+
if (prepared instanceof SdkError) return Effect.succeed(Stream.fail(prepared));
|
|
819
|
+
const run = (service: ProtocolShape) =>
|
|
820
|
+
service.stream === undefined
|
|
821
|
+
? Stream.fail(
|
|
822
|
+
new SdkError({
|
|
823
|
+
message: `${prepared.cfg.operationName ?? "this operation"}: its protocol can't stream`,
|
|
824
|
+
}),
|
|
825
|
+
)
|
|
826
|
+
: service.stream(prepared, input);
|
|
827
|
+
return prepared.service !== undefined
|
|
828
|
+
? Effect.succeed(run(prepared.service))
|
|
829
|
+
: Effect.map(protocolContext(prepared.cfg.protocol), (ctx) =>
|
|
830
|
+
run((prepared.service = Context.get(ctx, Protocol))),
|
|
831
|
+
);
|
|
832
|
+
}),
|
|
833
|
+
);
|
|
834
|
+
|
|
835
|
+
const StreamingOperationProto: object = /*@__PURE__*/ Object.create(OperationProto, {
|
|
836
|
+
stream: {
|
|
837
|
+
get(this: any) {
|
|
838
|
+
const fn = streamCall(stateOf(this));
|
|
839
|
+
Object.defineProperty(this, "stream", { value: fn, configurable: true });
|
|
840
|
+
return fn;
|
|
841
|
+
},
|
|
842
|
+
configurable: true,
|
|
843
|
+
},
|
|
844
|
+
// `yield* operation` returns a context-bound call; its `.stream` gets the
|
|
845
|
+
// same fallback (not snapshot) context.
|
|
846
|
+
asEffect: {
|
|
847
|
+
value(this: any) {
|
|
848
|
+
const state = stateOf(this);
|
|
849
|
+
return Effect.map(Effect.context(), (context) => {
|
|
850
|
+
const merge = (current: Context.Context<any>): Context.Context<any> =>
|
|
851
|
+
Context.merge(context, current);
|
|
852
|
+
const call = (input: unknown) => Effect.updateContext(this(input), merge);
|
|
853
|
+
return Object.assign(call, {
|
|
854
|
+
stream: (input: unknown) => Stream.updateContext(streamCall(state)(input), merge),
|
|
855
|
+
});
|
|
856
|
+
});
|
|
857
|
+
},
|
|
858
|
+
configurable: true,
|
|
859
|
+
writable: true,
|
|
860
|
+
},
|
|
861
|
+
});
|
|
862
|
+
|
|
863
|
+
/**
|
|
864
|
+
* Like {@link make}, for a server-streaming RPC whose output is `{ items }`:
|
|
865
|
+
* calling it collects the stream, and `.stream(input)` emits each message as
|
|
866
|
+
* the protocol receives it (see {@link ProtocolShape.stream}).
|
|
867
|
+
*/
|
|
868
|
+
export function makeStreaming<
|
|
869
|
+
I extends S.Top,
|
|
870
|
+
O extends S.Top,
|
|
871
|
+
PE,
|
|
872
|
+
PR,
|
|
873
|
+
const E extends readonly ApiErrorClass[] = readonly [],
|
|
874
|
+
>(
|
|
875
|
+
configFn: () => OperationConfig<I, O, PE, PR, E>,
|
|
876
|
+
): StreamingOperationMethod<
|
|
877
|
+
S.Schema.Type<I>,
|
|
878
|
+
S.Schema.Type<O>,
|
|
879
|
+
InstanceType<E[number]> | PE | HttpClientError.HttpClientError,
|
|
880
|
+
PR | HttpClient.HttpClient
|
|
881
|
+
> {
|
|
882
|
+
return makeOperation({ configFn }, StreamingOperationProto);
|
|
883
|
+
}
|
|
884
|
+
|
|
885
|
+
//#endregion
|
|
886
|
+
|
|
887
|
+
//#region Data operations
|
|
888
|
+
|
|
889
|
+
/**
|
|
890
|
+
* Generated operations described by data instead of code.
|
|
891
|
+
*
|
|
892
|
+
* A service module holds each operation as one arrow that is both the
|
|
893
|
+
* callable operation and the holder of its description:
|
|
894
|
+
*
|
|
895
|
+
* export const getFile = API.op((i) => i === API.D ? ['{input:#1,...};__more', [__0, __4, ...]] : API.call(getFile, i));
|
|
896
|
+
*
|
|
897
|
+
* Called with {@link D}, it returns `[data, refs]`: `;`-separated entries
|
|
898
|
+
* in a small expression language (below) and the values they name. `refs[0]`
|
|
899
|
+
* is the schema-lite `at` (lazy schema wrapper). Schemas reached by more
|
|
900
|
+
* than one operation live in shared holders, `function __d3() { return
|
|
901
|
+
* [data, refs]; }`, named in `refs` so a bundler keeps only the holders an
|
|
902
|
+
* operation reaches. Entry 0 of an operation is its config; the rest are
|
|
903
|
+
* schemas and thunk bodies. Evaluating an entry calls the same
|
|
904
|
+
* constructors the code form called, in the same order, so the result is
|
|
905
|
+
* the same schema.
|
|
906
|
+
*
|
|
907
|
+
* Importing a module allocates one function per operation and one per
|
|
908
|
+
* holder; the data stays text in the module source until first use. A
|
|
909
|
+
* holder's refs may also be values built from module code on first use
|
|
910
|
+
* (service traits, endpoint rules), which its value entries name.
|
|
911
|
+
*
|
|
912
|
+
* Grammar (`;` never appears outside an entry separator; strings escape it):
|
|
913
|
+
*
|
|
914
|
+
* $N refs[N]
|
|
915
|
+
* #N #R:N schema entry N of this holder / of the holder refs[R] (lazy, memoized)
|
|
916
|
+
* ~N ~R:N value entry N of this holder / of refs[R] (a constant, evaluated once)
|
|
917
|
+
* >N thunk `() => entry N`
|
|
918
|
+
* "..." -1.5 true false null JSON literal u undefined
|
|
919
|
+
* {k:e,"k":e} object [e,e] array
|
|
920
|
+
* e(a,b) call e.name member e.name(a,b) method call e@"X" e.annotate({ identifier: "X" })
|
|
921
|
+
*/
|
|
922
|
+
export const D: unique symbol = /*@__PURE__*/ Symbol.for("@distilled.cloud/core/api/D") as any;
|
|
923
|
+
|
|
924
|
+
type DataFn = (i?: unknown) => any;
|
|
925
|
+
|
|
926
|
+
interface Source {
|
|
927
|
+
readonly fn: DataFn;
|
|
928
|
+
e?: string[];
|
|
929
|
+
r?: ReadonlyArray<any>;
|
|
930
|
+
b?: (j: number) => unknown;
|
|
931
|
+
readonly c: unknown[];
|
|
932
|
+
/** Data error classes: the built base class. */
|
|
933
|
+
k?: Function;
|
|
934
|
+
}
|
|
935
|
+
|
|
936
|
+
const sources = /*@__PURE__*/ new WeakMap<DataFn, Source>();
|
|
937
|
+
|
|
938
|
+
const sourceOf = (fn: DataFn): Source => {
|
|
939
|
+
let src = sources.get(fn);
|
|
940
|
+
if (!src) sources.set(fn, (src = { fn, c: [] }));
|
|
941
|
+
if (!src.e) {
|
|
942
|
+
// Called with itself as `this`: a lazy error placeholder finds its data by it.
|
|
943
|
+
const [s, r] = fn.call(fn, D);
|
|
944
|
+
src.e = s.split(";");
|
|
945
|
+
src.r = r;
|
|
946
|
+
}
|
|
947
|
+
return src;
|
|
948
|
+
};
|
|
949
|
+
|
|
950
|
+
/** Schema `j` of a holder, wrapped by `at` (lazy until first use). */
|
|
951
|
+
const schemaOf = (src: Source, j: number): unknown =>
|
|
952
|
+
(src.c[j] ??= src.r => evalEntry(src, k)), j));
|
|
953
|
+
|
|
954
|
+
/** A schema of a holder, for module-level code (error classes) that names one at import. */
|
|
955
|
+
export const schema = (fn: DataFn, j: number): any => schemaOf(sourceOf(fn), j);
|
|
956
|
+
|
|
957
|
+
const TOKEN = /"(?:[^"\\]|\\.)*"|[\w$.+-]*/y;
|
|
958
|
+
const NAME = /[\w$]*/y;
|
|
959
|
+
|
|
960
|
+
const evalEntry = (src: Source, j: number): any => {
|
|
961
|
+
const s = src.e![j]!;
|
|
962
|
+
const r = src.r!;
|
|
963
|
+
let p = 0;
|
|
964
|
+
const tok = (re = NAME): string => {
|
|
965
|
+
re.lastIndex = p;
|
|
966
|
+
const t = re.exec(s)![0];
|
|
967
|
+
p += t.length;
|
|
968
|
+
return t;
|
|
969
|
+
};
|
|
970
|
+
const list = (close: string): any[] => {
|
|
971
|
+
const a: any[] = [];
|
|
972
|
+
if (s[p] === close) p++;
|
|
973
|
+
else
|
|
974
|
+
do a.push(expr());
|
|
975
|
+
while (s[p++] !== close);
|
|
976
|
+
return a;
|
|
977
|
+
};
|
|
978
|
+
const expr = (): any => {
|
|
979
|
+
let v: any;
|
|
980
|
+
const c = s[p++]!;
|
|
981
|
+
if (c === "{") {
|
|
982
|
+
v = {};
|
|
983
|
+
if (s[p] === "}") p++;
|
|
984
|
+
else
|
|
985
|
+
do {
|
|
986
|
+
const k = tok(TOKEN);
|
|
987
|
+
p++;
|
|
988
|
+
v[k[0] === '"' ? JSON.parse(k) : k] = expr();
|
|
989
|
+
} while (s[p++] !== "}");
|
|
990
|
+
} else if (c === "[") v = list("]");
|
|
991
|
+
else if ("$#~>".includes(c)) {
|
|
992
|
+
let h = src;
|
|
993
|
+
let k = +tok();
|
|
994
|
+
if (s[p] === ":") {
|
|
995
|
+
p++;
|
|
996
|
+
h = sourceOf(r[k]);
|
|
997
|
+
k = +tok();
|
|
998
|
+
}
|
|
999
|
+
// A value entry is evaluated once, unwrapped.
|
|
1000
|
+
v =
|
|
1001
|
+
c === "$"
|
|
1002
|
+
? r[k]
|
|
1003
|
+
: c === ">"
|
|
1004
|
+
? () => evalEntry(src, k)
|
|
1005
|
+
: c === "#"
|
|
1006
|
+
? schemaOf(h, k)
|
|
1007
|
+
: (h.c[k] ??= evalEntry(h, k));
|
|
1008
|
+
} else {
|
|
1009
|
+
p--;
|
|
1010
|
+
const t = tok(TOKEN);
|
|
1011
|
+
v = t === "u" ? undefined : JSON.parse(t);
|
|
1012
|
+
}
|
|
1013
|
+
for (;;) {
|
|
1014
|
+
const d = s[p++];
|
|
1015
|
+
if (d === "(") v = v(...list(")"));
|
|
1016
|
+
else if (d === "@") v = v.annotate({ identifier: JSON.parse(tok(TOKEN)) });
|
|
1017
|
+
else if (d === ".") {
|
|
1018
|
+
const name = tok();
|
|
1019
|
+
v = s[p] === "(" ? (p++, v[name](...list(")"))) : v[name];
|
|
1020
|
+
} else return (p--, v);
|
|
1021
|
+
}
|
|
430
1022
|
};
|
|
1023
|
+
return expr();
|
|
1024
|
+
};
|
|
431
1025
|
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
1026
|
+
// A data operation gets its state on first use, from this inherited getter.
|
|
1027
|
+
// Its descriptors are written inline: nothing keeps them after the prototype is made.
|
|
1028
|
+
const dataState = function (this: DataFn): OperationState {
|
|
1029
|
+
return defineState(this, { configFn: () => evalEntry(sourceOf(this), 0) });
|
|
1030
|
+
};
|
|
1031
|
+
let dataProto: object | undefined;
|
|
1032
|
+
let dataPaginatedProto: object | undefined;
|
|
1033
|
+
let dataStreamingProto: object | undefined;
|
|
1034
|
+
/**
|
|
1035
|
+
* While a lazy service loads its full module (see {@link lazyService}), the module's
|
|
1036
|
+
* definitions go to it instead (kind 0 operation, 1 paginated, 2 error class,
|
|
1037
|
+
* 3 streaming).
|
|
1038
|
+
*/
|
|
1039
|
+
let definer: ((fn: DataFn, kind: 0 | 1 | 2 | 3) => unknown) | undefined;
|
|
1040
|
+
|
|
1041
|
+
/** Runs `f` with `d` receiving the definitions it evaluates. */
|
|
1042
|
+
const defining = (d: typeof definer, f: () => void): void => {
|
|
1043
|
+
const outer = definer;
|
|
1044
|
+
definer = d;
|
|
1045
|
+
try {
|
|
1046
|
+
f();
|
|
1047
|
+
} finally {
|
|
1048
|
+
definer = outer;
|
|
1049
|
+
}
|
|
1050
|
+
};
|
|
1051
|
+
|
|
1052
|
+
/**
|
|
1053
|
+
* The data of an operation whose name recurs in its strings: `%` in them
|
|
1054
|
+
* stands for `stem` (a literal `%` is escaped).
|
|
1055
|
+
*/
|
|
1056
|
+
export const named = (stem: string, data: string, refs: unknown): [string, unknown] => [
|
|
1057
|
+
data.replaceAll("%", stem),
|
|
1058
|
+
refs,
|
|
1059
|
+
];
|
|
1060
|
+
|
|
1061
|
+
const asOp = (fn: DataFn): any =>
|
|
1062
|
+
Object.setPrototypeOf(
|
|
1063
|
+
fn,
|
|
1064
|
+
(dataProto ??= Object.create(OperationProto, {
|
|
1065
|
+
[stateKey]: { get: dataState, configurable: true },
|
|
1066
|
+
})),
|
|
1067
|
+
);
|
|
1068
|
+
|
|
1069
|
+
const asOpPaginated = (fn: DataFn): any =>
|
|
1070
|
+
Object.setPrototypeOf(
|
|
1071
|
+
fn,
|
|
1072
|
+
(dataPaginatedProto ??= Object.create(PaginatedOperationProto, {
|
|
1073
|
+
[stateKey]: { get: dataState, configurable: true },
|
|
1074
|
+
})),
|
|
1075
|
+
);
|
|
1076
|
+
|
|
1077
|
+
const asOpStreaming = (fn: DataFn): any =>
|
|
1078
|
+
Object.setPrototypeOf(
|
|
1079
|
+
fn,
|
|
1080
|
+
(dataStreamingProto ??= Object.create(StreamingOperationProto, {
|
|
1081
|
+
[stateKey]: { get: dataState, configurable: true },
|
|
1082
|
+
})),
|
|
1083
|
+
);
|
|
1084
|
+
|
|
1085
|
+
/** An operation described by data (see the region header). */
|
|
1086
|
+
export const op = (fn: DataFn): any => (definer ? definer(fn, 0) : asOp(fn));
|
|
1087
|
+
|
|
1088
|
+
/** A paginated operation described by data; its config may name a `strategy`. */
|
|
1089
|
+
export const opPaginated = (fn: DataFn): any => (definer ? definer(fn, 1) : asOpPaginated(fn));
|
|
1090
|
+
|
|
1091
|
+
/** A server-streaming operation described by data. */
|
|
1092
|
+
export const opStreaming = (fn: DataFn): any => (definer ? definer(fn, 3) : asOpStreaming(fn));
|
|
1093
|
+
|
|
1094
|
+
/** The call path of a data operation. */
|
|
1095
|
+
export const call = (op: unknown, input: unknown): Effect.Effect<any, any, any> =>
|
|
1096
|
+
callOperation(stateOf(op), input, op as Function);
|
|
1097
|
+
|
|
1098
|
+
/**
|
|
1099
|
+
* Generated error classes described by data:
|
|
1100
|
+
*
|
|
1101
|
+
* export const Oops = API.error(function Oops(i) {
|
|
1102
|
+
* return API.newError(i, new.target, ['$1()("Oops",{...})', [...]]);
|
|
1103
|
+
* });
|
|
1104
|
+
*
|
|
1105
|
+
* The function is the class callers see: `new Oops(props)` constructs, a
|
|
1106
|
+
* plain call returns the data. Entry 0 of the data is the expression the
|
|
1107
|
+
* class extended (e.g. `S.TaggedError()(...).pipe(category)`). The first
|
|
1108
|
+
* `new`, or the first read of a static the function does not own (`ast`,
|
|
1109
|
+
* `fields`, `identifier`, error matchers, ...), builds that base class and
|
|
1110
|
+
* puts it underneath: the function's statics and prototype then inherit
|
|
1111
|
+
* from it as `class Oops extends Base {}` did, so `instanceof`, `_tag`,
|
|
1112
|
+
* categories and subclasses behave as before. Until then an error class
|
|
1113
|
+
* costs one function. The `in` operator sees only `Function` members until
|
|
1114
|
+
* the class is built.
|
|
1115
|
+
*/
|
|
1116
|
+
const errorBase = (f: any): Function | undefined => {
|
|
1117
|
+
// `f` may be a subclass: find the data class it extends.
|
|
1118
|
+
while (f && Object.getPrototypeOf(f) !== lazyErrorStatics && !sources.get(f)?.k)
|
|
1119
|
+
f = Object.getPrototypeOf(f);
|
|
1120
|
+
if (!f) return undefined;
|
|
1121
|
+
const src = sourceOf(f);
|
|
1122
|
+
if (!src.k) {
|
|
1123
|
+
const base = evalEntry(src, 0) as Function;
|
|
1124
|
+
src.k = base;
|
|
1125
|
+
Object.setPrototypeOf(f, base);
|
|
1126
|
+
Object.setPrototypeOf(f.prototype, base.prototype);
|
|
1127
|
+
}
|
|
1128
|
+
return src.k;
|
|
1129
|
+
};
|
|
1130
|
+
|
|
1131
|
+
// The statics of an unbuilt error class: `Function.prototype` members answer
|
|
1132
|
+
// directly; any other read builds the class, then reads again. Made on first
|
|
1133
|
+
// use, so bundles without data errors drop it.
|
|
1134
|
+
let lazyErrorStatics: object | undefined;
|
|
1135
|
+
const LazyErrorStatics = (): object =>
|
|
1136
|
+
(lazyErrorStatics ??= new Proxy(Object.create(Function.prototype), {
|
|
1137
|
+
get: (target, key, receiver) =>
|
|
1138
|
+
key in target || !errorBase(receiver)
|
|
1139
|
+
? Reflect.get(target, key, receiver)
|
|
1140
|
+
: Reflect.get(receiver, key, receiver),
|
|
1141
|
+
}));
|
|
1142
|
+
|
|
1143
|
+
const asError = (fn: DataFn): any => Object.setPrototypeOf(fn, LazyErrorStatics());
|
|
1144
|
+
|
|
1145
|
+
/** An error class described by data (see {@link errorBase}). */
|
|
1146
|
+
export const error = (fn: DataFn): any => (definer ? definer(fn, 2) : asError(fn));
|
|
1147
|
+
|
|
1148
|
+
/**
|
|
1149
|
+
* The body of a data error class: with `new`, an instance of the built
|
|
1150
|
+
* base whose prototype is `newTarget`'s; called plainly, the class's data.
|
|
1151
|
+
*/
|
|
1152
|
+
export const newError = (props: unknown, newTarget: Function | undefined, data: unknown): any =>
|
|
1153
|
+
newTarget ? Reflect.construct(errorBase(newTarget)!, [props], newTarget) : data;
|
|
1154
|
+
|
|
1155
|
+
//#endregion
|
|
1156
|
+
|
|
1157
|
+
//#region Lazy service modules
|
|
1158
|
+
|
|
1159
|
+
/**
|
|
1160
|
+
* A Node process that enables the `distilled-lazy` export condition loads a
|
|
1161
|
+
* service module as a stub (`lib/services.lazy/<name>.js`): one cheap
|
|
1162
|
+
* placeholder per operation and error class, no operation data. Its first use
|
|
1163
|
+
* loads the full module (`lib/services/<name>.js`, what every other condition
|
|
1164
|
+
* resolves) with `require(esm)`.
|
|
1165
|
+
*
|
|
1166
|
+
* const { o, e, E } = API.lazyService(import.meta.url, "../services/sqs.js", "oop", [$0], at, len);
|
|
1167
|
+
* export const { OverLimit, QueueDoesNotExist } = E; // or OverLimit = e("OverLimit"), ...
|
|
1168
|
+
* export const addPermission = o(), _1 = o(), listQueues = o();
|
|
1169
|
+
*
|
|
1170
|
+
* Generated stubs reach this through their package's `_bundle/lazy.js`,
|
|
1171
|
+
* which passes its own URL and the namespaces every stub imports.
|
|
1172
|
+
*
|
|
1173
|
+
* `kinds` has one letter per operation definition of the full module: `o`
|
|
1174
|
+
* plain, `p` paginated, `s` server-streaming. While the stub's load evaluates the full module,
|
|
1175
|
+
* `op` / `opPaginated` / `error` hand back the stub's placeholders in
|
|
1176
|
+
* definition order instead of new values, and each placeholder takes the
|
|
1177
|
+
* data function it stands for: the full module's operations, error lists
|
|
1178
|
+
* and exports are the very objects the stub exported.
|
|
1179
|
+
*
|
|
1180
|
+
* With a slice index (below), a placeholder's first use evaluates only what
|
|
1181
|
+
* its operation reaches instead of the whole full module. A full module that
|
|
1182
|
+
* was imported directly (lib code names services through the package, so
|
|
1183
|
+
* it resolves the stub too; only an import by file path does) keeps
|
|
1184
|
+
* its own objects, separate from the stub's.
|
|
1185
|
+
*/
|
|
1186
|
+
interface LazyService {
|
|
1187
|
+
readonly url: string;
|
|
1188
|
+
readonly spec: string;
|
|
1189
|
+
readonly kinds: string;
|
|
1190
|
+
/** Namespaces of the full module's imports, when it has a slice index. */
|
|
1191
|
+
readonly ns: readonly any[] | undefined;
|
|
1192
|
+
/** Byte range of the slice index, a comment at the end of the full module. */
|
|
1193
|
+
readonly at: number | undefined;
|
|
1194
|
+
readonly len: number | undefined;
|
|
1195
|
+
/** The slice index (see {@link sliced}); false: load the whole module. */
|
|
1196
|
+
ix?: SliceIndex | false;
|
|
1197
|
+
readonly o: any[];
|
|
1198
|
+
readonly e: any[];
|
|
1199
|
+
/** Data functions by placeholder, filled while the full module loads. */
|
|
1200
|
+
od?: DataFn[];
|
|
1201
|
+
ed?: DataFn[];
|
|
1202
|
+
oi: number;
|
|
1203
|
+
ei: number;
|
|
1204
|
+
}
|
|
1205
|
+
|
|
1206
|
+
/** The stub letter of each operation kind (see {@link lazyService}). */
|
|
1207
|
+
const KIND_LETTERS = ["o", "p", "", "s"] as const;
|
|
1208
|
+
|
|
1209
|
+
const define = (svc: LazyService, fn: DataFn, kind: 0 | 1 | 2 | 3): any => {
|
|
1210
|
+
if (kind === 2) {
|
|
1211
|
+
const i = svc.ei++;
|
|
1212
|
+
if (i >= svc.e.length) throw new Error(`distilled: ${svc.spec}: error ${i} has no stub`);
|
|
1213
|
+
svc.ed![i] = fn;
|
|
1214
|
+
return svc.e[i];
|
|
1215
|
+
}
|
|
1216
|
+
const i = svc.oi++;
|
|
1217
|
+
if (i >= svc.o.length || svc.kinds[i] !== KIND_LETTERS[kind])
|
|
1218
|
+
throw new Error(`distilled: ${svc.spec}: operation ${i} does not match its stub`);
|
|
1219
|
+
svc.od![i] = fn;
|
|
1220
|
+
return svc.o[i];
|
|
1221
|
+
};
|
|
1222
|
+
|
|
1223
|
+
const load = (svc: LazyService): void => {
|
|
1224
|
+
if (svc.od) return;
|
|
1225
|
+
svc.od = [];
|
|
1226
|
+
svc.ed = [];
|
|
1227
|
+
try {
|
|
1228
|
+
defining(
|
|
1229
|
+
(fn, kind) => define(svc, fn, kind),
|
|
1230
|
+
() =>
|
|
1231
|
+
(globalThis as any).process.getBuiltinModule("node:module").createRequire(svc.url)(
|
|
1232
|
+
svc.spec,
|
|
1233
|
+
),
|
|
1234
|
+
);
|
|
1235
|
+
} catch (e) {
|
|
1236
|
+
svc.od = svc.ed = undefined;
|
|
1237
|
+
svc.oi = svc.ei = 0;
|
|
1238
|
+
throw e;
|
|
1239
|
+
}
|
|
1240
|
+
if (svc.oi !== svc.o.length || svc.ei !== svc.e.length)
|
|
1241
|
+
throw new Error(
|
|
1242
|
+
`distilled: ${svc.spec} defined ${svc.oi} of ${svc.o.length} operations and ${svc.ei} of ${svc.e.length} errors (was it imported directly before?)`,
|
|
441
1243
|
);
|
|
1244
|
+
};
|
|
442
1245
|
|
|
443
|
-
|
|
1246
|
+
/**
|
|
1247
|
+
* Per-operation loading. bundle-lib ends a full module with a comment
|
|
1248
|
+
* holding its slice index (see scripts/lazy-services.ts): for every top-level
|
|
1249
|
+
* declaration, the byte range of its expression and the declarations it may
|
|
1250
|
+
* read. A placeholder's first use evaluates only its own data function and,
|
|
1251
|
+
* on demand, what that reaches -- one `Function` per declaration, the
|
|
1252
|
+
* module's imports and its dependencies passed in as parameters -- instead
|
|
1253
|
+
* of the whole module. Function declarations (the shared schema holders)
|
|
1254
|
+
* become forwarding functions compiled on their first call, so cycles
|
|
1255
|
+
* between them need no order. Without an index, or where code generation
|
|
1256
|
+
* from strings is disallowed, the whole module is loaded instead.
|
|
1257
|
+
*/
|
|
1258
|
+
interface SliceIndex {
|
|
1259
|
+
readonly file: string;
|
|
1260
|
+
/** Open while a burst of evaluations runs; closed in a microtask. */
|
|
1261
|
+
fd?: number;
|
|
1262
|
+
/** The index text, and where its sections start. */
|
|
1263
|
+
readonly raw: string;
|
|
1264
|
+
readonly imports: number;
|
|
1265
|
+
readonly importsAt: number;
|
|
1266
|
+
readonly tableAt: number;
|
|
1267
|
+
readonly linesAt: number;
|
|
1268
|
+
/** Split on first use. */
|
|
1269
|
+
specs?: string[];
|
|
1270
|
+
readonly importValues: unknown[];
|
|
1271
|
+
/** Values by declaration; `busy` marks one being evaluated. */
|
|
1272
|
+
readonly v: unknown[];
|
|
444
1273
|
}
|
|
445
1274
|
|
|
1275
|
+
const busy = {};
|
|
1276
|
+
|
|
1277
|
+
const node = (m: string): any => (globalThis as any).process?.getBuiltinModule?.(m);
|
|
1278
|
+
|
|
1279
|
+
/** Reads `length` bytes at `position` of the full module. */
|
|
1280
|
+
const read = (ix: { file: string; fd?: number }, position: number, length: number): string => {
|
|
1281
|
+
const fs = node("node:fs");
|
|
1282
|
+
if (ix.fd === undefined) {
|
|
1283
|
+
ix.fd = fs.openSync(ix.file, "r") as number;
|
|
1284
|
+
queueMicrotask(() => {
|
|
1285
|
+
fs.closeSync(ix.fd);
|
|
1286
|
+
ix.fd = undefined;
|
|
1287
|
+
});
|
|
1288
|
+
}
|
|
1289
|
+
const buf = (globalThis as any).Buffer.allocUnsafe(length);
|
|
1290
|
+
fs.readSync(ix.fd, buf, 0, length, position);
|
|
1291
|
+
return buf.toString("utf8", 0, length);
|
|
1292
|
+
};
|
|
1293
|
+
|
|
1294
|
+
const indexOf = (file: string, raw: string): SliceIndex => {
|
|
1295
|
+
const importsAt = raw.indexOf("\n") + 1;
|
|
1296
|
+
const tableAt = raw.indexOf("\n", importsAt) + 1;
|
|
1297
|
+
return {
|
|
1298
|
+
file,
|
|
1299
|
+
raw,
|
|
1300
|
+
imports: parseInt(raw),
|
|
1301
|
+
importsAt,
|
|
1302
|
+
tableAt,
|
|
1303
|
+
linesAt: raw.indexOf("\n", tableAt) + 1,
|
|
1304
|
+
importValues: [],
|
|
1305
|
+
v: [],
|
|
1306
|
+
};
|
|
1307
|
+
};
|
|
1308
|
+
|
|
1309
|
+
const fileOf = (svc: LazyService): string =>
|
|
1310
|
+
// A plain POSIX file URL is its path (URL parsing costs ~0.1 ms the first time).
|
|
1311
|
+
/^file:\/\/\/[^%?#]*$/.test(svc.url) && (globalThis as any).process.platform !== "win32"
|
|
1312
|
+
? svc.url.slice(7, svc.url.lastIndexOf("/") + 1) + svc.spec
|
|
1313
|
+
: node("node:url").fileURLToPath(new URL(svc.spec, svc.url));
|
|
1314
|
+
|
|
1315
|
+
const sliced = (svc: LazyService): SliceIndex | false => {
|
|
1316
|
+
if (svc.ix !== undefined) return svc.ix;
|
|
1317
|
+
svc.ix = false;
|
|
1318
|
+
if (svc.at === undefined || svc.od) return false;
|
|
1319
|
+
try {
|
|
1320
|
+
// oxlint-disable-next-line distilled/no-function-constructor -- probes whether the host allows it (a CSP may not)
|
|
1321
|
+
Function("");
|
|
1322
|
+
const file = fileOf(svc);
|
|
1323
|
+
svc.ix = indexOf(file, read({ file }, svc.at, svc.len!));
|
|
1324
|
+
svc.od = [];
|
|
1325
|
+
svc.ed = [];
|
|
1326
|
+
} catch {
|
|
1327
|
+
// Code from strings is blocked, or the slice can't be read: load the
|
|
1328
|
+
// whole module instead (`svc.ix` stays `false`).
|
|
1329
|
+
svc.ix = false;
|
|
1330
|
+
}
|
|
1331
|
+
return svc.ix;
|
|
1332
|
+
};
|
|
1333
|
+
|
|
1334
|
+
/**
|
|
1335
|
+
* The first lazy service of a process reads its slice index right after it
|
|
1336
|
+
* is imported (in a microtask, so before the import settles), instead of on
|
|
1337
|
+
* its first call: that read also pays Node's one-time costs of the slice path
|
|
1338
|
+
* (~0.2 ms). Later services read theirs on first use; nothing else is read
|
|
1339
|
+
* ahead, so importing a whole provider holds one index.
|
|
1340
|
+
*/
|
|
1341
|
+
let primed = false;
|
|
1342
|
+
const prime = (svc: LazyService): void => {
|
|
1343
|
+
primed = true;
|
|
1344
|
+
queueMicrotask(() => {
|
|
1345
|
+
const ix = sliced(svc);
|
|
1346
|
+
// The first read of an export through a module namespace is slow.
|
|
1347
|
+
if (ix && ix.imports > 0) importOf(svc, ix, 0);
|
|
1348
|
+
});
|
|
1349
|
+
};
|
|
1350
|
+
|
|
1351
|
+
/** The index line of declaration `k`. */
|
|
1352
|
+
const lineOf = (ix: SliceIndex, k: number): string => {
|
|
1353
|
+
const at = ix.tableAt + 5 * k;
|
|
1354
|
+
return ix.raw.slice(
|
|
1355
|
+
ix.linesAt + parseInt(ix.raw.slice(at, at + 5), 36),
|
|
1356
|
+
ix.linesAt + parseInt(ix.raw.slice(at + 5, at + 10), 36) - 1,
|
|
1357
|
+
);
|
|
1358
|
+
};
|
|
1359
|
+
|
|
1360
|
+
const nameOf = (ix: SliceIndex, k: number): string => lineOf(ix, k).split("|")[0]!.split(" ")[3]!;
|
|
1361
|
+
|
|
1362
|
+
const importSpec = (ix: SliceIndex, j: number): string[] =>
|
|
1363
|
+
(ix.specs ??= ix.raw.slice(ix.importsAt, ix.tableAt - 1).split(" "))[j]!.split(":");
|
|
1364
|
+
|
|
1365
|
+
const importOf = (svc: LazyService, ix: SliceIndex, j: number): unknown => {
|
|
1366
|
+
if (j in ix.importValues) return ix.importValues[j];
|
|
1367
|
+
const [, source, name] = importSpec(ix, j);
|
|
1368
|
+
return (ix.importValues[j] = svc.ns![+source!][name!]);
|
|
1369
|
+
};
|
|
1370
|
+
|
|
1371
|
+
/** A top-level name of the full module: imports first, then declarations. */
|
|
1372
|
+
const refOf = (svc: LazyService, ix: SliceIndex, j: number): unknown =>
|
|
1373
|
+
j < ix.imports ? importOf(svc, ix, j) : valueOf(svc, ix, j - ix.imports);
|
|
1374
|
+
|
|
1375
|
+
/**
|
|
1376
|
+
* Evaluates declaration `k` that is not a data function in its generated
|
|
1377
|
+
* shape: compiled with its dependencies in scope; a function with plain
|
|
1378
|
+
* parameters from its body, so it is parsed once, bound to those values.
|
|
1379
|
+
*/
|
|
1380
|
+
const evaluate = (svc: LazyService, ix: SliceIndex, k: number): any => {
|
|
1381
|
+
const [head, fn, depText] = lineOf(ix, k).split("|");
|
|
1382
|
+
const deps = depText ? depText.split(" ").map((x) => parseInt(x, 36)) : [];
|
|
1383
|
+
const names = deps.map((j) =>
|
|
1384
|
+
j < ix.imports ? importSpec(ix, j)[0]! : nameOf(ix, j - ix.imports),
|
|
1385
|
+
);
|
|
1386
|
+
const values = deps.map((j) => refOf(svc, ix, j));
|
|
1387
|
+
const url = `\n//# sourceURL=${ix.file}#${nameOf(ix, k)}`;
|
|
1388
|
+
if (fn && fn[0] !== "(") {
|
|
1389
|
+
const [params, range] = fn.split(";");
|
|
1390
|
+
const [start, end, expr] = range!.split(" ").map((x) => parseInt(x, 36));
|
|
1391
|
+
return compileBody(
|
|
1392
|
+
ix,
|
|
1393
|
+
names,
|
|
1394
|
+
values,
|
|
1395
|
+
params ? params.split(",") : [],
|
|
1396
|
+
start!,
|
|
1397
|
+
end!,
|
|
1398
|
+
expr!,
|
|
1399
|
+
url,
|
|
1400
|
+
);
|
|
1401
|
+
}
|
|
1402
|
+
const [, start, end] = head!.split(" ").map((x) => parseInt(x, 36));
|
|
1403
|
+
let text: string;
|
|
1404
|
+
if (fn?.[0] === "(") {
|
|
1405
|
+
// Functions it passes compile on their first call (many never are): it
|
|
1406
|
+
// reads the text around them only.
|
|
1407
|
+
const args = fn.slice(1).split(",");
|
|
1408
|
+
const outer = { names: names.slice(), values: values.slice() };
|
|
1409
|
+
text = "";
|
|
1410
|
+
let at = start!;
|
|
1411
|
+
args.forEach((arg, i) => {
|
|
1412
|
+
const [a, b, bs, be, expr] = arg.split(" ").map((x) => parseInt(x, 36));
|
|
1413
|
+
const params = arg.split(" ")[5];
|
|
1414
|
+
let compiled: Function | undefined;
|
|
1415
|
+
names.push(`$lazy${i}`);
|
|
1416
|
+
values.push(function (this: unknown) {
|
|
1417
|
+
compiled ??= compileBody(
|
|
1418
|
+
ix,
|
|
1419
|
+
outer.names,
|
|
1420
|
+
outer.values,
|
|
1421
|
+
params ? params.split("+") : [],
|
|
1422
|
+
bs!,
|
|
1423
|
+
be!,
|
|
1424
|
+
expr!,
|
|
1425
|
+
url,
|
|
1426
|
+
);
|
|
1427
|
+
return compiled.apply(this, arguments);
|
|
1428
|
+
});
|
|
1429
|
+
text += `${read(ix, at, a! - at)}$lazy${i}`;
|
|
1430
|
+
at = b!;
|
|
1431
|
+
});
|
|
1432
|
+
text += read(ix, at, end! - at);
|
|
1433
|
+
} else text = read(ix, start!, end! - start!);
|
|
1434
|
+
// oxlint-disable-next-line distilled/no-function-constructor -- the distilled-lazy loader compiles one declaration of a bundled service
|
|
1435
|
+
return Function(...names, `"use strict";return(${text}\n)${url}`)(...values);
|
|
1436
|
+
};
|
|
1437
|
+
|
|
1438
|
+
/**
|
|
1439
|
+
* A function with plain parameters, compiled from its body (parsed once)
|
|
1440
|
+
* with `names` in scope bound to `values`; its parameters shadow them.
|
|
1441
|
+
*/
|
|
1442
|
+
const compileBody = (
|
|
1443
|
+
ix: SliceIndex,
|
|
1444
|
+
names: string[],
|
|
1445
|
+
values: unknown[],
|
|
1446
|
+
own: string[],
|
|
1447
|
+
start: number,
|
|
1448
|
+
end: number,
|
|
1449
|
+
expr: number,
|
|
1450
|
+
url: string,
|
|
1451
|
+
): Function => {
|
|
1452
|
+
const text = read(ix, start, end - start);
|
|
1453
|
+
const keep = names.map((n) => !own.includes(n));
|
|
1454
|
+
// oxlint-disable-next-line distilled/no-function-constructor -- the distilled-lazy loader compiles one declaration of a bundled service
|
|
1455
|
+
return Function(
|
|
1456
|
+
...names.filter((_, i) => keep[i]),
|
|
1457
|
+
...own,
|
|
1458
|
+
// A block: the body's own declarations shadow the names in scope, as they did.
|
|
1459
|
+
`"use strict";${expr ? `return(${text}\n)` : `{${text}\n}`}${url}`,
|
|
1460
|
+
).bind(undefined, ...values.filter((_, i) => keep[i]));
|
|
1461
|
+
};
|
|
1462
|
+
|
|
1463
|
+
/**
|
|
1464
|
+
* The data function of a data line (`=stem;start end;refs`): reads the data
|
|
1465
|
+
* and resolves its refs, compiling nothing.
|
|
1466
|
+
*/
|
|
1467
|
+
const dataFn = (svc: LazyService, ix: SliceIndex, fn: string): [string, unknown[]] => {
|
|
1468
|
+
const [stem, range, refs] = fn.slice(1).split(";");
|
|
1469
|
+
const sp = range!.indexOf(" ");
|
|
1470
|
+
const start = parseInt(range!, 36);
|
|
1471
|
+
const data = read(ix, start, parseInt(range!.slice(sp + 1), 36) - start);
|
|
1472
|
+
const values: unknown[] = [];
|
|
1473
|
+
if (refs)
|
|
1474
|
+
for (const x of refs.split(",")) {
|
|
1475
|
+
const j = parseInt(x, 36);
|
|
1476
|
+
values.push(j < ix.imports ? importOf(svc, ix, j) : slot(svc, ix, j - ix.imports, false));
|
|
1477
|
+
}
|
|
1478
|
+
return [stem ? data.replaceAll("%", stem) : data, values];
|
|
1479
|
+
};
|
|
1480
|
+
|
|
1481
|
+
/**
|
|
1482
|
+
* The value declaration `k` of the full module has; with `own`, for an
|
|
1483
|
+
* operation or error class, its data function instead of its placeholder.
|
|
1484
|
+
*/
|
|
1485
|
+
const slot = (svc: LazyService, ix: SliceIndex, k: number, own: boolean): any => {
|
|
1486
|
+
if (!own) {
|
|
1487
|
+
if (k in ix.v) return ix.v[k] === busy ? undefined : ix.v[k];
|
|
1488
|
+
const ops = svc.o.length;
|
|
1489
|
+
if (k < ops) return (ix.v[k] = svc.o[k]);
|
|
1490
|
+
if (k < ops + svc.e.length) return (ix.v[k] = svc.e[k - ops]);
|
|
1491
|
+
}
|
|
1492
|
+
const at = ix.tableAt + 5 * k;
|
|
1493
|
+
const line = ix.raw.slice(
|
|
1494
|
+
ix.linesAt + parseInt(ix.raw.slice(at, at + 5), 36),
|
|
1495
|
+
ix.linesAt + parseInt(ix.raw.slice(at + 5, at + 10), 36) - 1,
|
|
1496
|
+
);
|
|
1497
|
+
const bar = line.indexOf("|");
|
|
1498
|
+
if (line[bar + 1] === "=") {
|
|
1499
|
+
const fn = dataFn.bind(undefined, svc, ix, line.slice(bar + 1)) as DataFn;
|
|
1500
|
+
return own ? fn : (ix.v[k] = fn);
|
|
1501
|
+
}
|
|
1502
|
+
if (own) return evaluate(svc, ix, k);
|
|
1503
|
+
if (line[0] === "1") {
|
|
1504
|
+
// A function declaration: compiled on its first call, so cycles need no order.
|
|
1505
|
+
let fn: Function | undefined;
|
|
1506
|
+
return (ix.v[k] = function (this: unknown) {
|
|
1507
|
+
return (fn ??= evaluate(svc, ix, k)).apply(this, arguments);
|
|
1508
|
+
});
|
|
1509
|
+
}
|
|
1510
|
+
ix.v[k] = busy;
|
|
1511
|
+
return (ix.v[k] = evaluate(svc, ix, k));
|
|
1512
|
+
};
|
|
1513
|
+
|
|
1514
|
+
const valueOf = (svc: LazyService, ix: SliceIndex, k: number): unknown => slot(svc, ix, k, false);
|
|
1515
|
+
|
|
1516
|
+
/** The data function of placeholder `i` (`kind` 0: operation, 1: error class). */
|
|
1517
|
+
const dataOf = (svc: LazyService, kind: 0 | 1, i: number): DataFn => {
|
|
1518
|
+
const loaded = kind === 0 ? svc.od : svc.ed;
|
|
1519
|
+
if (loaded?.[i]) return loaded[i]!;
|
|
1520
|
+
const ix = sliced(svc);
|
|
1521
|
+
if (!ix) {
|
|
1522
|
+
load(svc);
|
|
1523
|
+
return (kind === 0 ? svc.od : svc.ed)![i]!;
|
|
1524
|
+
}
|
|
1525
|
+
return ((kind === 0 ? svc.od : svc.ed)![i] = slot(
|
|
1526
|
+
svc,
|
|
1527
|
+
ix,
|
|
1528
|
+
kind === 0 ? i : svc.o.length + i,
|
|
1529
|
+
true,
|
|
1530
|
+
));
|
|
1531
|
+
};
|
|
1532
|
+
|
|
1533
|
+
/**
|
|
1534
|
+
* The placeholders of a lazy service module (see the region header): `o()`
|
|
1535
|
+
* and `e()` make the next operation / error class. A placeholder finds its
|
|
1536
|
+
* data by its index; it closes over nothing of its own, so it costs one
|
|
1537
|
+
* function.
|
|
1538
|
+
*/
|
|
1539
|
+
export const lazyService = (
|
|
1540
|
+
url: string,
|
|
1541
|
+
spec: string,
|
|
1542
|
+
kinds: string,
|
|
1543
|
+
ns?: readonly any[],
|
|
1544
|
+
at?: number,
|
|
1545
|
+
len?: number,
|
|
1546
|
+
): { readonly o: () => any; readonly e: (name: string) => any; readonly E: any } => {
|
|
1547
|
+
const svc: LazyService = { url, spec, kinds, ns, at, len, o: [], e: [], oi: 0, ei: 0 };
|
|
1548
|
+
if (!primed && at !== undefined) prime(svc);
|
|
1549
|
+
return {
|
|
1550
|
+
o: () => {
|
|
1551
|
+
const kind = kinds[svc.o.length];
|
|
1552
|
+
const f: DataFn = function op(x) {
|
|
1553
|
+
return x === D ? dataOf(svc, 0, svc.o.indexOf(op))(D) : call(op, x);
|
|
1554
|
+
};
|
|
1555
|
+
svc.o.push(kind === "p" ? asOpPaginated(f) : kind === "s" ? asOpStreaming(f) : asOp(f));
|
|
1556
|
+
return f;
|
|
1557
|
+
},
|
|
1558
|
+
e: (name: string) => {
|
|
1559
|
+
// A computed key names the function without a property of its own.
|
|
1560
|
+
const f = {
|
|
1561
|
+
[name]: function (this: unknown, x: unknown) {
|
|
1562
|
+
return new.target
|
|
1563
|
+
? newError(x, new.target, undefined)
|
|
1564
|
+
: dataOf(svc, 1, svc.e.indexOf(this))(x);
|
|
1565
|
+
},
|
|
1566
|
+
}[name]!;
|
|
1567
|
+
svc.e.push(asError(f));
|
|
1568
|
+
return f;
|
|
1569
|
+
},
|
|
1570
|
+
// Destructured once by the stub: each property read makes the error class of that name.
|
|
1571
|
+
get E() {
|
|
1572
|
+
const e = this.e;
|
|
1573
|
+
return new Proxy({}, { get: (_, name) => e(name as string) });
|
|
1574
|
+
},
|
|
1575
|
+
};
|
|
1576
|
+
};
|
|
1577
|
+
|
|
1578
|
+
/**
|
|
1579
|
+
* A service barrel's stand-in for `export * as sqs from "./sqs.js"` in Node:
|
|
1580
|
+
* a namespace whose module is loaded (`require(esm)`) on first access, so
|
|
1581
|
+
* importing a provider's barrel loads no service module. Reads, `in`,
|
|
1582
|
+
* `Object.keys` and spreading see the module's exports; it is read-only.
|
|
1583
|
+
*/
|
|
1584
|
+
interface LazyNamespace {
|
|
1585
|
+
readonly url: string;
|
|
1586
|
+
readonly spec: string;
|
|
1587
|
+
ns?: any;
|
|
1588
|
+
}
|
|
1589
|
+
|
|
1590
|
+
const namespaceOf = (t: LazyNamespace): any =>
|
|
1591
|
+
(t.ns ??= (globalThis as any).process.getBuiltinModule("node:module").createRequire(t.url)(
|
|
1592
|
+
t.spec,
|
|
1593
|
+
));
|
|
1594
|
+
|
|
1595
|
+
let lazyNamespaceHandler: ProxyHandler<LazyNamespace> | undefined;
|
|
1596
|
+
|
|
1597
|
+
export const lazyNamespace = (url: string, spec: string): any =>
|
|
1598
|
+
new Proxy<LazyNamespace>(
|
|
1599
|
+
{ url, spec },
|
|
1600
|
+
(lazyNamespaceHandler ??= {
|
|
1601
|
+
get: (t, k) => namespaceOf(t)[k],
|
|
1602
|
+
has: (t, k) => k in namespaceOf(t),
|
|
1603
|
+
ownKeys: (t) => Reflect.ownKeys(namespaceOf(t)),
|
|
1604
|
+
getOwnPropertyDescriptor: (t, k) => {
|
|
1605
|
+
const d = Reflect.getOwnPropertyDescriptor(namespaceOf(t), k);
|
|
1606
|
+
// The target does not hold these: a proxy may only report them configurable.
|
|
1607
|
+
return d && { ...d, configurable: true };
|
|
1608
|
+
},
|
|
1609
|
+
getPrototypeOf: () => null,
|
|
1610
|
+
set: () => false,
|
|
1611
|
+
defineProperty: () => false,
|
|
1612
|
+
deleteProperty: () => false,
|
|
1613
|
+
}),
|
|
1614
|
+
);
|
|
1615
|
+
|
|
446
1616
|
//#endregion
|