@open-conduit/sdk 0.0.0-stage → 7.0.0
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 +21 -0
- package/README.md +12 -2
- package/dist/errors.d.ts +99 -0
- package/dist/errors.js +143 -0
- package/dist/extension.d.ts +360 -0
- package/dist/extension.js +674 -0
- package/dist/host.d.ts +131 -0
- package/dist/host.js +253 -0
- package/dist/index.d.ts +10 -0
- package/dist/index.js +19 -0
- package/dist/jsonrpc.d.ts +39 -0
- package/dist/jsonrpc.js +350 -0
- package/dist/schema.d.ts +71 -0
- package/dist/schema.js +252 -0
- package/dist/testing.d.ts +167 -0
- package/dist/testing.js +711 -0
- package/dist/wire.d.ts +1647 -0
- package/dist/wire.js +628 -0
- package/package.json +29 -4
package/dist/jsonrpc.js
ADDED
|
@@ -0,0 +1,350 @@
|
|
|
1
|
+
// The protocol version 1 transport, as protocol/jsonrpc implements it:
|
|
2
|
+
// JSON-RPC 2.0 over a pair of byte streams, one JSON object per line. The
|
|
3
|
+
// connection is symmetric: either side sends requests, which is how an
|
|
4
|
+
// extension calls the host (KV, events, secrets) while serving a host
|
|
5
|
+
// request.
|
|
6
|
+
//
|
|
7
|
+
// - over maxInflight concurrently served requests, a request is refused
|
|
8
|
+
// with "overloaded" rather than queued;
|
|
9
|
+
// - a line longer than maxMessage, invalid JSON or a truncated final line
|
|
10
|
+
// closes the connection, failing every pending call with TransportError;
|
|
11
|
+
// - authored errors cross as -32000 with data.code; anything else crosses
|
|
12
|
+
// as "internal" with no detail;
|
|
13
|
+
// - "$/cancel" aborts the peer's handler signal; a cancelled call rejects
|
|
14
|
+
// at once with CancelledError and a late response is discarded.
|
|
15
|
+
import { CancelledError, Code, ProtocolError, TransportError, decode, encode, } from "./errors.js";
|
|
16
|
+
import { isRecord, matches, t } from "./schema.js";
|
|
17
|
+
/** Bounds of protocol version 1 (protocol/protocol.go). */
|
|
18
|
+
export const MaxMessageBytes = 16 << 20;
|
|
19
|
+
export const MaxChunkBytes = 256 << 10;
|
|
20
|
+
export const MaxInflight = 64;
|
|
21
|
+
/** Capacity reserved for control methods on top of MaxInflight. */
|
|
22
|
+
export const MaxControlInflight = 16;
|
|
23
|
+
const heldMethods = new Set(["executor.wait"]);
|
|
24
|
+
const controlMethods = new Set([
|
|
25
|
+
"executor.recover",
|
|
26
|
+
"executor.interrupt",
|
|
27
|
+
"executor.stop",
|
|
28
|
+
"executor.forget",
|
|
29
|
+
]);
|
|
30
|
+
/** The lane of a host-to-extension method (protocol.LaneOf). */
|
|
31
|
+
export function laneOf(method) {
|
|
32
|
+
if (heldMethods.has(method))
|
|
33
|
+
return "held";
|
|
34
|
+
if (controlMethods.has(method))
|
|
35
|
+
return "control";
|
|
36
|
+
return "bounded";
|
|
37
|
+
}
|
|
38
|
+
export const CancelMethod = "$/cancel";
|
|
39
|
+
const codeParse = -32700;
|
|
40
|
+
const codeInvalidRequest = -32600;
|
|
41
|
+
const codeMethodNotFound = -32601;
|
|
42
|
+
const codeInvalidParams = -32602;
|
|
43
|
+
const codeInternal = -32603;
|
|
44
|
+
const codeCancelled = -32800;
|
|
45
|
+
const codeApplication = -32000;
|
|
46
|
+
const WireError = t.object({
|
|
47
|
+
code: t.integer(),
|
|
48
|
+
message: t.string(),
|
|
49
|
+
data: t.optional(t.object({
|
|
50
|
+
code: t.string(),
|
|
51
|
+
reset_at: t.optional(t.string()),
|
|
52
|
+
diagnostics: t.optional(t.array(t.object({ path: t.string(), code: t.string(), message: t.string() }, { open: true }))),
|
|
53
|
+
}, { open: true })),
|
|
54
|
+
}, { open: true });
|
|
55
|
+
// Only the envelope is decoded here; params and results are decoded by
|
|
56
|
+
// whoever knows their schema.
|
|
57
|
+
const Message = t.object({
|
|
58
|
+
jsonrpc: t.literal("2.0"),
|
|
59
|
+
id: t.optional(t.nullable(t.any())),
|
|
60
|
+
method: t.optional(t.string()),
|
|
61
|
+
params: t.optional(t.any()),
|
|
62
|
+
result: t.optional(t.any()),
|
|
63
|
+
error: t.optional(t.nullable(WireError)),
|
|
64
|
+
}, { open: true });
|
|
65
|
+
function isID(v) {
|
|
66
|
+
return typeof v === "number" || typeof v === "string";
|
|
67
|
+
}
|
|
68
|
+
/** One JSON-RPC peer. */
|
|
69
|
+
export class Conn {
|
|
70
|
+
#handler;
|
|
71
|
+
#out;
|
|
72
|
+
#maxMessage;
|
|
73
|
+
#maxInflight;
|
|
74
|
+
#lane;
|
|
75
|
+
#controlInflight = 0;
|
|
76
|
+
#onProtocolError;
|
|
77
|
+
#pending = new Map();
|
|
78
|
+
#cancels = new Map();
|
|
79
|
+
#next = 0;
|
|
80
|
+
#inflight = 0;
|
|
81
|
+
#closed = false;
|
|
82
|
+
#buffered = [];
|
|
83
|
+
#bufferedBytes = 0;
|
|
84
|
+
done;
|
|
85
|
+
#finish;
|
|
86
|
+
constructor(input, output, handler, o = {}) {
|
|
87
|
+
this.#handler = handler;
|
|
88
|
+
this.#out = output;
|
|
89
|
+
this.#maxMessage = o.maxMessage ?? MaxMessageBytes;
|
|
90
|
+
this.#maxInflight = o.maxInflight ?? MaxInflight;
|
|
91
|
+
this.#lane = o.lane ?? (() => "bounded");
|
|
92
|
+
this.#onProtocolError = o.onProtocolError;
|
|
93
|
+
this.done = new Promise((resolve) => {
|
|
94
|
+
this.#finish = resolve;
|
|
95
|
+
});
|
|
96
|
+
input.on("data", (chunk) => this.#read(typeof chunk === "string" ? Buffer.from(chunk) : chunk));
|
|
97
|
+
input.on("end", () => {
|
|
98
|
+
// A partial final line (a response cut off by a crash) is a protocol
|
|
99
|
+
// error, never a result.
|
|
100
|
+
if (this.#bufferedBytes > 0)
|
|
101
|
+
this.#protocolError("truncated message");
|
|
102
|
+
else
|
|
103
|
+
this.close();
|
|
104
|
+
});
|
|
105
|
+
input.on("error", () => this.close());
|
|
106
|
+
output.on("error", () => this.close());
|
|
107
|
+
}
|
|
108
|
+
/** Reports whether the connection has ended. */
|
|
109
|
+
get closed() {
|
|
110
|
+
return this.#closed;
|
|
111
|
+
}
|
|
112
|
+
/** Ends the connection; pending calls reject with TransportError. */
|
|
113
|
+
close() {
|
|
114
|
+
if (this.#closed)
|
|
115
|
+
return;
|
|
116
|
+
this.#closed = true;
|
|
117
|
+
for (const c of this.#cancels.values())
|
|
118
|
+
c.abort();
|
|
119
|
+
for (const p of this.#pending.values())
|
|
120
|
+
p.reject(new TransportError());
|
|
121
|
+
this.#pending.clear();
|
|
122
|
+
this.#finish();
|
|
123
|
+
}
|
|
124
|
+
#protocolError(reason) {
|
|
125
|
+
this.#onProtocolError?.(reason);
|
|
126
|
+
this.close();
|
|
127
|
+
}
|
|
128
|
+
#read(chunk) {
|
|
129
|
+
let start = 0;
|
|
130
|
+
for (;;) {
|
|
131
|
+
const nl = chunk.indexOf(0x0a, start);
|
|
132
|
+
if (nl < 0)
|
|
133
|
+
break;
|
|
134
|
+
const part = chunk.subarray(start, nl);
|
|
135
|
+
if (this.#bufferedBytes + part.length >= this.#maxMessage)
|
|
136
|
+
return this.#protocolError("message exceeds the protocol bound");
|
|
137
|
+
const line = this.#bufferedBytes === 0
|
|
138
|
+
? part
|
|
139
|
+
: Buffer.concat([...this.#buffered, part]);
|
|
140
|
+
this.#buffered = [];
|
|
141
|
+
this.#bufferedBytes = 0;
|
|
142
|
+
start = nl + 1;
|
|
143
|
+
if (line.length > 0)
|
|
144
|
+
this.#message(line);
|
|
145
|
+
if (this.#closed)
|
|
146
|
+
return;
|
|
147
|
+
}
|
|
148
|
+
const rest = chunk.subarray(start);
|
|
149
|
+
if (rest.length === 0)
|
|
150
|
+
return;
|
|
151
|
+
if (this.#bufferedBytes + rest.length >= this.#maxMessage)
|
|
152
|
+
return this.#protocolError("message exceeds the protocol bound");
|
|
153
|
+
this.#buffered.push(Buffer.from(rest));
|
|
154
|
+
this.#bufferedBytes += rest.length;
|
|
155
|
+
}
|
|
156
|
+
#message(line) {
|
|
157
|
+
let m;
|
|
158
|
+
try {
|
|
159
|
+
m = JSON.parse(line.toString("utf8"));
|
|
160
|
+
}
|
|
161
|
+
catch {
|
|
162
|
+
return this.#protocolError("malformed message");
|
|
163
|
+
}
|
|
164
|
+
if (!matches(Message, m))
|
|
165
|
+
return this.#protocolError("malformed message");
|
|
166
|
+
const { id, method } = m;
|
|
167
|
+
if (method === CancelMethod) {
|
|
168
|
+
if (isRecord(m.params))
|
|
169
|
+
this.#cancels.get(JSON.stringify(m.params.id))?.abort();
|
|
170
|
+
}
|
|
171
|
+
else if (method !== undefined && method !== "" && isID(id)) {
|
|
172
|
+
// Refuse rather than queue: the reader also carries the responses
|
|
173
|
+
// in-flight handlers wait for, so blocking it would deadlock them.
|
|
174
|
+
const release = this.#admit(method);
|
|
175
|
+
if (release === undefined) {
|
|
176
|
+
this.#write({
|
|
177
|
+
jsonrpc: "2.0",
|
|
178
|
+
id,
|
|
179
|
+
error: {
|
|
180
|
+
code: codeApplication,
|
|
181
|
+
message: "too many requests in flight",
|
|
182
|
+
data: { code: Code.Overloaded },
|
|
183
|
+
},
|
|
184
|
+
});
|
|
185
|
+
return;
|
|
186
|
+
}
|
|
187
|
+
void this.#serve(id, method, m.params, release);
|
|
188
|
+
}
|
|
189
|
+
else if (method !== undefined && method !== "") {
|
|
190
|
+
// Other notifications are served without a reply.
|
|
191
|
+
void this.#handler(method, m.params, new AbortController().signal).catch(() => { });
|
|
192
|
+
}
|
|
193
|
+
else if (isID(id)) {
|
|
194
|
+
const key = JSON.stringify(id);
|
|
195
|
+
const p = this.#pending.get(key);
|
|
196
|
+
this.#pending.delete(key);
|
|
197
|
+
if (p === undefined)
|
|
198
|
+
return;
|
|
199
|
+
if (m.error !== undefined && m.error !== null)
|
|
200
|
+
p.reject(decodeError(m.error));
|
|
201
|
+
else
|
|
202
|
+
p.resolve(m.result);
|
|
203
|
+
}
|
|
204
|
+
else {
|
|
205
|
+
this.#protocolError("message is neither request nor response");
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
/** Takes the capacity a method is served from, or undefined when full. */
|
|
209
|
+
#admit(method) {
|
|
210
|
+
const lane = this.#lane(method);
|
|
211
|
+
if (lane === "held")
|
|
212
|
+
return () => { };
|
|
213
|
+
if (lane === "control" && this.#controlInflight < MaxControlInflight) {
|
|
214
|
+
this.#controlInflight++;
|
|
215
|
+
return () => void this.#controlInflight--;
|
|
216
|
+
}
|
|
217
|
+
if (this.#inflight >= this.#maxInflight)
|
|
218
|
+
return undefined;
|
|
219
|
+
this.#inflight++;
|
|
220
|
+
return () => void this.#inflight--;
|
|
221
|
+
}
|
|
222
|
+
async #serve(id, method, params, release) {
|
|
223
|
+
const key = JSON.stringify(id);
|
|
224
|
+
const abort = new AbortController();
|
|
225
|
+
this.#cancels.set(key, abort);
|
|
226
|
+
let reply;
|
|
227
|
+
try {
|
|
228
|
+
const result = await this.#handler(method, params, abort.signal);
|
|
229
|
+
reply = abort.signal.aborted
|
|
230
|
+
? { jsonrpc: "2.0", id, error: encodeError(new CancelledError(), true) }
|
|
231
|
+
: { jsonrpc: "2.0", id, result: result === undefined ? {} : result };
|
|
232
|
+
}
|
|
233
|
+
catch (err) {
|
|
234
|
+
reply = {
|
|
235
|
+
jsonrpc: "2.0",
|
|
236
|
+
id,
|
|
237
|
+
error: encodeError(err, abort.signal.aborted),
|
|
238
|
+
};
|
|
239
|
+
}
|
|
240
|
+
finally {
|
|
241
|
+
release();
|
|
242
|
+
this.#cancels.delete(key);
|
|
243
|
+
}
|
|
244
|
+
if (this.#closed)
|
|
245
|
+
return;
|
|
246
|
+
if (!this.#write(reply) && reply.error === undefined) {
|
|
247
|
+
// An oversized result is refused rather than closing the stream.
|
|
248
|
+
this.#write({
|
|
249
|
+
jsonrpc: "2.0",
|
|
250
|
+
id,
|
|
251
|
+
error: encodeError(new ProtocolError(Code.Invalid, "message exceeds the protocol bound"), false),
|
|
252
|
+
});
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
/** Writes one message; false when it is over the bound or unencodable. */
|
|
256
|
+
#write(m) {
|
|
257
|
+
if (this.#closed)
|
|
258
|
+
return false;
|
|
259
|
+
let data;
|
|
260
|
+
try {
|
|
261
|
+
data = Buffer.from(JSON.stringify(m) + "\n", "utf8");
|
|
262
|
+
}
|
|
263
|
+
catch {
|
|
264
|
+
return false;
|
|
265
|
+
}
|
|
266
|
+
if (data.length - 1 >= this.#maxMessage)
|
|
267
|
+
return false;
|
|
268
|
+
this.#out.write(data);
|
|
269
|
+
return true;
|
|
270
|
+
}
|
|
271
|
+
/**
|
|
272
|
+
* Sends a request and resolves with its result, undecoded. Aborting
|
|
273
|
+
* signal sends $/cancel and rejects at once with CancelledError.
|
|
274
|
+
*/
|
|
275
|
+
call(method, params = {}, signal) {
|
|
276
|
+
if (this.#closed)
|
|
277
|
+
return Promise.reject(new TransportError());
|
|
278
|
+
if (signal?.aborted)
|
|
279
|
+
return Promise.reject(new CancelledError());
|
|
280
|
+
const id = ++this.#next;
|
|
281
|
+
const key = JSON.stringify(id);
|
|
282
|
+
return new Promise((resolve, reject) => {
|
|
283
|
+
const onAbort = () => {
|
|
284
|
+
if (!this.#pending.delete(key))
|
|
285
|
+
return;
|
|
286
|
+
this.#write({ jsonrpc: "2.0", method: CancelMethod, params: { id } });
|
|
287
|
+
reject(new CancelledError());
|
|
288
|
+
};
|
|
289
|
+
this.#pending.set(key, {
|
|
290
|
+
resolve: (v) => {
|
|
291
|
+
signal?.removeEventListener("abort", onAbort);
|
|
292
|
+
resolve(v);
|
|
293
|
+
},
|
|
294
|
+
reject: (e) => {
|
|
295
|
+
signal?.removeEventListener("abort", onAbort);
|
|
296
|
+
reject(e);
|
|
297
|
+
},
|
|
298
|
+
});
|
|
299
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
300
|
+
if (!this.#write({ jsonrpc: "2.0", id, method, params })) {
|
|
301
|
+
this.#pending.delete(key);
|
|
302
|
+
signal?.removeEventListener("abort", onAbort);
|
|
303
|
+
reject(new ProtocolError(Code.Invalid, "message exceeds the protocol bound"));
|
|
304
|
+
}
|
|
305
|
+
});
|
|
306
|
+
}
|
|
307
|
+
/** Sends a notification (no response). */
|
|
308
|
+
notify(method, params = {}) {
|
|
309
|
+
this.#write({ jsonrpc: "2.0", method, params });
|
|
310
|
+
}
|
|
311
|
+
}
|
|
312
|
+
function encodeError(err, cancelled) {
|
|
313
|
+
if (cancelled)
|
|
314
|
+
return {
|
|
315
|
+
code: codeCancelled,
|
|
316
|
+
message: "request cancelled",
|
|
317
|
+
data: { code: Code.Cancelled },
|
|
318
|
+
};
|
|
319
|
+
const e = encode(err);
|
|
320
|
+
if (e.code === Code.Cancelled)
|
|
321
|
+
return { code: codeCancelled, message: e.message, data: { code: e.code } };
|
|
322
|
+
const code = e.code === Code.MethodNotFound
|
|
323
|
+
? codeMethodNotFound
|
|
324
|
+
: e.code === Code.Internal
|
|
325
|
+
? codeInternal
|
|
326
|
+
: codeApplication;
|
|
327
|
+
const data = { code: e.code };
|
|
328
|
+
if (e.resetAt !== undefined)
|
|
329
|
+
data.reset_at = e.resetAt;
|
|
330
|
+
if (e.diagnostics !== undefined)
|
|
331
|
+
data.diagnostics = e.diagnostics;
|
|
332
|
+
return { code, message: e.message, data };
|
|
333
|
+
}
|
|
334
|
+
function decodeError(e) {
|
|
335
|
+
if (e.code === codeCancelled)
|
|
336
|
+
return new CancelledError();
|
|
337
|
+
if (e.data?.code)
|
|
338
|
+
return decode(e.data.code, e.message, e.data.reset_at, e.data.diagnostics?.map(({ path, code, message }) => ({
|
|
339
|
+
path,
|
|
340
|
+
code,
|
|
341
|
+
message,
|
|
342
|
+
})));
|
|
343
|
+
if (e.code === codeMethodNotFound)
|
|
344
|
+
return new ProtocolError(Code.MethodNotFound, e.message);
|
|
345
|
+
if (e.code === codeInvalidParams ||
|
|
346
|
+
e.code === codeInvalidRequest ||
|
|
347
|
+
e.code === codeParse)
|
|
348
|
+
return new ProtocolError(Code.Invalid, e.message);
|
|
349
|
+
return new ProtocolError(Code.Internal, "internal error");
|
|
350
|
+
}
|
package/dist/schema.d.ts
ADDED
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
import type { ConfigDiagnostic } from "./errors.js";
|
|
2
|
+
declare const phantom: unique symbol;
|
|
3
|
+
declare const optionalMark: unique symbol;
|
|
4
|
+
/** A JSON Schema that accepts values of type T. */
|
|
5
|
+
export type Type<T> = Readonly<Record<string, unknown>> & {
|
|
6
|
+
readonly [phantom]?: T;
|
|
7
|
+
};
|
|
8
|
+
/** The type of the values a schema accepts. */
|
|
9
|
+
export type Infer<S> = S extends Type<infer T> ? T : never;
|
|
10
|
+
type Optional<T> = Type<T> & {
|
|
11
|
+
readonly [optionalMark]: true;
|
|
12
|
+
};
|
|
13
|
+
type Shape = Record<string, Type<unknown>>;
|
|
14
|
+
type RequiredKeys<S extends Shape> = {
|
|
15
|
+
[K in keyof S]: S[K] extends {
|
|
16
|
+
readonly [optionalMark]: true;
|
|
17
|
+
} ? never : K;
|
|
18
|
+
}[keyof S];
|
|
19
|
+
type Flatten<T> = {
|
|
20
|
+
[K in keyof T]: T[K];
|
|
21
|
+
} & {};
|
|
22
|
+
type ObjectOf<S extends Shape> = Flatten<{
|
|
23
|
+
[K in RequiredKeys<S>]: Infer<S[K]>;
|
|
24
|
+
} & {
|
|
25
|
+
[K in Exclude<keyof S, RequiredKeys<S>>]?: Infer<S[K]>;
|
|
26
|
+
}>;
|
|
27
|
+
interface Doc {
|
|
28
|
+
/** Becomes the schema's description, which an agent reads in its toolbelt. */
|
|
29
|
+
description?: string;
|
|
30
|
+
}
|
|
31
|
+
interface ObjectOptions extends Doc {
|
|
32
|
+
/** Accept fields the shape doesn't name, and ignore them. */
|
|
33
|
+
open?: boolean;
|
|
34
|
+
}
|
|
35
|
+
export declare const t: {
|
|
36
|
+
string(o?: Doc & {
|
|
37
|
+
format?: string;
|
|
38
|
+
}): Type<string>;
|
|
39
|
+
/** One of the given strings. */
|
|
40
|
+
enum<const V extends readonly [string, ...string[]]>(values: V, o?: Doc): Type<V[number]>;
|
|
41
|
+
integer(o?: Doc): Type<number>;
|
|
42
|
+
number(o?: Doc): Type<number>;
|
|
43
|
+
boolean(o?: Doc): Type<boolean>;
|
|
44
|
+
/** Exactly this value: tells apart the members of a union. */
|
|
45
|
+
literal<const V extends string | number | boolean>(value: V, o?: Doc): Type<V>;
|
|
46
|
+
array<T>(items: Type<T>, o?: Doc): Type<T[]>;
|
|
47
|
+
/** An object of these fields; each is required unless t.optional. */
|
|
48
|
+
object<S extends Shape>(shape: S, o?: ObjectOptions): Type<ObjectOf<S>>;
|
|
49
|
+
/** An object with any keys, each holding a value of one schema. */
|
|
50
|
+
record<T>(values: Type<T>, o?: Doc): Type<Record<string, T>>;
|
|
51
|
+
/** A field that may be left out. */
|
|
52
|
+
optional<T>(inner: Type<T>): Optional<T>;
|
|
53
|
+
/** inner, or null (Go sends a nil slice or map as null). */
|
|
54
|
+
nullable<T>(inner: Type<T>): Type<T | null>;
|
|
55
|
+
/** Any JSON value, passed through as it is. */
|
|
56
|
+
any(o?: Doc): Type<unknown>;
|
|
57
|
+
};
|
|
58
|
+
/** Reports whether v is a JSON object (not null, not an array). */
|
|
59
|
+
export declare function isRecord(v: unknown): v is Record<string, unknown>;
|
|
60
|
+
/** Reports whether value matches schema, narrowing it to the schema's type. */
|
|
61
|
+
export declare function matches<S extends Type<unknown>>(schema: S, value: unknown): value is Infer<S>;
|
|
62
|
+
/** Why value does not match schema, or undefined when it does. */
|
|
63
|
+
export declare function check(schema: Readonly<Record<string, unknown>>, value: unknown, path?: string): string | undefined;
|
|
64
|
+
/**
|
|
65
|
+
* What about value does not match schema, as config diagnostics: each at
|
|
66
|
+
* its field's JSON pointer, with code invalid_type, invalid_value,
|
|
67
|
+
* missing_field or unknown_field. Empty when it matches. Messages never
|
|
68
|
+
* quote the value.
|
|
69
|
+
*/
|
|
70
|
+
export declare function diagnose(schema: Readonly<Record<string, unknown>>, value: unknown, path?: string): ConfigDiagnostic[];
|
|
71
|
+
export {};
|
package/dist/schema.js
ADDED
|
@@ -0,0 +1,252 @@
|
|
|
1
|
+
// Schemas that are also types. `t` builds a JSON Schema, and Infer gives the
|
|
2
|
+
// TypeScript type of the values it accepts, so a declaration and its type
|
|
3
|
+
// cannot disagree. The SDK decodes everything that crosses the wire through
|
|
4
|
+
// one: an operation's input (strictly, as the Go SDK does), an entry's
|
|
5
|
+
// config, and the host's own messages (openly, so a newer host's extra
|
|
6
|
+
// fields are ignored rather than refused).
|
|
7
|
+
// Symbol keys never reach JSON, so the marks stay out of the manifest.
|
|
8
|
+
const optionalMark = Symbol("optional");
|
|
9
|
+
function withDoc(schema, o) {
|
|
10
|
+
return o?.description === undefined
|
|
11
|
+
? schema
|
|
12
|
+
: { ...schema, description: o.description };
|
|
13
|
+
}
|
|
14
|
+
function isOptional(s) {
|
|
15
|
+
return optionalMark in s;
|
|
16
|
+
}
|
|
17
|
+
export const t = {
|
|
18
|
+
string(o) {
|
|
19
|
+
return withDoc(o?.format === undefined
|
|
20
|
+
? { type: "string" }
|
|
21
|
+
: { type: "string", format: o.format }, o);
|
|
22
|
+
},
|
|
23
|
+
/** One of the given strings. */
|
|
24
|
+
enum(values, o) {
|
|
25
|
+
return withDoc({ type: "string", enum: [...values] }, o);
|
|
26
|
+
},
|
|
27
|
+
integer(o) {
|
|
28
|
+
return withDoc({ type: "integer" }, o);
|
|
29
|
+
},
|
|
30
|
+
number(o) {
|
|
31
|
+
return withDoc({ type: "number" }, o);
|
|
32
|
+
},
|
|
33
|
+
boolean(o) {
|
|
34
|
+
return withDoc({ type: "boolean" }, o);
|
|
35
|
+
},
|
|
36
|
+
/** Exactly this value: tells apart the members of a union. */
|
|
37
|
+
literal(value, o) {
|
|
38
|
+
return withDoc({ const: value }, o);
|
|
39
|
+
},
|
|
40
|
+
array(items, o) {
|
|
41
|
+
return withDoc({ type: "array", items }, o);
|
|
42
|
+
},
|
|
43
|
+
/** An object of these fields; each is required unless t.optional. */
|
|
44
|
+
object(shape, o) {
|
|
45
|
+
const required = Object.keys(shape).filter((k) => {
|
|
46
|
+
const field = shape[k];
|
|
47
|
+
return field !== undefined && !isOptional(field);
|
|
48
|
+
});
|
|
49
|
+
const s = { type: "object", properties: shape };
|
|
50
|
+
if (!o?.open)
|
|
51
|
+
s.additionalProperties = false;
|
|
52
|
+
if (required.length > 0)
|
|
53
|
+
s.required = required;
|
|
54
|
+
return withDoc(s, o);
|
|
55
|
+
},
|
|
56
|
+
/** An object with any keys, each holding a value of one schema. */
|
|
57
|
+
record(values, o) {
|
|
58
|
+
return withDoc({ type: "object", additionalProperties: values }, o);
|
|
59
|
+
},
|
|
60
|
+
/** A field that may be left out. */
|
|
61
|
+
optional(inner) {
|
|
62
|
+
return { ...inner, [optionalMark]: true };
|
|
63
|
+
},
|
|
64
|
+
/** inner, or null (Go sends a nil slice or map as null). */
|
|
65
|
+
nullable(inner) {
|
|
66
|
+
return { anyOf: [inner, { type: "null" }] };
|
|
67
|
+
},
|
|
68
|
+
/** Any JSON value, passed through as it is. */
|
|
69
|
+
any(o) {
|
|
70
|
+
return withDoc({}, o);
|
|
71
|
+
},
|
|
72
|
+
};
|
|
73
|
+
/** Reports whether v is a JSON object (not null, not an array). */
|
|
74
|
+
export function isRecord(v) {
|
|
75
|
+
return typeof v === "object" && v !== null && !Array.isArray(v);
|
|
76
|
+
}
|
|
77
|
+
/** Reports whether value matches schema, narrowing it to the schema's type. */
|
|
78
|
+
export function matches(schema, value) {
|
|
79
|
+
return check(schema, value) === undefined;
|
|
80
|
+
}
|
|
81
|
+
/** Why value does not match schema, or undefined when it does. */
|
|
82
|
+
export function check(schema, value, path = "") {
|
|
83
|
+
const field = path === "" ? "the input" : `field "${path}"`;
|
|
84
|
+
const wrongType = `${field} has the wrong type (got a JSON ${jsonKind(value)})`;
|
|
85
|
+
if (Array.isArray(schema.anyOf)) {
|
|
86
|
+
const options = schema.anyOf.filter(isRecord);
|
|
87
|
+
return options.some((s) => check(s, value, path) === undefined)
|
|
88
|
+
? undefined
|
|
89
|
+
: wrongType;
|
|
90
|
+
}
|
|
91
|
+
if ("const" in schema && value !== schema.const)
|
|
92
|
+
return `${field} must be ${JSON.stringify(schema.const)}`;
|
|
93
|
+
switch (schema.type) {
|
|
94
|
+
case "null":
|
|
95
|
+
return value === null ? undefined : wrongType;
|
|
96
|
+
case "string":
|
|
97
|
+
if (typeof value !== "string")
|
|
98
|
+
return wrongType;
|
|
99
|
+
if (Array.isArray(schema.enum) && !schema.enum.includes(value))
|
|
100
|
+
return `${field} must be one of ${schema.enum.map((v) => JSON.stringify(v)).join(", ")}`;
|
|
101
|
+
return undefined;
|
|
102
|
+
case "integer":
|
|
103
|
+
return typeof value === "number" && Number.isInteger(value)
|
|
104
|
+
? undefined
|
|
105
|
+
: wrongType;
|
|
106
|
+
case "number":
|
|
107
|
+
return typeof value === "number" ? undefined : wrongType;
|
|
108
|
+
case "boolean":
|
|
109
|
+
return typeof value === "boolean" ? undefined : wrongType;
|
|
110
|
+
case "array": {
|
|
111
|
+
if (!Array.isArray(value))
|
|
112
|
+
return wrongType;
|
|
113
|
+
const items = isRecord(schema.items) ? schema.items : {};
|
|
114
|
+
for (const [i, item] of value.entries()) {
|
|
115
|
+
const why = check(items, item, `${path}[${i}]`);
|
|
116
|
+
if (why !== undefined)
|
|
117
|
+
return why;
|
|
118
|
+
}
|
|
119
|
+
return undefined;
|
|
120
|
+
}
|
|
121
|
+
case "object":
|
|
122
|
+
return checkObject(schema, value, path, wrongType);
|
|
123
|
+
default:
|
|
124
|
+
return undefined;
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
function checkObject(schema, value, path, wrongType) {
|
|
128
|
+
if (!isRecord(value))
|
|
129
|
+
return path === "" ? "the input must be a JSON object" : wrongType;
|
|
130
|
+
const props = isRecord(schema.properties) ? schema.properties : {};
|
|
131
|
+
const required = Array.isArray(schema.required) ? schema.required : [];
|
|
132
|
+
for (const k of required) {
|
|
133
|
+
if (typeof k === "string" && !(k in value))
|
|
134
|
+
return `missing field "${join(path, k)}"`;
|
|
135
|
+
}
|
|
136
|
+
for (const [k, v] of Object.entries(value)) {
|
|
137
|
+
const p = props[k];
|
|
138
|
+
if (isRecord(p)) {
|
|
139
|
+
const why = check(p, v, join(path, k));
|
|
140
|
+
if (why !== undefined)
|
|
141
|
+
return why;
|
|
142
|
+
}
|
|
143
|
+
else if (schema.additionalProperties === false) {
|
|
144
|
+
return `unknown field "${join(path, k)}"`;
|
|
145
|
+
}
|
|
146
|
+
else if (isRecord(schema.additionalProperties)) {
|
|
147
|
+
const why = check(schema.additionalProperties, v, join(path, k));
|
|
148
|
+
if (why !== undefined)
|
|
149
|
+
return why;
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
return undefined;
|
|
153
|
+
}
|
|
154
|
+
/**
|
|
155
|
+
* What about value does not match schema, as config diagnostics: each at
|
|
156
|
+
* its field's JSON pointer, with code invalid_type, invalid_value,
|
|
157
|
+
* missing_field or unknown_field. Empty when it matches. Messages never
|
|
158
|
+
* quote the value.
|
|
159
|
+
*/
|
|
160
|
+
export function diagnose(schema, value, path = "") {
|
|
161
|
+
const wrong = (what) => [
|
|
162
|
+
{ path, code: "invalid_type", message: `must be ${what}` },
|
|
163
|
+
];
|
|
164
|
+
if (Array.isArray(schema.anyOf)) {
|
|
165
|
+
const options = schema.anyOf.filter(isRecord);
|
|
166
|
+
return options.some((s) => check(s, value) === undefined)
|
|
167
|
+
? []
|
|
168
|
+
: [{ path, code: "invalid_type", message: "has the wrong type" }];
|
|
169
|
+
}
|
|
170
|
+
if ("const" in schema && value !== schema.const)
|
|
171
|
+
return [
|
|
172
|
+
{
|
|
173
|
+
path,
|
|
174
|
+
code: "invalid_value",
|
|
175
|
+
message: `must be ${JSON.stringify(schema.const)}`,
|
|
176
|
+
},
|
|
177
|
+
];
|
|
178
|
+
switch (schema.type) {
|
|
179
|
+
case "null":
|
|
180
|
+
return value === null ? [] : wrong("null");
|
|
181
|
+
case "string":
|
|
182
|
+
if (typeof value !== "string")
|
|
183
|
+
return wrong("a string");
|
|
184
|
+
if (Array.isArray(schema.enum) && !schema.enum.includes(value))
|
|
185
|
+
return [
|
|
186
|
+
{
|
|
187
|
+
path,
|
|
188
|
+
code: "invalid_value",
|
|
189
|
+
message: `must be one of ${schema.enum.map((v) => JSON.stringify(v)).join(", ")}`,
|
|
190
|
+
},
|
|
191
|
+
];
|
|
192
|
+
return [];
|
|
193
|
+
case "integer":
|
|
194
|
+
return typeof value === "number" && Number.isInteger(value)
|
|
195
|
+
? []
|
|
196
|
+
: wrong("a whole number");
|
|
197
|
+
case "number":
|
|
198
|
+
return typeof value === "number" ? [] : wrong("a number");
|
|
199
|
+
case "boolean":
|
|
200
|
+
return typeof value === "boolean" ? [] : wrong("true or false");
|
|
201
|
+
case "array": {
|
|
202
|
+
if (!Array.isArray(value))
|
|
203
|
+
return wrong("an array");
|
|
204
|
+
const items = isRecord(schema.items) ? schema.items : {};
|
|
205
|
+
return value.flatMap((item, i) => diagnose(items, item, pointer(path, i)));
|
|
206
|
+
}
|
|
207
|
+
case "object": {
|
|
208
|
+
if (!isRecord(value))
|
|
209
|
+
return wrong("an object");
|
|
210
|
+
const props = isRecord(schema.properties) ? schema.properties : {};
|
|
211
|
+
const required = Array.isArray(schema.required) ? schema.required : [];
|
|
212
|
+
const out = [];
|
|
213
|
+
for (const k of required) {
|
|
214
|
+
if (typeof k === "string" && !(k in value))
|
|
215
|
+
out.push({
|
|
216
|
+
path: pointer(path, k),
|
|
217
|
+
code: "missing_field",
|
|
218
|
+
message: "required field is missing",
|
|
219
|
+
});
|
|
220
|
+
}
|
|
221
|
+
for (const [k, v] of Object.entries(value)) {
|
|
222
|
+
const p = props[k];
|
|
223
|
+
if (isRecord(p))
|
|
224
|
+
out.push(...diagnose(p, v, pointer(path, k)));
|
|
225
|
+
else if (schema.additionalProperties === false)
|
|
226
|
+
out.push({
|
|
227
|
+
path: pointer(path, k),
|
|
228
|
+
code: "unknown_field",
|
|
229
|
+
message: `unknown field; allowed fields are ${Object.keys(props).join(", ")}`,
|
|
230
|
+
});
|
|
231
|
+
else if (isRecord(schema.additionalProperties))
|
|
232
|
+
out.push(...diagnose(schema.additionalProperties, v, pointer(path, k)));
|
|
233
|
+
}
|
|
234
|
+
return out;
|
|
235
|
+
}
|
|
236
|
+
default:
|
|
237
|
+
return [];
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
function pointer(path, key) {
|
|
241
|
+
return `${path}/${String(key).replaceAll("~", "~0").replaceAll("/", "~1")}`;
|
|
242
|
+
}
|
|
243
|
+
function join(path, key) {
|
|
244
|
+
return path === "" ? key : `${path}.${key}`;
|
|
245
|
+
}
|
|
246
|
+
function jsonKind(v) {
|
|
247
|
+
if (v === null)
|
|
248
|
+
return "null";
|
|
249
|
+
if (Array.isArray(v))
|
|
250
|
+
return "array";
|
|
251
|
+
return typeof v === "object" ? "object" : typeof v;
|
|
252
|
+
}
|