@workerstack/clients 1.0.0-rc.27 → 1.0.0-rc.29
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 +30 -7
- package/dist/emit/cli/commands.js +25 -5
- package/dist/emit/cli/flags.js +7 -3
- package/dist/emit/cli/skills.js +5 -1
- package/dist/emit/csharp/realtime.d.ts +1 -8
- package/dist/emit/csharp/realtime.js +25 -25
- package/dist/emit/csharp/sdk-answer.d.ts +10 -2
- package/dist/emit/csharp/sdk-method.js +9 -2
- package/dist/emit/csharp/sse.d.ts +0 -11
- package/dist/emit/csharp/sse.js +91 -10
- package/dist/emit/csharp/transport.js +3 -3
- package/dist/emit/csharp/types-messages.d.ts +47 -0
- package/dist/emit/csharp/types-messages.js +172 -0
- package/dist/emit/csharp/types-names.js +3 -2
- package/dist/emit/csharp/ws.d.ts +0 -15
- package/dist/emit/csharp/ws.js +26 -5
- package/dist/emit/go/sdk-answer.d.ts +24 -1
- package/dist/emit/go/sdk-method.d.ts +3 -0
- package/dist/emit/go/sdk-method.js +16 -10
- package/dist/emit/go/sse.d.ts +2 -10
- package/dist/emit/go/sse.js +87 -12
- package/dist/emit/go/types-union.d.ts +3 -2
- package/dist/emit/go/types-union.js +2 -0
- package/dist/emit/go/types.d.ts +6 -0
- package/dist/emit/go/types.js +12 -1
- package/dist/emit/go/ws.d.ts +4 -11
- package/dist/emit/go/ws.js +214 -58
- package/dist/emit/java/json.d.ts +3 -0
- package/dist/emit/java/layout-ast.d.ts +4 -1
- package/dist/emit/java/layout-types.js +1 -1
- package/dist/emit/java/models-names.d.ts +2 -0
- package/dist/emit/java/models-names.js +1 -0
- package/dist/emit/java/models-union.d.ts +12 -1
- package/dist/emit/java/models-union.js +11 -5
- package/dist/emit/java/models.d.ts +5 -0
- package/dist/emit/java/models.js +22 -7
- package/dist/emit/java/realtime.d.ts +29 -9
- package/dist/emit/java/realtime.js +45 -10
- package/dist/emit/java/sdk-mirror.js +6 -5
- package/dist/emit/java/sdk-op.js +1 -1
- package/dist/emit/java/sse.d.ts +11 -10
- package/dist/emit/java/sse.js +104 -5
- package/dist/emit/java/ws.d.ts +46 -7
- package/dist/emit/java/ws.js +89 -4
- package/dist/emit/mcp/output-schema.d.ts +4 -2
- package/dist/emit/mcp/output-schema.js +56 -12
- package/dist/emit/python/realtime.d.ts +9 -6
- package/dist/emit/python/realtime.js +21 -19
- package/dist/emit/python/sdk-answer.d.ts +5 -1
- package/dist/emit/python/sdk-method.d.ts +1 -1
- package/dist/emit/python/sdk-method.js +33 -6
- package/dist/emit/python/sdk.js +22 -2
- package/dist/emit/python/sse.d.ts +0 -5
- package/dist/emit/python/sse.js +35 -5
- package/dist/emit/python/types.d.ts +7 -0
- package/dist/emit/python/types.js +20 -3
- package/dist/emit/python/ws.d.ts +20 -6
- package/dist/emit/python/ws.js +67 -1
- package/dist/emit/rust/realtime.d.ts +7 -5
- package/dist/emit/rust/realtime.js +14 -17
- package/dist/emit/rust/sdk-method.js +1 -1
- package/dist/emit/rust/sse.d.ts +11 -7
- package/dist/emit/rust/sse.js +52 -6
- package/dist/emit/rust/types-union.d.ts +9 -1
- package/dist/emit/rust/types-union.js +4 -0
- package/dist/emit/rust/types.d.ts +9 -0
- package/dist/emit/rust/types.js +13 -7
- package/dist/emit/rust/ws.d.ts +22 -4
- package/dist/emit/rust/ws.js +57 -7
- package/dist/emit/ts/route-tree.d.ts +1 -1
- package/dist/emit/ts/route-tree.js +0 -11
- package/dist/emit/ts/sdk-types-preamble.js +4 -0
- package/dist/emit/ts/sdk-types.js +49 -10
- package/dist/emit/ts/sdk.js +2 -2
- package/dist/emit/ts/service-map.d.ts +8 -2
- package/dist/emit/ts/service-map.js +30 -2
- package/dist/emit/ts/type-gen.d.ts +4 -3
- package/dist/emit/ts/type-gen.js +83 -40
- package/dist/extract/chain.d.ts +10 -6
- package/dist/extract/chain.js +5 -19
- package/dist/extract/extract.d.ts +2 -2
- package/dist/extract/extract.js +37 -23
- package/dist/extract/walk.d.ts +15 -4
- package/dist/extract/walk.js +159 -15
- package/dist/ir/build.js +4 -0
- package/dist/ir/model.d.ts +16 -0
- package/dist/ir/sdk-model.d.ts +25 -1
- package/dist/ir/sdk-model.js +35 -5
- package/dist/ir/slots.d.ts +1 -1
- package/dist/ir/slots.js +11 -3
- package/dist/ir/streams.d.ts +16 -0
- package/dist/ir/streams.js +40 -0
- package/dist/runtime/cli/socket.go +107 -13
- package/dist/runtime/cli/stream.go +18 -11
- package/dist/runtime/csharp/Adapters.cs +12 -11
- package/dist/runtime/csharp/Events.cs +22 -17
- package/dist/runtime/csharp/Realtime.cs +50 -23
- package/dist/runtime/csharp/RealtimeLoop.cs +1 -1
- package/dist/runtime/csharp/TransportSse.cs +3 -3
- package/dist/runtime/csharp/Ws.cs +1 -1
- package/dist/runtime/csharp/WsDial.cs +19 -1
- package/dist/runtime/csharp/WsTyped.cs +109 -0
- package/dist/runtime/go/realtime.go +125 -41
- package/dist/runtime/go/realtime_loop.go +21 -18
- package/dist/runtime/go/result.go +2 -1
- package/dist/runtime/go/sse.go +11 -0
- package/dist/runtime/go/stream.go +29 -13
- package/dist/runtime/go/transport.go +15 -21
- package/dist/runtime/go/transport_longpoll.go +3 -4
- package/dist/runtime/go/transport_sse.go +6 -6
- package/dist/runtime/go/ws.go +157 -61
- package/dist/runtime/java/EventStream.java +47 -29
- package/dist/runtime/java/Exchange.java +5 -5
- package/dist/runtime/java/Flight.java +3 -3
- package/dist/runtime/java/Realtime.java +45 -11
- package/dist/runtime/java/ResumableConnection.java +77 -32
- package/dist/runtime/java/Socket.java +8 -4
- package/dist/runtime/java/SseAdapter.java +1 -1
- package/dist/runtime/java/TypedWebSocket.java +81 -24
- package/dist/runtime/java/WsAdapter.java +4 -2
- package/dist/runtime/java/WsDial.java +12 -5
- package/dist/runtime/python/events.py +25 -11
- package/dist/runtime/python/operation.py +6 -1
- package/dist/runtime/python/realtime.py +47 -33
- package/dist/runtime/python/send_async.py +1 -0
- package/dist/runtime/python/transport_sse.py +2 -2
- package/dist/runtime/python/transport_ws.py +1 -1
- package/dist/runtime/python/ws.py +100 -39
- package/dist/runtime/rust/events.rs +64 -41
- package/dist/runtime/rust/realtime.rs +80 -34
- package/dist/runtime/rust/realtime_loop.rs +37 -12
- package/dist/runtime/rust/sse.rs +3 -2
- package/dist/runtime/rust/transport_sse.rs +1 -1
- package/dist/runtime/rust/transport_ws.rs +3 -2
- package/dist/runtime/rust/ws.rs +122 -50
- package/dist/runtime/ts/realtime-connection.ts +22 -0
- package/dist/runtime/ts/realtime-transports.ts +13 -4
- package/dist/runtime/ts/realtime.ts +27 -3
- package/dist/runtime/ts/sdk-realtime.ts +1 -1
- package/dist/runtime/ts/sdk-sse.ts +31 -14
- package/dist/runtime/ts/sdk-ws.ts +2 -1
- package/dist/runtime/ts/sdk.ts +9 -2
- package/dist/runtime/ts/sse.ts +8 -0
- package/dist/runtime/ts/ws.ts +88 -50
- package/package.json +3 -61
package/dist/emit/rust/types.js
CHANGED
|
@@ -2,7 +2,7 @@ import { pascalWords, rustTypeIdent } from "../shared/lang.js";
|
|
|
2
2
|
import { integerValues, intEnumDecl, stringEnumDecl, stringValues } from "./types-enum.js";
|
|
3
3
|
import { irNames, plainNames } from "./types-names.js";
|
|
4
4
|
import { allOfDecl, DERIVE, objectDecl, unboxed } from "./types-struct.js";
|
|
5
|
-
import { unionDecl } from "./types-union.js";
|
|
5
|
+
import { unionDecl, unionVariants } from "./types-union.js";
|
|
6
6
|
const VALUE = "serde_json::Value";
|
|
7
7
|
const MAP = "std::collections::HashMap";
|
|
8
8
|
/* deeper than this, a schema is any JSON value */
|
|
@@ -19,7 +19,7 @@ export function rustTypeContext(ir) {
|
|
|
19
19
|
return { decls: new Map(), fieldName: "", names: ir ? irNames(ir) : plainNames(), parentName: "" };
|
|
20
20
|
}
|
|
21
21
|
/** `ir` declared once as `names.hoist(key, base)` into `at.decls`; its name. */
|
|
22
|
-
function
|
|
22
|
+
export function rustHoisted(ir, at, key, base) {
|
|
23
23
|
const name = at.names.hoist(key, base);
|
|
24
24
|
if (!at.decls.has(name)) {
|
|
25
25
|
/* claimed before its body: what the body hoists in turn comes after it */
|
|
@@ -29,7 +29,7 @@ function declare(ir, at, key, base) {
|
|
|
29
29
|
return name;
|
|
30
30
|
}
|
|
31
31
|
/** `ir` hoisted as `<Parent><Field>`. */
|
|
32
|
-
const hoist = (ir, at) =>
|
|
32
|
+
const hoist = (ir, at) => rustHoisted(ir, at, `${at.parentName}.${at.fieldName}`, `${rustTypeIdent(at.parentName)}${pascalWords(at.fieldName)}`);
|
|
33
33
|
const deeper = (at, fieldName = at.fieldName) => ({ ...at, depth: at.depth + 1, fieldName });
|
|
34
34
|
/** Whether a scalar is a string or integer enum with a value of its kind: a declared enum. */
|
|
35
35
|
const isEnum = (ir) => ir.enum !== undefined &&
|
|
@@ -83,6 +83,14 @@ export function rustTypeOf(ir, at) {
|
|
|
83
83
|
}
|
|
84
84
|
/** The use positions inside the declaration of `name`. */
|
|
85
85
|
const memberOf = (name, at) => (schema, fieldName) => use(schema, { ...at, depth: 0, fieldName, parentName: name, self: name });
|
|
86
|
+
/** What the union declared as `name` reaches: its members' use positions and the hoist of its inline variants. */
|
|
87
|
+
const unionScope = (name, at) => ({
|
|
88
|
+
declare: (schema, key, base) => rustHoisted(schema, at, key, base),
|
|
89
|
+
member: memberOf(name, at),
|
|
90
|
+
names: at.names,
|
|
91
|
+
});
|
|
92
|
+
/** Each value the keyed union `union`, declared as `name`, selects a variant by, with that variant and its payload type. */
|
|
93
|
+
export const rustUnionVariants = (name, union, at) => unionVariants(name, union, unionScope(name, at));
|
|
86
94
|
/** The top-level declaration of the type `name` (a Rust identifier already) for `ir`. */
|
|
87
95
|
export function rustTopLevel(name, ir, at) {
|
|
88
96
|
const member = memberOf(name, at);
|
|
@@ -97,9 +105,7 @@ export function rustTopLevel(name, ir, at) {
|
|
|
97
105
|
/* a closed object without fields is a struct too: `{}` on the wire, where a map alias would admit any key */
|
|
98
106
|
if (ir.kind === "object" && (ir.fields.length > 0 || ir.additional === false))
|
|
99
107
|
return objectDecl(name, ir, member);
|
|
100
|
-
if (ir.kind === "union" && ir.variants.length > 0)
|
|
101
|
-
|
|
102
|
-
return unionDecl(name, ir, { declare: variant, member, names: at.names });
|
|
103
|
-
}
|
|
108
|
+
if (ir.kind === "union" && ir.variants.length > 0)
|
|
109
|
+
return unionDecl(name, ir, unionScope(name, at));
|
|
104
110
|
return `pub type ${name} = ${member(ir, "Value")};`;
|
|
105
111
|
}
|
package/dist/emit/rust/ws.d.ts
CHANGED
|
@@ -1,9 +1,15 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* A WebSocket operation's answer (contract 20 §2.0, §2.2): `TypedWebSocket
|
|
2
|
+
* A WebSocket operation's answer (contract 20 §2.0, §2.2): `TypedWebSocket<In, Out>`, dialed offering the Opts'
|
|
3
3
|
* `protocols`, its Opts' `reconnect_token` sent as one query param only when set and non-empty; a declared
|
|
4
|
-
* `reconnect_token` query param is folded into that field (Fd3).
|
|
4
|
+
* `reconnect_token` query param is folded into that field (Fd3). `In` is what the server sends (`send`), `Out` what
|
|
5
|
+
* it receives (`receive`), an inline union hoisted as `<Op>Send` or `<Op>Receive`; an op without them keeps the
|
|
6
|
+
* defaults, its frames as bytes and any JSON value sent. A read side keyed on one field (D9) gets an `on_<value>` per
|
|
7
|
+
* member, an inherent impl in types.rs written once per read type, except a value whose method a handler holds.
|
|
5
8
|
*/
|
|
9
|
+
import type { IRSchema } from "../../ir/model.ts";
|
|
10
|
+
import { type SdkOp } from "../../ir/sdk-model.ts";
|
|
6
11
|
import type { OptsField, StreamAnswer } from "./sdk-opts.ts";
|
|
12
|
+
import { type RustTypeContext } from "./types.ts";
|
|
7
13
|
/** The resume cursor's token, which the WebSocket and realtime Opts carry. */
|
|
8
14
|
export declare const RECONNECT_TOKEN: {
|
|
9
15
|
ident: string;
|
|
@@ -17,5 +23,17 @@ export declare const PROTOCOLS: {
|
|
|
17
23
|
};
|
|
18
24
|
/** Whether a declared param is the `reconnect_token` query param, the resume channel a socket dial sends. */
|
|
19
25
|
export declare const isReconnectToken: (param: string, where: OptsField["in"]) => boolean;
|
|
20
|
-
/**
|
|
21
|
-
export declare
|
|
26
|
+
/** One direction of `op`'s messages as its Rust type: an inline union is declared as `<Op><side>`. */
|
|
27
|
+
export declare function messageType(op: SdkOp, schema: IRSchema, side: "Receive" | "Send", at: RustTypeContext): string;
|
|
28
|
+
/**
|
|
29
|
+
* The `on_<value>` methods of `<base><read, Out>`, `read` the keyed `schema`, declared once in `at`: each takes the
|
|
30
|
+
* messages whose key is that value; a value whose method one of `handlers` names gets none.
|
|
31
|
+
*/
|
|
32
|
+
export declare function valueHandlers(base: string, handlers: readonly string[], read: {
|
|
33
|
+
readonly schema: IRSchema;
|
|
34
|
+
readonly type: string;
|
|
35
|
+
}, at: RustTypeContext): void;
|
|
36
|
+
/** The type params of a socket reading `read` and sending `write`, the defaults left out. */
|
|
37
|
+
export declare const typeParams: (read: string | undefined, write: string | undefined, untyped: string) => string;
|
|
38
|
+
/** The WebSocket operation `op`'s answer, its message types hoisted into `at`. */
|
|
39
|
+
export declare function wsAnswer(op: SdkOp, at: RustTypeContext): StreamAnswer;
|
package/dist/emit/rust/ws.js
CHANGED
|
@@ -1,3 +1,8 @@
|
|
|
1
|
+
import { dispatchOf } from "../../ir/sdk-model.js";
|
|
2
|
+
import { lineComment, rustString } from "../shared/escape.js";
|
|
3
|
+
import { NameScope, rustTypeIdent, rustValueIdent } from "../shared/lang.js";
|
|
4
|
+
import { typeAt } from "./sdk-body.js";
|
|
5
|
+
import { rustHoisted, rustUnionVariants } from "./types.js";
|
|
1
6
|
/** The resume cursor's token, which the WebSocket and realtime Opts carry. */
|
|
2
7
|
export const RECONNECT_TOKEN = { ident: "reconnect_token", type: "Option<String>" };
|
|
3
8
|
/** The subprotocols a WebSocket or realtime dial offers. */
|
|
@@ -11,10 +16,55 @@ const WS = {
|
|
|
11
16
|
sends: ['spec.query("reconnect_token", &crate::request::cursor(&opts.reconnect_token));'],
|
|
12
17
|
};
|
|
13
18
|
const DOC = "Resolves once the socket is open: a refused handshake with an error status is `Err(Error::Api)`. `cancel_on` ends its reads quietly; dropping it closes it.";
|
|
14
|
-
/**
|
|
15
|
-
export
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
19
|
+
/** One direction of `op`'s messages as its Rust type: an inline union is declared as `<Op><side>`. */
|
|
20
|
+
export function messageType(op, schema, side, at) {
|
|
21
|
+
if (schema.kind !== "union")
|
|
22
|
+
return typeAt(schema, op.id, side, at);
|
|
23
|
+
return rustHoisted(schema, at, `${op.id}.${side}`, `${rustTypeIdent(op.id)}${side}`);
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* The `on_<value>` methods of `<base><read, Out>`, `read` the keyed `schema`, declared once in `at`: each takes the
|
|
27
|
+
* messages whose key is that value; a value whose method one of `handlers` names gets none.
|
|
28
|
+
*/
|
|
29
|
+
export function valueHandlers(base, handlers, read, at) {
|
|
30
|
+
const key = `${read.type}.${base}`;
|
|
31
|
+
const dispatch = dispatchOf(read.schema, at.names.resolve);
|
|
32
|
+
if (dispatch === undefined || at.decls.has(key))
|
|
33
|
+
return;
|
|
34
|
+
const scope = new NameScope(handlers);
|
|
35
|
+
const methods = rustUnionVariants(read.type, dispatch.union, at).flatMap(({ type, value, variant }) => {
|
|
36
|
+
const method = rustValueIdent(`on_${value}`);
|
|
37
|
+
if (scope.has(method))
|
|
38
|
+
return [];
|
|
39
|
+
return [
|
|
40
|
+
"",
|
|
41
|
+
...lineComment(`Calls \`handler\` on each message whose ${rustString(dispatch.key)} is ${rustString(value)}.`, "///", " "),
|
|
42
|
+
` pub fn ${scope.claim(method)}(&mut self, mut handler: impl FnMut(&${type}) + Send + 'static) {`,
|
|
43
|
+
" self.on_message(move |m| {",
|
|
44
|
+
` if let ${read.type}::${variant}(v) = m {`,
|
|
45
|
+
" handler(v);",
|
|
46
|
+
" }",
|
|
47
|
+
" });",
|
|
48
|
+
" }",
|
|
49
|
+
];
|
|
50
|
+
});
|
|
51
|
+
if (methods.length === 0)
|
|
52
|
+
return;
|
|
53
|
+
at.decls.set(key, [`impl<Out> crate::${base}<${read.type}, Out> {`, ...methods.slice(1), "}"].join("\n"));
|
|
54
|
+
}
|
|
55
|
+
/** The type params of a socket reading `read` and sending `write`, the defaults left out. */
|
|
56
|
+
export const typeParams = (read, write, untyped) => write === undefined ? (read === undefined ? "" : `<${read}>`) : `<${read ?? untyped}, ${write}>`;
|
|
57
|
+
/* the handlers a socket takes: a member whose on_<value> one of them names gets none */
|
|
58
|
+
const HANDLERS = ["on_message", "on_close", "on_error"];
|
|
59
|
+
/** The WebSocket operation `op`'s answer, its message types hoisted into `at`. */
|
|
60
|
+
export function wsAnswer(op, at) {
|
|
61
|
+
const { receive, send } = op.ir.messages ?? {};
|
|
62
|
+
const read = send && messageType(op, send, "Send", at);
|
|
63
|
+
const write = receive && messageType(op, receive, "Receive", at);
|
|
64
|
+
if (send !== undefined && read !== undefined)
|
|
65
|
+
valueHandlers("TypedWebSocket", HANDLERS, { schema: send, type: read }, at);
|
|
66
|
+
const params = typeParams(read, write, "Vec<u8>");
|
|
67
|
+
/* the answer type fixes both params: a socket without a read type reads bytes */
|
|
68
|
+
const run = `crate::ws::${read === undefined ? "dial" : "typed"}(opts.protocols.clone())`;
|
|
69
|
+
return { doc: DOC, run, stream: WS, type: `TypedWebSocket${params}` };
|
|
70
|
+
}
|
|
@@ -36,7 +36,7 @@ export type RouteEntry = {
|
|
|
36
36
|
es?: Readonly<Record<string, string>>;
|
|
37
37
|
/** The live handler record; present in a snapshot of a running app, never written. */
|
|
38
38
|
h?: unknown;
|
|
39
|
-
/** Set on an internal route (spec, docs, manifest): it is left out of the
|
|
39
|
+
/** Set on an internal route (spec, docs, manifest): it is left out of the document. */
|
|
40
40
|
i?: 1 | true;
|
|
41
41
|
/** What the route's `.input()` declares; a live value, never written. */
|
|
42
42
|
iv?: unknown;
|
|
@@ -200,16 +200,6 @@ function N(s: Record<string, TreeNode> = S({}), m: Record<string, string> | null
|
|
|
200
200
|
return { d, m, s, w, ws }
|
|
201
201
|
}
|
|
202
202
|
`;
|
|
203
|
-
/** The exported selectors: every HTTP route that is neither internal nor marked internal by its meta. */
|
|
204
|
-
function selectorType(routes, intern) {
|
|
205
|
-
const ids = routes
|
|
206
|
-
.filter((route) => !route.id.startsWith("WS ") && route.i === null && route.mt?.internal !== true)
|
|
207
|
-
.map((route) => route.id)
|
|
208
|
-
.sort(compareCodeUnits);
|
|
209
|
-
if (ids.length === 0)
|
|
210
|
-
return "";
|
|
211
|
-
return `\nexport type RouteSelector = ${ids.map((id) => `typeof ${intern.id(id)}`).join(" | ")}\n`;
|
|
212
|
-
}
|
|
213
203
|
/** The route-tree module for `tree` (a snapshot or a merged tree); throws on anything it cannot carry. */
|
|
214
204
|
export function generateRouteTree(tree) {
|
|
215
205
|
if (tree.v !== 2)
|
|
@@ -231,7 +221,6 @@ export function generateRouteTree(tree) {
|
|
|
231
221
|
/* S typed by its entry: inferred from the literals, the union of entries would give each es the others' keys */
|
|
232
222
|
`export const routes: RouteTree["routes"] = S<RouteTree["routes"][string]>({\n${routes.map((route) => routeLine(route, intern)).join(",\n")}\n})\n`,
|
|
233
223
|
shape ?? "",
|
|
234
|
-
selectorType(routes, intern),
|
|
235
224
|
meta.length > 0 ? `export const meta: ${metaType} = S({\n${meta.join(",\n")}\n})\n` : "",
|
|
236
225
|
`export const routeTree: RouteTree = { v: 2, root: tree, routes, ${meta.length > 0 ? "meta" : "meta: {}"} }\n`,
|
|
237
226
|
]
|
|
@@ -22,9 +22,11 @@ export const RESERVED = [
|
|
|
22
22
|
"Result",
|
|
23
23
|
"SDKConfig",
|
|
24
24
|
"SSEEvent",
|
|
25
|
+
"SSEEventOf",
|
|
25
26
|
"SseOptions",
|
|
26
27
|
"TypedWebSocket",
|
|
27
28
|
"Uint8Array",
|
|
29
|
+
"WsFrame",
|
|
28
30
|
"WsOptions",
|
|
29
31
|
];
|
|
30
32
|
/** What the types file may import from the runtime module, in the order the import lists them. */
|
|
@@ -34,7 +36,9 @@ const RUNTIME_TYPES = [
|
|
|
34
36
|
"ResumableConnection",
|
|
35
37
|
"SDKConfig",
|
|
36
38
|
"SSEEvent",
|
|
39
|
+
"SSEEventOf",
|
|
37
40
|
"TypedWebSocket",
|
|
41
|
+
"WsFrame",
|
|
38
42
|
];
|
|
39
43
|
/** The input fields every call takes, by transport. */
|
|
40
44
|
const OPTIONS = `export type HttpOptions = {
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { irErrorEnvelope, isJsonMedia, mediaEssence, sdkModel, sseEventSchema } from "../../ir/sdk-model.js";
|
|
1
|
+
import { dispatchKey, irErrorEnvelope, isJsonMedia, mediaEssence, sdkModel, sseEventSchema, sseEvents, } from "../../ir/sdk-model.js";
|
|
2
2
|
import { bodiesOf } from "../../ir/slots.js";
|
|
3
3
|
import { blockCommentText, tsString } from "../shared/escape.js";
|
|
4
4
|
import { compareCodeUnits, NameTable, pascalWords } from "../shared/lang.js";
|
|
@@ -58,11 +58,13 @@ function inputOf(op, ctx) {
|
|
|
58
58
|
/* a header or cookie is text on the wire: an enum keeps its values, anything else is a string */
|
|
59
59
|
const text = (p) => (p.schema.kind === "scalar" && p.schema.enum ? irToTs(p.schema, types) : "string");
|
|
60
60
|
const pathParams = op.pathParams.map((p) => ({ ...p, required: true }));
|
|
61
|
+
/* a browser WebSocket sends no headers and sets no cookies, so a socket call takes neither */
|
|
62
|
+
const socket = op.stream === "ws";
|
|
61
63
|
const parts = [
|
|
62
64
|
paramsPart("params", pathParams, (p) => irToTs(p.schema, types)),
|
|
63
65
|
paramsPart("search", op.query, (p) => irToTs(p.schema, types)),
|
|
64
|
-
paramsPart("headers", op.headers, text),
|
|
65
|
-
paramsPart("cookies", op.ir.params.cookie ?? [], text),
|
|
66
|
+
socket ? null : paramsPart("headers", op.headers, text),
|
|
67
|
+
socket ? null : paramsPart("cookies", op.ir.params.cookie ?? [], text),
|
|
66
68
|
...bodyParts(op, ctx),
|
|
67
69
|
].filter((part) => part !== null);
|
|
68
70
|
const ordered = [...parts.filter((p) => p.required), ...parts.filter((p) => !p.required)];
|
|
@@ -102,6 +104,46 @@ function headersOf(op) {
|
|
|
102
104
|
const fields = [...byName].sort(([a], [b]) => compareCodeUnits(a, b));
|
|
103
105
|
return objectText(fields.map(([name, required]) => `${quoteKey(name)}${required ? "" : "?"}: string`));
|
|
104
106
|
}
|
|
107
|
+
/** A WebSocket op's socket: typed by its declared messages, `In` what the server receives, `Out` what it sends (D9). */
|
|
108
|
+
function socketType(op, ctx) {
|
|
109
|
+
const messages = op.ir.messages;
|
|
110
|
+
if (messages === undefined)
|
|
111
|
+
return "TypedWebSocket";
|
|
112
|
+
const { receive, send } = messages;
|
|
113
|
+
const key = send === undefined ? undefined : dispatchKey(send, ctx.resolve);
|
|
114
|
+
const args = [
|
|
115
|
+
receive === undefined ? "WsFrame" : irToTs(receive, ctx.types),
|
|
116
|
+
send === undefined ? "string" : irToTs(send, ctx.types),
|
|
117
|
+
...(key === undefined ? [] : [tsString(key)]),
|
|
118
|
+
];
|
|
119
|
+
while (args.length > 0 && args.at(-1) === ["WsFrame", "string"][args.length - 1])
|
|
120
|
+
args.pop();
|
|
121
|
+
return args.length === 0 ? "TypedWebSocket" : `TypedWebSocket<${args.join(", ")}>`;
|
|
122
|
+
}
|
|
123
|
+
/** A realtime op's connection: what it yields (the messages it hears, else its event data), sends, and dispatches on. */
|
|
124
|
+
function connectionType(op, ctx) {
|
|
125
|
+
const { receive, send } = op.ir.messages ?? {};
|
|
126
|
+
const yields = send ?? sseEventSchema(op.ir, ctx.resolve);
|
|
127
|
+
const key = send === undefined ? undefined : dispatchKey(send, ctx.resolve);
|
|
128
|
+
const args = [
|
|
129
|
+
yields === undefined ? "unknown" : irToTs(yields, ctx.types),
|
|
130
|
+
receive === undefined ? "unknown" : irToTs(receive, ctx.types),
|
|
131
|
+
...(key === undefined ? [] : [tsString(key)]),
|
|
132
|
+
];
|
|
133
|
+
while (args.length > 1 && args.at(-1) === "unknown")
|
|
134
|
+
args.pop();
|
|
135
|
+
return `ResumableConnection<${args.join(", ")}>`;
|
|
136
|
+
}
|
|
137
|
+
/** What an SSE op's stream yields: `SSEEventOf` its named events (D7), else `SSEEvent` of its one data schema. */
|
|
138
|
+
function sseEventType(op, ctx) {
|
|
139
|
+
const named = sseEvents(op.ir);
|
|
140
|
+
if (named !== undefined) {
|
|
141
|
+
const fields = named.map(({ data, name }) => `${quoteKey(name)}: ${irToTs(data, ctx.types)}`);
|
|
142
|
+
return `SSEEventOf<${objectText(fields)}>`;
|
|
143
|
+
}
|
|
144
|
+
const events = sseEventSchema(op.ir, ctx.resolve);
|
|
145
|
+
return events === undefined ? "SSEEvent" : `SSEEvent<${irToTs(events, ctx.types)}>`;
|
|
146
|
+
}
|
|
105
147
|
/** `op`'s member line `name`: a REST call a HttpCall, a stream a HttpStream, defaults dropped; a connection its method. */
|
|
106
148
|
function signature(name, op, ctx) {
|
|
107
149
|
const input = inputOf(op, ctx);
|
|
@@ -112,16 +154,13 @@ function signature(name, op, ctx) {
|
|
|
112
154
|
const key = quoteKey(name);
|
|
113
155
|
/* a realtime op is one resumable connection of its event data; any other is typed by its transport */
|
|
114
156
|
const { realtime, sse, websocket } = op.ir.extensions;
|
|
115
|
-
if (realtime)
|
|
116
|
-
|
|
117
|
-
return `${key}(${arg("RealtimeCallOptions")}): ResumableConnection<${events ? irToTs(events, ctx.types) : "unknown"}>`;
|
|
118
|
-
}
|
|
157
|
+
if (realtime)
|
|
158
|
+
return `${key}(${arg("RealtimeCallOptions")}): ${connectionType(op, ctx)}`;
|
|
119
159
|
if (websocket)
|
|
120
|
-
return `${key}(${arg("WsOptions")}):
|
|
160
|
+
return `${key}(${arg("WsOptions")}): ${socketType(op, ctx)}`;
|
|
121
161
|
const errors = errorsOf(op, ctx.types, ctx.resolve);
|
|
122
162
|
if (sse) {
|
|
123
|
-
const
|
|
124
|
-
const event = events === undefined ? "SSEEvent" : `SSEEvent<${irToTs(events, ctx.types)}>`;
|
|
163
|
+
const event = sseEventType(op, ctx);
|
|
125
164
|
return `${key}: HttpStream<${[input.type, event, ...(errors === null ? [] : [errors])].join(", ")}>`;
|
|
126
165
|
}
|
|
127
166
|
const headers = headersOf(op);
|
package/dist/emit/ts/sdk.js
CHANGED
|
@@ -63,8 +63,8 @@ const RUNTIME_TYPES = {
|
|
|
63
63
|
"TransportConnection",
|
|
64
64
|
"TransportOpts",
|
|
65
65
|
],
|
|
66
|
-
sse: ["SSEEvent"],
|
|
67
|
-
ws: ["TypedWebSocket"],
|
|
66
|
+
sse: ["SSEEvent", "SSEEventOf"],
|
|
67
|
+
ws: ["TypedWebSocket", "WsFrame"],
|
|
68
68
|
};
|
|
69
69
|
/** The names of `lists` a runtime with `features` ships, ignoring case in their order. */
|
|
70
70
|
function shipped(lists, features) {
|
|
@@ -15,10 +15,16 @@ export type ServiceEntry = {
|
|
|
15
15
|
params?: string[];
|
|
16
16
|
path: string;
|
|
17
17
|
realtime?: true;
|
|
18
|
-
/** an event stream; `"json"` when its declared event schema is not a string */
|
|
19
|
-
sse?: "json" | true;
|
|
18
|
+
/** an event stream; `"json"` when its declared event schema is not a string, its JSON events' names when it names them */
|
|
19
|
+
sse?: "json" | string[] | true;
|
|
20
20
|
wildcard?: string;
|
|
21
21
|
ws?: true;
|
|
22
|
+
/** the server declares what it sends: the socket parses each text frame */
|
|
23
|
+
decode?: true;
|
|
24
|
+
/** the field a socket's message union is keyed on (D9) */
|
|
25
|
+
dispatch?: string;
|
|
26
|
+
/** the server declares what it receives: the socket sends JSON */
|
|
27
|
+
encode?: true;
|
|
22
28
|
};
|
|
23
29
|
export type ServiceMapNode = ServiceEntry | {
|
|
24
30
|
[key: string]: ServiceMapNode;
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { isJsonMedia, mediaEssence, sdkModel, sseEventSchema, } from "../../ir/sdk-model.js";
|
|
1
|
+
import { isJsonMedia, mediaEssence, sdkModel, dispatchKey, isJsonEventData, sseEventSchema, sseEvents, } from "../../ir/sdk-model.js";
|
|
2
2
|
import { openApiPathParams } from "../../ir/slots.js";
|
|
3
3
|
import { tsString } from "../shared/escape.js";
|
|
4
4
|
import { compareCodeUnits } from "../shared/lang.js";
|
|
@@ -69,6 +69,33 @@ function headersOf(op, status) {
|
|
|
69
69
|
const declared = op.responses[status]?.headers ?? [];
|
|
70
70
|
return [...new Set(declared.map(({ name }) => name.toLowerCase()))].sort(compareCodeUnits);
|
|
71
71
|
}
|
|
72
|
+
/** How the runtime reads `op`'s events: the names of its JSON events when it names them (D7), else all or none. */
|
|
73
|
+
function sseKind(op, resolve) {
|
|
74
|
+
const named = sseEvents(op);
|
|
75
|
+
if (named !== undefined)
|
|
76
|
+
return named.filter(({ data }) => isJsonEventData(data, resolve)).map(({ name }) => name);
|
|
77
|
+
return sseEventSchema(op, resolve) === undefined ? true : "json";
|
|
78
|
+
}
|
|
79
|
+
/**
|
|
80
|
+
* How a socket op's declared messages read on the wire: a WebSocket's sends JSON when the server declares `receive`
|
|
81
|
+
* and its frames parsed when it declares `send`; either kind's messages dispatched on `send`'s key (D9).
|
|
82
|
+
*/
|
|
83
|
+
function socketEntry(op, resolve) {
|
|
84
|
+
const { messages } = op;
|
|
85
|
+
if (messages === undefined)
|
|
86
|
+
return {};
|
|
87
|
+
const out = {};
|
|
88
|
+
if (!op.extensions.realtime) {
|
|
89
|
+
if (messages.receive !== undefined)
|
|
90
|
+
out.encode = true;
|
|
91
|
+
if (messages.send !== undefined)
|
|
92
|
+
out.decode = true;
|
|
93
|
+
}
|
|
94
|
+
const key = messages.send === undefined ? undefined : dispatchKey(messages.send, resolve);
|
|
95
|
+
if (key !== undefined)
|
|
96
|
+
out.dispatch = key;
|
|
97
|
+
return out;
|
|
98
|
+
}
|
|
72
99
|
/** The service entry of `op`; `success` is its success answer as the SDK model reads it. */
|
|
73
100
|
function entryOf(op, success, resolve) {
|
|
74
101
|
const entry = { method: op.method, path: op.path };
|
|
@@ -79,11 +106,12 @@ function entryOf(op, success, resolve) {
|
|
|
79
106
|
if (wildcard)
|
|
80
107
|
entry.wildcard = wildcard.name;
|
|
81
108
|
if (op.extensions.sse)
|
|
82
|
-
entry.sse =
|
|
109
|
+
entry.sse = sseKind(op, resolve);
|
|
83
110
|
if (op.extensions.websocket)
|
|
84
111
|
entry.ws = true;
|
|
85
112
|
if (op.extensions.realtime)
|
|
86
113
|
entry.realtime = true;
|
|
114
|
+
Object.assign(entry, socketEntry(op, resolve));
|
|
87
115
|
if (op.extensions.idempotencyKey)
|
|
88
116
|
entry.idempotent = true;
|
|
89
117
|
const invalidate = op.extensions.invalidates;
|
|
@@ -1,8 +1,9 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* `generateTypes` (F3): an app's `_gen/types.gen.d.ts` — the `Routes` map, each route's ctx,
|
|
3
|
-
* input, output, errors and meta, the
|
|
4
|
-
* `BaseCtx`. Read from the app's OpenAPI document (the IR), its route tree
|
|
5
|
-
* extracted ctx types (middleware, env,
|
|
3
|
+
* input, output, errors and meta, the `HttpCodegen` `operationId` slot mapping each declared id
|
|
4
|
+
* to its context, and `BaseCtx`. Read from the app's OpenAPI document (the IR), its route tree
|
|
5
|
+
* (meta, O1) and the extracted ctx types (middleware, env, parsed inputs, O3), joined on
|
|
6
|
+
* `x-backend-route`.
|
|
6
7
|
*/
|
|
7
8
|
import type { ExtractedTypes } from "../../extract/extract.ts";
|
|
8
9
|
import type { RouteTree } from "./route-tree.ts";
|
package/dist/emit/ts/type-gen.js
CHANGED
|
@@ -8,22 +8,10 @@ import { statusKeyOf } from "../shared/status-keys.js";
|
|
|
8
8
|
import { irToTs } from "../shared/type-emitter.js";
|
|
9
9
|
import { componentNames } from "./sdk-types.js";
|
|
10
10
|
/* the names the file declares, which a component schema never takes */
|
|
11
|
-
const RESERVED = [
|
|
12
|
-
"HttpContext",
|
|
13
|
-
"HttpError",
|
|
14
|
-
"HttpMeta",
|
|
15
|
-
"Omit",
|
|
16
|
-
"Partial",
|
|
17
|
-
"Readonly",
|
|
18
|
-
"Record",
|
|
19
|
-
"Routes",
|
|
20
|
-
"RouteSelector",
|
|
21
|
-
"TapMap",
|
|
22
|
-
];
|
|
11
|
+
const RESERVED = ["HttpContext", "HttpError", "HttpMeta", "Omit", "Partial", "Readonly", "Record", "Routes"];
|
|
23
12
|
/* the v1 error-factory signature of a key without a schema (core errors.ts ErrorFactoryOpts) */
|
|
24
13
|
const STANDARD_FACTORY = "(opts?: { cause?: unknown; fields?: Record<string, { error_key: string; message: string; path: string }[]>; headers?: Record<string, string>; vars?: Record<string, number | string> }) => HttpError";
|
|
25
14
|
const EXTRACTORS = [
|
|
26
|
-
["RouteCtx", "ctx"],
|
|
27
15
|
["RouteInput", "input"],
|
|
28
16
|
["RouteOutput", "output"],
|
|
29
17
|
["RouteErrors", "errors"],
|
|
@@ -148,15 +136,29 @@ function errorsOf(op, ctx) {
|
|
|
148
136
|
* Without an extracted declaration (no ts-morph, or an app that declares no meta) the literals are all there is.
|
|
149
137
|
*/
|
|
150
138
|
function ctxMeta(extracted, literal) {
|
|
151
|
-
|
|
139
|
+
/* with nothing extracted, the tree's literals are all there is */
|
|
140
|
+
if (extracted === null || extracted === undefined)
|
|
141
|
+
return literal;
|
|
152
142
|
/* the OpenAPI keys the declared meta does not redefine: a consumer that types `security` its own way holds
|
|
153
|
-
that type in the handler, and intersecting backend's would conflict with it
|
|
154
|
-
|
|
143
|
+
that type in the handler, and intersecting backend's would conflict with it. An app that declares none
|
|
144
|
+
holds them all, each widened by \`.meta()\` */
|
|
145
|
+
const declared = extracted.meta;
|
|
146
|
+
return declared === null ? "Partial<HttpMeta>" : `Partial<Omit<HttpMeta, keyof ${declared}>> & ${declared}`;
|
|
155
147
|
}
|
|
156
148
|
/** `ctx.params`: the type a param schema gives it as extracted, else each of the pattern's params a string. */
|
|
157
149
|
function ctxParams(extracted, id, pattern) {
|
|
158
150
|
return extracted?.params[id] ?? objectText(paramsOf(pattern));
|
|
159
151
|
}
|
|
152
|
+
/**
|
|
153
|
+
* The ctx's `meta` and `routePattern`. A mounted route's handler types the path it was registered at, never the one
|
|
154
|
+
* it is served at, so its ctx keeps the base's `string` and that handler's own ctx still fits.
|
|
155
|
+
*/
|
|
156
|
+
function routeFields(extracted, id, literal) {
|
|
157
|
+
const fields = [["readonly meta", `Readonly<${ctxMeta(extracted, literal)}>`]];
|
|
158
|
+
if (!extracted?.mounted.includes(id))
|
|
159
|
+
fields.push(["readonly routePattern", tsString(id.slice(id.indexOf(" ") + 1))]);
|
|
160
|
+
return fields;
|
|
161
|
+
}
|
|
160
162
|
/** One `Routes[pattern][method]` entry. */
|
|
161
163
|
function routeEntry(id, op, options, ctx) {
|
|
162
164
|
const pattern = id.slice(id.indexOf(" ") + 1);
|
|
@@ -168,7 +170,6 @@ function routeEntry(id, op, options, ctx) {
|
|
|
168
170
|
const mt = options.tree.routes[id]?.mt;
|
|
169
171
|
/* the values the tree carries, as literals: what a consumer reads a route's configuration from */
|
|
170
172
|
const literal = mt && Object.keys(mt).length > 0 ? literalType(mt) : "{}";
|
|
171
|
-
const meta = ctxMeta(extracted, literal);
|
|
172
173
|
const output = outputOf(op, ctx);
|
|
173
174
|
const own = [];
|
|
174
175
|
if (input !== "{}")
|
|
@@ -177,7 +178,7 @@ function routeEntry(id, op, options, ctx) {
|
|
|
177
178
|
own.push(["readonly params", params]);
|
|
178
179
|
if (factories.length > 0)
|
|
179
180
|
own.push(["readonly errors", objectText(factories)]);
|
|
180
|
-
own.push(
|
|
181
|
+
own.push(...routeFields(extracted, id, literal));
|
|
181
182
|
const base = options.baseCtxName ?? "BaseCtx";
|
|
182
183
|
const parts = [factories.length > 0 ? `Omit<${base}, "errors">` : base];
|
|
183
184
|
const adds = extracted?.routes[id];
|
|
@@ -193,18 +194,67 @@ function routeEntry(id, op, options, ctx) {
|
|
|
193
194
|
];
|
|
194
195
|
return entry.map(([key, type]) => `\t\t\t${key}: ${type}`).join("\n");
|
|
195
196
|
}
|
|
196
|
-
/** `BaseCtx`: the app's context over its env, the middleware's additions
|
|
197
|
+
/** `BaseCtx`: the app's context over its env, with the middleware's additions. */
|
|
197
198
|
function baseCtx(extracted, name) {
|
|
198
|
-
const
|
|
199
|
-
const taps = extracted?.taps ?? null;
|
|
200
|
-
const parts = [taps === null ? `HttpContext<${env}>` : `Omit<HttpContext<${env}>, "tap">`];
|
|
199
|
+
const parts = [`HttpContext<${extracted?.env ?? "Record<string, unknown>"}>`];
|
|
201
200
|
const middleware = extracted?.middleware ?? [];
|
|
202
201
|
if (middleware.length > 0)
|
|
203
202
|
parts.push(propsText(middleware));
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
203
|
+
return `export type ${name} = ${parts.join(" & ")}`;
|
|
204
|
+
}
|
|
205
|
+
/**
|
|
206
|
+
* A WebSocket route's ctx, as core's `WSRouteCtx` types its callbacks: the base with the pattern's params, and the
|
|
207
|
+
* search, headers and cookies `.input()` declares. Extracted additions are keyed by HTTP routes only, so none join
|
|
208
|
+
* here.
|
|
209
|
+
*/
|
|
210
|
+
function wsCtx(op, id, options, ctx) {
|
|
211
|
+
const own = [];
|
|
212
|
+
/* the upgrade request's validated search, headers and cookies, as core's `WithInput` holds them */
|
|
213
|
+
const input = wireInput(op, ctx).filter(([key]) => key === "search" || key === "headers" || key === "cookies");
|
|
214
|
+
if (input.length > 0)
|
|
215
|
+
own.push(["readonly input", objectText(input)]);
|
|
216
|
+
const params = ctxParams(options.extracted, id, pathOf(id));
|
|
217
|
+
if (params !== "{}")
|
|
218
|
+
own.push(["readonly params", params]);
|
|
219
|
+
const base = options.baseCtxName ?? "BaseCtx";
|
|
220
|
+
return own.length === 0 ? base : `${base} & ${objectText(own)}`;
|
|
221
|
+
}
|
|
222
|
+
/**
|
|
223
|
+
* The `HttpCodegen` augmentation: each declared id (the route's own, before core's suffix) to its kind and ctx, in
|
|
224
|
+
* code-unit order. An HTTP id names its `Routes` entry's ctx, a declared id over several routes its first route's in
|
|
225
|
+
* code-unit order (D3: no union of contexts). An operation without `x-backend-route` has no entry: `routesOf`
|
|
226
|
+
* reports an HTTP one, this a WebSocket one. Null with no operations, so core's plain string ids apply.
|
|
227
|
+
*/
|
|
228
|
+
function operationSlot(ir, options, ctx) {
|
|
229
|
+
const routeIds = new Map();
|
|
230
|
+
const missing = [];
|
|
231
|
+
for (const op of ir.operations) {
|
|
232
|
+
const route = op.extensions.route;
|
|
233
|
+
if (route === undefined) {
|
|
234
|
+
if (op.extensions.websocket === true)
|
|
235
|
+
missing.push(`${op.method} ${op.path}: no x-backend-route; left out of the operationId slot`);
|
|
236
|
+
continue;
|
|
237
|
+
}
|
|
238
|
+
const declared = op.extensions.declaredId ?? op.id;
|
|
239
|
+
const entry = routeIds.get(declared) ?? { op, routes: [] };
|
|
240
|
+
if (!entry.routes.includes(route))
|
|
241
|
+
entry.routes.push(route);
|
|
242
|
+
routeIds.set(declared, entry);
|
|
243
|
+
}
|
|
244
|
+
for (const message of missing.sort(compareCodeUnits))
|
|
245
|
+
options.report(message);
|
|
246
|
+
if (routeIds.size === 0)
|
|
247
|
+
return null;
|
|
248
|
+
const entries = [...routeIds].sort(([a], [b]) => compareCodeUnits(a, b));
|
|
249
|
+
const lines = entries.map(([declared, { op, routes }]) => {
|
|
250
|
+
const id = routes.sort(compareCodeUnits)[0];
|
|
251
|
+
const method = id.slice(0, id.indexOf(" ")).toLowerCase();
|
|
252
|
+
const entry = op.extensions.websocket === true
|
|
253
|
+
? `kind: "ws"; ctx: ${wsCtx(op, id, options, ctx)}`
|
|
254
|
+
: `kind: "http"; ctx: Routes[${tsString(pathOf(id))}][${tsString(method)}]["ctx"]`;
|
|
255
|
+
return `\t\t\t${tsString(declared)}: { ${entry} }`;
|
|
256
|
+
});
|
|
257
|
+
return `declare module "@workerstack/backend/http" {\n\tinterface HttpCodegen {\n\t\toperationId: {\n${lines.join("\n")}\n\t\t}\n\t}\n}`;
|
|
208
258
|
}
|
|
209
259
|
/** A route id's path: `GET /a` → `/a`. */
|
|
210
260
|
const pathOf = (id) => id.slice(id.indexOf(" ") + 1);
|
|
@@ -231,21 +281,14 @@ export function generateTypes(options) {
|
|
|
231
281
|
const names = { refName: componentNames(ir, [...RESERVED, name]) };
|
|
232
282
|
const ctx = { names, resolve: (schema) => irToTs(schema, names) };
|
|
233
283
|
const hasErrors = [...routes.values()].some((op) => Object.keys(op.extensions.errors ?? {}).length > 0);
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
const
|
|
237
|
-
const imports = [
|
|
238
|
-
"HttpContext",
|
|
239
|
-
"WithOutput",
|
|
240
|
-
...(hasErrors ? ["HttpError"] : []),
|
|
241
|
-
...(declaredMeta === null ? [] : ["HttpMeta"]),
|
|
242
|
-
];
|
|
284
|
+
/* HttpMeta once a route's ctx reads it: with anything extracted, the ctx's meta is built from its keys */
|
|
285
|
+
const readsMeta = options.extracted !== null && options.extracted !== undefined && routes.size > 0;
|
|
286
|
+
const imports = ["HttpContext", "WithOutput", ...(hasErrors ? ["HttpError"] : []), ...(readsMeta ? ["HttpMeta"] : [])];
|
|
243
287
|
const out = [`import type { ${imports.join(", ")} } from "@workerstack/backend/http"`];
|
|
244
|
-
out.push(
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
out.push(
|
|
248
|
-
}
|
|
288
|
+
out.push(baseCtx(options.extracted, name));
|
|
289
|
+
const slot = operationSlot(ir, options, ctx);
|
|
290
|
+
if (slot !== null)
|
|
291
|
+
out.push(slot);
|
|
249
292
|
for (const schema of Object.keys(ir.schemas).sort(compareCodeUnits))
|
|
250
293
|
out.push(`type ${names.refName?.(schema)} = ${ctx.resolve(ir.schemas[schema])}`);
|
|
251
294
|
out.push(routesType(routes, options, ctx));
|
package/dist/extract/chain.d.ts
CHANGED
|
@@ -7,6 +7,12 @@
|
|
|
7
7
|
import type { ts } from "ts-morph";
|
|
8
8
|
import { type Serializer } from "./serialize.ts";
|
|
9
9
|
import type { Registration } from "./walk.ts";
|
|
10
|
+
/** A registration with the route ids its methods and paths give: the router's, never guessed. */
|
|
11
|
+
export type Routed = Registration & {
|
|
12
|
+
ids: string[];
|
|
13
|
+
/** the ids among `ids` served through a mount, at a path other than `own` */
|
|
14
|
+
mounted: string[];
|
|
15
|
+
};
|
|
10
16
|
/** One property on `ctx` that the framework's context class does not declare: what the middleware added. */
|
|
11
17
|
export type ExtractedProp = {
|
|
12
18
|
/** Its name on `ctx`. */
|
|
@@ -25,10 +31,8 @@ export type RouteOptions = {
|
|
|
25
31
|
base: ReadonlySet<string>;
|
|
26
32
|
owner: ts.Node | undefined;
|
|
27
33
|
report: (message: string) => void;
|
|
28
|
-
routeId: (method: string, path: string) => string;
|
|
29
34
|
};
|
|
30
|
-
/**
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
export declare function routeAdditions(found: readonly Registration[], ser: Serializer, options: RouteOptions): Record<string, ExtractedProp[]>;
|
|
35
|
+
/** What a skip says of the route it skips. */
|
|
36
|
+
export declare const SKIPPED = "its ctx is not extracted";
|
|
37
|
+
/** Each route's own additions by route id. An id two registrations give different additions is dropped, never guessed. */
|
|
38
|
+
export declare function routeAdditions(found: readonly Routed[], ser: Serializer, options: RouteOptions): Record<string, ExtractedProp[]>;
|