@nyte-ai/protocol 0.0.0-stage → 0.0.18
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 +22 -2
- package/THIRD-PARTY-NOTICES.md +800 -0
- package/dist/chunks/client-053qg1fq.js +165 -0
- package/dist/chunks/client-3sbyne3r.js +22 -0
- package/dist/chunks/client-5xm0heem.js +185 -0
- package/dist/chunks/client-624vz0q1.js +155 -0
- package/dist/chunks/client-b8brz84x.js +113 -0
- package/dist/chunks/client-eggvt9rc.js +36 -0
- package/dist/chunks/client-hrkzqw6w.js +21 -0
- package/dist/chunks/client-kq4yq8n4.js +305 -0
- package/dist/chunks/client-rk08pxm6.js +12 -0
- package/dist/chunks/client-wffhcyad.js +387 -0
- package/dist/chunks/client-x7k53ygp.js +0 -0
- package/dist/chunks/client-xscg1xbf.js +44 -0
- package/dist/src/client.d.ts +25 -0
- package/dist/src/client.js +11 -0
- package/dist/src/codec.d.ts +15 -0
- package/dist/src/codec.js +19 -0
- package/dist/src/declarations.d.ts +25 -0
- package/dist/src/declarations.js +1 -0
- package/dist/src/digest.d.ts +2 -0
- package/dist/src/digest.js +6 -0
- package/dist/src/index.d.ts +11 -0
- package/dist/src/index.js +98 -0
- package/dist/src/json.d.ts +2 -0
- package/dist/src/json.js +6 -0
- package/dist/src/raw-parts.d.ts +10 -0
- package/dist/src/raw-parts.js +6 -0
- package/dist/src/stream-buffer.d.ts +7 -0
- package/dist/src/stream-buffer.js +6 -0
- package/dist/src/stream-channel.d.ts +27 -0
- package/dist/src/stream-channel.js +16 -0
- package/dist/src/stream-client.d.ts +7 -0
- package/dist/src/stream-client.js +10 -0
- package/dist/src/streams.d.ts +2 -0
- package/dist/src/streams.js +8 -0
- package/dist/src/view-frames.d.ts +5 -0
- package/dist/src/view-frames.js +9 -0
- package/dist/src/wire.d.ts +46 -0
- package/dist/src/wire.js +35 -0
- package/package.json +44 -3
|
@@ -0,0 +1,305 @@
|
|
|
1
|
+
import {
|
|
2
|
+
parseJson2
|
|
3
|
+
} from "./client-rk08pxm6.js";
|
|
4
|
+
|
|
5
|
+
// src/wire.ts
|
|
6
|
+
import { isJsonObject, SdkError, SdkErrorWireSchema, SdkErrorWireType } from "@nyte-ai/schema";
|
|
7
|
+
import { dev } from "@nyte-ai/core";
|
|
8
|
+
var errorStatus2 = {
|
|
9
|
+
invalid: 400,
|
|
10
|
+
unauthenticated: 401,
|
|
11
|
+
denied: 403,
|
|
12
|
+
unknown: 404,
|
|
13
|
+
stale: 409,
|
|
14
|
+
internal: 500,
|
|
15
|
+
unavailable: 503
|
|
16
|
+
};
|
|
17
|
+
var INPUT_HEADER2 = "X-Nyte-Input";
|
|
18
|
+
var HOST_HEADER2 = "X-Nyte-Host";
|
|
19
|
+
var OPERATIONS_HEADER2 = "X-Nyte-Operations";
|
|
20
|
+
var DATA = 0;
|
|
21
|
+
var CONTROL = 1;
|
|
22
|
+
function encodeError2(error) {
|
|
23
|
+
return {
|
|
24
|
+
code: error.code,
|
|
25
|
+
message: error.message,
|
|
26
|
+
hostId: error.hostId,
|
|
27
|
+
issues: error.issues,
|
|
28
|
+
correlation: error.correlation
|
|
29
|
+
};
|
|
30
|
+
}
|
|
31
|
+
function decodeError2(value, status) {
|
|
32
|
+
const result = SdkErrorWireSchema["~standard"].validate(value);
|
|
33
|
+
if (result instanceof Promise || result.issues !== undefined)
|
|
34
|
+
return new SdkError(status === undefined ? "internal" : statusCode2(status), typeof value === "string" && value !== "" ? value : "The host answered with an error it did not describe.");
|
|
35
|
+
const wire = result.value;
|
|
36
|
+
return new SdkError(wire.code, wire.message, {
|
|
37
|
+
hostId: wire.hostId,
|
|
38
|
+
issues: wire.issues,
|
|
39
|
+
correlation: wire.correlation
|
|
40
|
+
});
|
|
41
|
+
}
|
|
42
|
+
function statusCode2(status) {
|
|
43
|
+
if (status === 413)
|
|
44
|
+
return "invalid";
|
|
45
|
+
return SdkErrorWireType.properties.code.enum.find((code) => errorStatus2[code] === status) ?? "internal";
|
|
46
|
+
}
|
|
47
|
+
function sseFrames2(source, options) {
|
|
48
|
+
const iterator = source[Symbol.asyncIterator]();
|
|
49
|
+
const encoder = new TextEncoder;
|
|
50
|
+
let timer;
|
|
51
|
+
return new ReadableStream({
|
|
52
|
+
start(controller) {
|
|
53
|
+
const every = options?.heartbeatMs;
|
|
54
|
+
if (every !== undefined)
|
|
55
|
+
timer = setInterval(() => controller.enqueue(encoder.encode(`: ping
|
|
56
|
+
|
|
57
|
+
`)), every);
|
|
58
|
+
},
|
|
59
|
+
async pull(controller) {
|
|
60
|
+
try {
|
|
61
|
+
const next = await iterator.next();
|
|
62
|
+
if (next.done === true) {
|
|
63
|
+
clearInterval(timer);
|
|
64
|
+
controller.close();
|
|
65
|
+
return;
|
|
66
|
+
}
|
|
67
|
+
controller.enqueue(encoder.encode(`data: ${JSON.stringify(next.value)}
|
|
68
|
+
|
|
69
|
+
`));
|
|
70
|
+
} catch (error) {
|
|
71
|
+
clearInterval(timer);
|
|
72
|
+
const wire = JSON.stringify(encodeError2(asSdkError2(error)));
|
|
73
|
+
controller.enqueue(encoder.encode(`event: error
|
|
74
|
+
data: ${wire}
|
|
75
|
+
|
|
76
|
+
`));
|
|
77
|
+
controller.close();
|
|
78
|
+
}
|
|
79
|
+
},
|
|
80
|
+
async cancel() {
|
|
81
|
+
clearInterval(timer);
|
|
82
|
+
await iterator.return?.();
|
|
83
|
+
}
|
|
84
|
+
});
|
|
85
|
+
}
|
|
86
|
+
async function* parseSse2(stream) {
|
|
87
|
+
const reader = stream.getReader();
|
|
88
|
+
const decoder = new TextDecoder;
|
|
89
|
+
let buffer = "";
|
|
90
|
+
try {
|
|
91
|
+
for (;; ) {
|
|
92
|
+
const read = await reader.read();
|
|
93
|
+
buffer += read.done ? decoder.decode() : decoder.decode(read.value, { stream: true });
|
|
94
|
+
const blocks = buffer.replace(/\r\n?/g, `
|
|
95
|
+
`).split(`
|
|
96
|
+
|
|
97
|
+
`);
|
|
98
|
+
buffer = read.done ? "" : blocks.pop() ?? "";
|
|
99
|
+
for (const block of blocks) {
|
|
100
|
+
const frame = parseEventBlock(block);
|
|
101
|
+
if (frame !== null)
|
|
102
|
+
yield frame.data;
|
|
103
|
+
}
|
|
104
|
+
if (read.done)
|
|
105
|
+
return;
|
|
106
|
+
}
|
|
107
|
+
} finally {
|
|
108
|
+
await reader.cancel().catch(() => {
|
|
109
|
+
return;
|
|
110
|
+
});
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
function octetStream2(body, signal) {
|
|
114
|
+
const { reader } = body;
|
|
115
|
+
const chunks = reader.chunks()[Symbol.asyncIterator]();
|
|
116
|
+
const headers = new Headers(body.headers);
|
|
117
|
+
headers.set("Content-Type", "application/octet-stream");
|
|
118
|
+
if (reader.mime !== null)
|
|
119
|
+
headers.set("X-Nyte-Mime", reader.mime);
|
|
120
|
+
if (reader.size !== null)
|
|
121
|
+
headers.set("Content-Length", String(reader.size));
|
|
122
|
+
let closing = null;
|
|
123
|
+
const close = () => {
|
|
124
|
+
closing ??= (async () => {
|
|
125
|
+
try {
|
|
126
|
+
await reader.close();
|
|
127
|
+
} finally {
|
|
128
|
+
await chunks.return?.();
|
|
129
|
+
}
|
|
130
|
+
})();
|
|
131
|
+
return closing;
|
|
132
|
+
};
|
|
133
|
+
const stream = new ReadableStream({
|
|
134
|
+
start(controller) {
|
|
135
|
+
const abort = () => {
|
|
136
|
+
controller.error(signal.reason);
|
|
137
|
+
close().catch((error) => {
|
|
138
|
+
dev("protocol", "byte reader close failed", {
|
|
139
|
+
message: error instanceof Error ? error.message : String(error)
|
|
140
|
+
});
|
|
141
|
+
});
|
|
142
|
+
};
|
|
143
|
+
if (signal.aborted)
|
|
144
|
+
abort();
|
|
145
|
+
else
|
|
146
|
+
signal.addEventListener("abort", abort, { once: true });
|
|
147
|
+
},
|
|
148
|
+
async pull(controller) {
|
|
149
|
+
try {
|
|
150
|
+
const next = await chunks.next();
|
|
151
|
+
if (next.done === true) {
|
|
152
|
+
controller.close();
|
|
153
|
+
await close();
|
|
154
|
+
return;
|
|
155
|
+
}
|
|
156
|
+
controller.enqueue(next.value);
|
|
157
|
+
} catch (error) {
|
|
158
|
+
controller.error(error);
|
|
159
|
+
await close();
|
|
160
|
+
}
|
|
161
|
+
},
|
|
162
|
+
cancel: close
|
|
163
|
+
});
|
|
164
|
+
return new Response(stream, { status: 200, headers });
|
|
165
|
+
}
|
|
166
|
+
function outputFrames2(source) {
|
|
167
|
+
const iterator = source[Symbol.asyncIterator]();
|
|
168
|
+
const encoder = new TextEncoder;
|
|
169
|
+
return new ReadableStream({
|
|
170
|
+
async pull(controller) {
|
|
171
|
+
try {
|
|
172
|
+
const next = await iterator.next();
|
|
173
|
+
if (next.done === true) {
|
|
174
|
+
controller.close();
|
|
175
|
+
return;
|
|
176
|
+
}
|
|
177
|
+
const frame = next.value;
|
|
178
|
+
controller.enqueue(frame.kind === "bytes" ? framed(DATA, frame.data) : framed(CONTROL, encoder.encode(JSON.stringify(frame))));
|
|
179
|
+
} catch (error) {
|
|
180
|
+
const failure = { kind: "error", error: encodeError2(asSdkError2(error)) };
|
|
181
|
+
controller.enqueue(framed(CONTROL, encoder.encode(JSON.stringify(failure))));
|
|
182
|
+
controller.close();
|
|
183
|
+
}
|
|
184
|
+
},
|
|
185
|
+
async cancel() {
|
|
186
|
+
await iterator.return?.();
|
|
187
|
+
}
|
|
188
|
+
});
|
|
189
|
+
}
|
|
190
|
+
async function* parseOutputFrames2(stream) {
|
|
191
|
+
const reader = stream.getReader();
|
|
192
|
+
const decoder = new TextDecoder;
|
|
193
|
+
let buffer = new Uint8Array(0);
|
|
194
|
+
try {
|
|
195
|
+
for (;; ) {
|
|
196
|
+
const read = await reader.read();
|
|
197
|
+
if (read.done) {
|
|
198
|
+
if (buffer.byteLength > 0)
|
|
199
|
+
throw new SdkError("internal", "The output stream ended mid-frame.");
|
|
200
|
+
return;
|
|
201
|
+
}
|
|
202
|
+
buffer = joined(buffer, read.value);
|
|
203
|
+
while (buffer.byteLength >= 5) {
|
|
204
|
+
const length = new DataView(buffer.buffer, buffer.byteOffset, 5).getUint32(1);
|
|
205
|
+
if (buffer.byteLength < 5 + length)
|
|
206
|
+
break;
|
|
207
|
+
const tag = buffer[0];
|
|
208
|
+
const payload = buffer.slice(5, 5 + length);
|
|
209
|
+
buffer = buffer.slice(5 + length);
|
|
210
|
+
if (tag === DATA) {
|
|
211
|
+
yield { kind: "bytes", data: payload };
|
|
212
|
+
continue;
|
|
213
|
+
}
|
|
214
|
+
const control = decodeControl(parseJson2(decoder.decode(payload)));
|
|
215
|
+
if (control !== null)
|
|
216
|
+
yield control;
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
} finally {
|
|
220
|
+
await reader.cancel().catch(() => {
|
|
221
|
+
return;
|
|
222
|
+
});
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
function withInputHeader2(input, body) {
|
|
226
|
+
return {
|
|
227
|
+
method: "POST",
|
|
228
|
+
headers: { "Content-Type": "application/octet-stream", [INPUT_HEADER2]: base64url(input) },
|
|
229
|
+
...body instanceof ReadableStream ? { body, duplex: "half" } : {
|
|
230
|
+
body: body.buffer instanceof ArrayBuffer ? new Uint8Array(body.buffer, body.byteOffset, body.byteLength) : body.slice()
|
|
231
|
+
}
|
|
232
|
+
};
|
|
233
|
+
}
|
|
234
|
+
function readInputHeader2(request) {
|
|
235
|
+
const header = request.headers.get(INPUT_HEADER2);
|
|
236
|
+
if (header === null)
|
|
237
|
+
return null;
|
|
238
|
+
try {
|
|
239
|
+
const binary = atob(header.replace(/-/g, "+").replace(/_/g, "/"));
|
|
240
|
+
return parseJson2(new TextDecoder().decode(Uint8Array.from(binary, (char) => char.charCodeAt(0))));
|
|
241
|
+
} catch {
|
|
242
|
+
throw new SdkError("invalid", `${INPUT_HEADER2} is not base64url JSON.`);
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
function asSdkError2(error) {
|
|
246
|
+
if (error instanceof SdkError)
|
|
247
|
+
return error;
|
|
248
|
+
return new SdkError("internal", "The host failed to answer.", {
|
|
249
|
+
correlation: crypto.randomUUID()
|
|
250
|
+
});
|
|
251
|
+
}
|
|
252
|
+
function parseEventBlock(block) {
|
|
253
|
+
let event = "message";
|
|
254
|
+
const data = [];
|
|
255
|
+
for (const line of block.split(`
|
|
256
|
+
`)) {
|
|
257
|
+
if (line === "" || line.startsWith(":"))
|
|
258
|
+
continue;
|
|
259
|
+
const [field, ...rest] = line.split(":");
|
|
260
|
+
const value = rest.join(":").replace(/^ /, "");
|
|
261
|
+
if (field === "event")
|
|
262
|
+
event = value;
|
|
263
|
+
else if (field === "data")
|
|
264
|
+
data.push(value);
|
|
265
|
+
}
|
|
266
|
+
if (data.length === 0)
|
|
267
|
+
return null;
|
|
268
|
+
const json = parseJson2(data.join(`
|
|
269
|
+
`));
|
|
270
|
+
if (event === "error")
|
|
271
|
+
throw decodeError2(json);
|
|
272
|
+
return { data: json };
|
|
273
|
+
}
|
|
274
|
+
function decodeControl(value) {
|
|
275
|
+
if (!isJsonObject(value))
|
|
276
|
+
return null;
|
|
277
|
+
if (value.kind === "gap")
|
|
278
|
+
return { kind: "gap" };
|
|
279
|
+
if (value.kind === "exit")
|
|
280
|
+
return { kind: "exit", code: typeof value.code === "number" ? value.code : null };
|
|
281
|
+
if (value.kind === "error" && value.error !== undefined)
|
|
282
|
+
throw decodeError2(value.error);
|
|
283
|
+
return null;
|
|
284
|
+
}
|
|
285
|
+
function framed(tag, payload) {
|
|
286
|
+
const frame = new Uint8Array(5 + payload.byteLength);
|
|
287
|
+
frame[0] = tag;
|
|
288
|
+
new DataView(frame.buffer).setUint32(1, payload.byteLength);
|
|
289
|
+
frame.set(payload, 5);
|
|
290
|
+
return frame;
|
|
291
|
+
}
|
|
292
|
+
function joined(left, right) {
|
|
293
|
+
if (left.byteLength === 0)
|
|
294
|
+
return right;
|
|
295
|
+
const both = new Uint8Array(left.byteLength + right.byteLength);
|
|
296
|
+
both.set(left);
|
|
297
|
+
both.set(right, left.byteLength);
|
|
298
|
+
return both;
|
|
299
|
+
}
|
|
300
|
+
function base64url(input) {
|
|
301
|
+
const utf8 = encodeURIComponent(JSON.stringify(input)).replace(/%([0-9A-F]{2})/g, (_match, hex) => String.fromCharCode(Number.parseInt(hex, 16)));
|
|
302
|
+
return btoa(utf8).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
export { errorStatus2, INPUT_HEADER2, HOST_HEADER2, OPERATIONS_HEADER2, encodeError2, decodeError2, statusCode2, sseFrames2, parseSse2, octetStream2, outputFrames2, parseOutputFrames2, withInputHeader2, readInputHeader2, asSdkError2 };
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
// src/json.ts
|
|
2
|
+
import { isJson, SdkError } from "@nyte-ai/schema";
|
|
3
|
+
function parseJson2(text) {
|
|
4
|
+
try {
|
|
5
|
+
const value = JSON.parse(text);
|
|
6
|
+
if (isJson(value))
|
|
7
|
+
return value;
|
|
8
|
+
} catch {}
|
|
9
|
+
throw new SdkError("invalid", "The body is not JSON.");
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export { parseJson2 };
|
|
@@ -0,0 +1,387 @@
|
|
|
1
|
+
import {
|
|
2
|
+
rawPart2
|
|
3
|
+
} from "./client-eggvt9rc.js";
|
|
4
|
+
|
|
5
|
+
// src/codec.ts
|
|
6
|
+
import { Compile } from "typebox/compile";
|
|
7
|
+
import { Guard } from "typebox/guard";
|
|
8
|
+
import { OPERATIONS, SdkError } from "@nyte-ai/schema";
|
|
9
|
+
var INERT = { form: "inert" };
|
|
10
|
+
var PRIMITIVE_TYPES = new Set(["string", "number", "integer", "boolean", "null"]);
|
|
11
|
+
var VIEW_DEPTH = 2;
|
|
12
|
+
var rows = OPERATIONS;
|
|
13
|
+
var plans = new WeakMap;
|
|
14
|
+
var BYTE_ROWS = {
|
|
15
|
+
"connection.blob": true,
|
|
16
|
+
"files.bytes": true,
|
|
17
|
+
"page.capture": true
|
|
18
|
+
};
|
|
19
|
+
function namesOperation2(name) {
|
|
20
|
+
return Object.hasOwn(OPERATIONS, name);
|
|
21
|
+
}
|
|
22
|
+
function answersOnce2(name) {
|
|
23
|
+
const { kind } = OPERATIONS[name];
|
|
24
|
+
return kind === "query" || kind === "command" || kind === "receipt";
|
|
25
|
+
}
|
|
26
|
+
function answersBytes2(name) {
|
|
27
|
+
return Object.hasOwn(BYTE_ROWS, name);
|
|
28
|
+
}
|
|
29
|
+
function decodeInput2(name, value) {
|
|
30
|
+
const schema = rows[name].input;
|
|
31
|
+
const input = validated(schema, value);
|
|
32
|
+
const unknown = [];
|
|
33
|
+
collect(plan(schema), value, [], unknown);
|
|
34
|
+
if (unknown.length > 0)
|
|
35
|
+
throw new SdkError("invalid", `${name} does not take ${unknown.map(pointer).join(", ")}.`, {
|
|
36
|
+
issues: unknown.map((path) => ({ severity: "error", path, message: "Unknown field." }))
|
|
37
|
+
});
|
|
38
|
+
return input;
|
|
39
|
+
}
|
|
40
|
+
function encodeInput2(_name, input) {
|
|
41
|
+
return toJson(input) ?? null;
|
|
42
|
+
}
|
|
43
|
+
function encodeOutput2(name, value) {
|
|
44
|
+
return encode(plan(rows[name].output), value) ?? null;
|
|
45
|
+
}
|
|
46
|
+
function decodeOutput2(name, value) {
|
|
47
|
+
const schema = rows[name].output;
|
|
48
|
+
const result = schema["~standard"].validate(value);
|
|
49
|
+
if (!(result instanceof Promise) && result.issues === undefined)
|
|
50
|
+
return result.value;
|
|
51
|
+
return validated(schema, known(plan(schema), value, name === "head.watch" ? VIEW_DEPTH : null));
|
|
52
|
+
}
|
|
53
|
+
function validated(schema, value) {
|
|
54
|
+
const result = schema["~standard"].validate(value);
|
|
55
|
+
if (result instanceof Promise)
|
|
56
|
+
throw new SdkError("internal", "A wire schema is asynchronous.");
|
|
57
|
+
if (result.issues === undefined)
|
|
58
|
+
return result.value;
|
|
59
|
+
const issues = result.issues.map((issue) => ({
|
|
60
|
+
severity: "error",
|
|
61
|
+
path: (issue.path ?? []).map((segment) => {
|
|
62
|
+
const key = typeof segment === "object" ? segment.key : segment;
|
|
63
|
+
return typeof key === "number" ? key : String(key);
|
|
64
|
+
}),
|
|
65
|
+
message: issue.message
|
|
66
|
+
}));
|
|
67
|
+
throw new SdkError("invalid", issues.map((issue) => `${pointer(issue.path)}: ${issue.message}`).join("; "), { issues });
|
|
68
|
+
}
|
|
69
|
+
function plan(schema) {
|
|
70
|
+
const cached = plans.get(schema);
|
|
71
|
+
if (cached !== undefined)
|
|
72
|
+
return cached;
|
|
73
|
+
const built = compilePlan(schema["~standard"].jsonSchema.input({ target: "draft-2020-12" }), {}, new Map);
|
|
74
|
+
plans.set(schema, built);
|
|
75
|
+
return built;
|
|
76
|
+
}
|
|
77
|
+
function compilePlan(start, scope, memo) {
|
|
78
|
+
const resolved = resolve(start, scope);
|
|
79
|
+
if (resolved === null)
|
|
80
|
+
return INERT;
|
|
81
|
+
const { node, definitions } = resolved;
|
|
82
|
+
const cached = memo.get(node);
|
|
83
|
+
if (cached !== undefined)
|
|
84
|
+
return cached;
|
|
85
|
+
if (Guard.IsArray(node.anyOf)) {
|
|
86
|
+
const choice = { form: "choice", members: [], kinded: new Map, unkinded: [] };
|
|
87
|
+
memo.set(node, choice);
|
|
88
|
+
for (const entry of node.anyOf) {
|
|
89
|
+
const member = readNode(entry);
|
|
90
|
+
if (member === null)
|
|
91
|
+
continue;
|
|
92
|
+
let validator = null;
|
|
93
|
+
choice.members.push({
|
|
94
|
+
plan: compilePlan(member, definitions, memo),
|
|
95
|
+
kinds: readKinds(member, definitions, new Map),
|
|
96
|
+
check: (value) => (validator ??= Compile(definitions, member)).Check(value)
|
|
97
|
+
});
|
|
98
|
+
}
|
|
99
|
+
if (choice.members.every((candidate) => candidate.plan === INERT)) {
|
|
100
|
+
memo.set(node, INERT);
|
|
101
|
+
return INERT;
|
|
102
|
+
}
|
|
103
|
+
const kinds = new Set(choice.members.flatMap((candidate) => [...candidate.kinds ?? []]));
|
|
104
|
+
for (const kind of kinds)
|
|
105
|
+
choice.kinded.set(kind, choice.members.filter((candidate) => candidate.kinds?.has(kind) ?? true));
|
|
106
|
+
choice.unkinded.push(...choice.members.filter((candidate) => candidate.kinds === null));
|
|
107
|
+
return choice;
|
|
108
|
+
}
|
|
109
|
+
if (typeof node.type === "string" && PRIMITIVE_TYPES.has(node.type)) {
|
|
110
|
+
memo.set(node, INERT);
|
|
111
|
+
return INERT;
|
|
112
|
+
}
|
|
113
|
+
const declared = readNode(node.properties);
|
|
114
|
+
const properties = declared === null ? null : new Map;
|
|
115
|
+
const composite = {
|
|
116
|
+
form: "composite",
|
|
117
|
+
properties,
|
|
118
|
+
rest: null,
|
|
119
|
+
items: null,
|
|
120
|
+
nulled: []
|
|
121
|
+
};
|
|
122
|
+
memo.set(node, composite);
|
|
123
|
+
for (const [key, property] of Object.entries(declared ?? {})) {
|
|
124
|
+
const child = readNode(property);
|
|
125
|
+
if (child !== null)
|
|
126
|
+
properties?.set(key, compilePlan(child, definitions, memo));
|
|
127
|
+
}
|
|
128
|
+
const rest = readRest(node);
|
|
129
|
+
composite.rest = rest === null ? null : compilePlan(rest, definitions, memo);
|
|
130
|
+
const items = readNode(node.items);
|
|
131
|
+
if (items !== null) {
|
|
132
|
+
let validator = null;
|
|
133
|
+
composite.items = {
|
|
134
|
+
plan: compilePlan(items, definitions, memo),
|
|
135
|
+
kinds: readKinds(items, definitions, new Map),
|
|
136
|
+
reads: (value) => (validator ??= Compile(definitions, items)).Check(value)
|
|
137
|
+
};
|
|
138
|
+
}
|
|
139
|
+
for (const key of Guard.IsArray(node.required) ? node.required : []) {
|
|
140
|
+
if (typeof key !== "string" || declared === null || !Object.hasOwn(declared, key))
|
|
141
|
+
continue;
|
|
142
|
+
const property = readNode(declared[key]);
|
|
143
|
+
if (property !== null && accepts(property, definitions))
|
|
144
|
+
composite.nulled.push(key);
|
|
145
|
+
}
|
|
146
|
+
return composite;
|
|
147
|
+
}
|
|
148
|
+
function collect(plan, value, path, found) {
|
|
149
|
+
if (plan.form === "inert")
|
|
150
|
+
return;
|
|
151
|
+
if (plan.form === "choice") {
|
|
152
|
+
const member = select(plan, value);
|
|
153
|
+
if (member !== null)
|
|
154
|
+
collect(member, value, path, found);
|
|
155
|
+
return;
|
|
156
|
+
}
|
|
157
|
+
if (Guard.IsArray(value)) {
|
|
158
|
+
const { items } = plan;
|
|
159
|
+
if (items !== null)
|
|
160
|
+
for (const [index, item] of value.entries())
|
|
161
|
+
collect(items.plan, item, [...path, index], found);
|
|
162
|
+
return;
|
|
163
|
+
}
|
|
164
|
+
if (typeof value !== "object" || value === null)
|
|
165
|
+
return;
|
|
166
|
+
for (const [key, field] of Object.entries(value)) {
|
|
167
|
+
const known = plan.properties?.get(key) ?? plan.rest;
|
|
168
|
+
if (known === null)
|
|
169
|
+
found.push([...path, key]);
|
|
170
|
+
else
|
|
171
|
+
collect(known, field, [...path, key], found);
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
function encode(plan, value) {
|
|
175
|
+
if (plan.form === "inert" || value instanceof Uint8Array)
|
|
176
|
+
return toJson(value);
|
|
177
|
+
if (plan.form === "choice") {
|
|
178
|
+
if (!(value instanceof Map)) {
|
|
179
|
+
const candidates = candidatesFor(plan, readKind(value));
|
|
180
|
+
const [only] = candidates;
|
|
181
|
+
if (candidates.length === 0)
|
|
182
|
+
return toJson(value);
|
|
183
|
+
if (candidates.length === 1 && only !== undefined)
|
|
184
|
+
return encode(only.plan, value);
|
|
185
|
+
}
|
|
186
|
+
const json = toJson(value);
|
|
187
|
+
if (json === undefined)
|
|
188
|
+
return;
|
|
189
|
+
const member = select(plan, json);
|
|
190
|
+
return member === null ? json : encode(member, json);
|
|
191
|
+
}
|
|
192
|
+
if (Guard.IsArray(value) || value instanceof Set) {
|
|
193
|
+
const { items } = plan;
|
|
194
|
+
return items === null ? toJson(value) : Array.from(value, (item) => encode(items.plan, item) ?? null);
|
|
195
|
+
}
|
|
196
|
+
if (typeof value !== "object" || value === null)
|
|
197
|
+
return toJson(value);
|
|
198
|
+
const { properties, rest } = plan;
|
|
199
|
+
if (properties === null && rest === null)
|
|
200
|
+
return toJson(value);
|
|
201
|
+
const record = {};
|
|
202
|
+
const keep = (key, item) => {
|
|
203
|
+
const target = properties?.get(key) ?? rest;
|
|
204
|
+
const json = target === null ? undefined : encode(target, item);
|
|
205
|
+
if (json !== undefined)
|
|
206
|
+
put(record, key, json);
|
|
207
|
+
};
|
|
208
|
+
if (value instanceof Map)
|
|
209
|
+
for (const [key, item] of value)
|
|
210
|
+
keep(String(key), item);
|
|
211
|
+
else if (Guard.IsObjectNotArray(value))
|
|
212
|
+
for (const key of Object.keys(value))
|
|
213
|
+
keep(key, value[key]);
|
|
214
|
+
for (const key of plan.nulled)
|
|
215
|
+
if (!Object.hasOwn(record, key))
|
|
216
|
+
put(record, key, null);
|
|
217
|
+
return record;
|
|
218
|
+
}
|
|
219
|
+
function known(plan, value, positional) {
|
|
220
|
+
if (plan.form === "inert")
|
|
221
|
+
return value;
|
|
222
|
+
if (plan.form === "choice") {
|
|
223
|
+
const member = select(plan, value);
|
|
224
|
+
return member === null ? value : known(member, value, positional);
|
|
225
|
+
}
|
|
226
|
+
if (Guard.IsArray(value)) {
|
|
227
|
+
const { items } = plan;
|
|
228
|
+
if (items === null)
|
|
229
|
+
return value;
|
|
230
|
+
const { kinds, reads } = items;
|
|
231
|
+
const keeps = positional !== null && positional >= 0;
|
|
232
|
+
return value.flatMap((item) => {
|
|
233
|
+
const kind = readKind(item);
|
|
234
|
+
const listed = kinds === null || kind === undefined || kinds.has(kind);
|
|
235
|
+
const read = listed ? known(items.plan, item, null) : item;
|
|
236
|
+
if (listed && reads(read))
|
|
237
|
+
return [read];
|
|
238
|
+
const raw = rawPart2(item);
|
|
239
|
+
if (raw !== null && reads(raw))
|
|
240
|
+
return [raw];
|
|
241
|
+
return keeps ? [read] : [];
|
|
242
|
+
});
|
|
243
|
+
}
|
|
244
|
+
const { properties } = plan;
|
|
245
|
+
if (typeof value !== "object" || value === null || properties === null)
|
|
246
|
+
return value;
|
|
247
|
+
const inner = positional === null ? null : positional - 1;
|
|
248
|
+
return Object.fromEntries(Object.entries(value).map(([key, field]) => {
|
|
249
|
+
const property = properties.get(key);
|
|
250
|
+
return [key, property === undefined ? field : known(property, field, inner)];
|
|
251
|
+
}));
|
|
252
|
+
}
|
|
253
|
+
function select(choice, value) {
|
|
254
|
+
const candidates = candidatesFor(choice, readKind(value));
|
|
255
|
+
const [only] = candidates;
|
|
256
|
+
if (candidates.length === 1 && only !== undefined)
|
|
257
|
+
return only.plan;
|
|
258
|
+
return candidates.find((candidate) => candidate.check(value))?.plan ?? null;
|
|
259
|
+
}
|
|
260
|
+
function candidatesFor(choice, kind) {
|
|
261
|
+
if (kind === undefined)
|
|
262
|
+
return choice.members;
|
|
263
|
+
return choice.kinded.get(kind) ?? choice.unkinded;
|
|
264
|
+
}
|
|
265
|
+
function resolve(start, scope) {
|
|
266
|
+
let node = start;
|
|
267
|
+
let definitions = scope;
|
|
268
|
+
for (;; ) {
|
|
269
|
+
const local = readNode(node.$defs);
|
|
270
|
+
if (local !== null) {
|
|
271
|
+
const merged = Object.assign({}, definitions);
|
|
272
|
+
for (const [key, entry] of Object.entries(local)) {
|
|
273
|
+
const definition = readNode(entry);
|
|
274
|
+
if (definition !== null)
|
|
275
|
+
merged[key] = definition;
|
|
276
|
+
}
|
|
277
|
+
definitions = merged;
|
|
278
|
+
}
|
|
279
|
+
const ref = node.$ref;
|
|
280
|
+
if (typeof ref !== "string")
|
|
281
|
+
return { node, definitions };
|
|
282
|
+
if (ref === "Json")
|
|
283
|
+
return null;
|
|
284
|
+
const target = definitions[ref];
|
|
285
|
+
if (target === undefined)
|
|
286
|
+
return null;
|
|
287
|
+
node = target;
|
|
288
|
+
}
|
|
289
|
+
}
|
|
290
|
+
function readKinds(start, scope, seen) {
|
|
291
|
+
const resolved = resolve(start, scope);
|
|
292
|
+
if (resolved === null)
|
|
293
|
+
return null;
|
|
294
|
+
const { node, definitions } = resolved;
|
|
295
|
+
if (seen.has(node))
|
|
296
|
+
return seen.get(node) ?? null;
|
|
297
|
+
seen.set(node, null);
|
|
298
|
+
if (Guard.IsArray(node.anyOf)) {
|
|
299
|
+
const sets = node.anyOf.map((member) => {
|
|
300
|
+
const child = readNode(member);
|
|
301
|
+
return child === null ? null : readKinds(child, definitions, seen);
|
|
302
|
+
});
|
|
303
|
+
const kinds = sets.every((set) => set !== null) ? new Set(sets.flatMap((set) => [...set ?? []])) : null;
|
|
304
|
+
seen.set(node, kinds);
|
|
305
|
+
return kinds;
|
|
306
|
+
}
|
|
307
|
+
const kind = readNode(readNode(node.properties)?.kind);
|
|
308
|
+
if (kind === null)
|
|
309
|
+
return null;
|
|
310
|
+
const kinds = typeof kind.const === "string" ? new Set([kind.const]) : Guard.IsArray(kind.enum) && kind.enum.every((entry) => typeof entry === "string") ? new Set(kind.enum) : null;
|
|
311
|
+
seen.set(node, kinds);
|
|
312
|
+
return kinds;
|
|
313
|
+
}
|
|
314
|
+
function accepts(start, scope) {
|
|
315
|
+
if (start.$ref === "Json")
|
|
316
|
+
return true;
|
|
317
|
+
const resolved = resolve(start, scope);
|
|
318
|
+
if (resolved === null)
|
|
319
|
+
return false;
|
|
320
|
+
const { node, definitions } = resolved;
|
|
321
|
+
if (node.type === "null")
|
|
322
|
+
return true;
|
|
323
|
+
return Guard.IsArray(node.anyOf) && node.anyOf.some((member) => {
|
|
324
|
+
const child = readNode(member);
|
|
325
|
+
return child !== null && accepts(child, definitions);
|
|
326
|
+
});
|
|
327
|
+
}
|
|
328
|
+
function readRest(node) {
|
|
329
|
+
const additional = readNode(node.additionalProperties);
|
|
330
|
+
if (additional !== null)
|
|
331
|
+
return additional;
|
|
332
|
+
const patterns = readNode(node.patternProperties);
|
|
333
|
+
if (patterns === null)
|
|
334
|
+
return null;
|
|
335
|
+
const [first] = Object.values(patterns);
|
|
336
|
+
return readNode(first);
|
|
337
|
+
}
|
|
338
|
+
function toJson(value) {
|
|
339
|
+
if (value === null || typeof value === "boolean" || typeof value === "string")
|
|
340
|
+
return value;
|
|
341
|
+
if (typeof value === "number")
|
|
342
|
+
return Number.isFinite(value) ? value : null;
|
|
343
|
+
if (value instanceof Uint8Array)
|
|
344
|
+
return btoa(Array.from(value, (byte) => String.fromCharCode(byte)).join(""));
|
|
345
|
+
if (value instanceof Set)
|
|
346
|
+
return Array.from(value, (item) => toJson(item) ?? null);
|
|
347
|
+
if (Guard.IsArray(value))
|
|
348
|
+
return value.map((item) => toJson(item) ?? null);
|
|
349
|
+
if (typeof value !== "object")
|
|
350
|
+
return;
|
|
351
|
+
const record = {};
|
|
352
|
+
const keep = (key, item) => {
|
|
353
|
+
const json = toJson(item);
|
|
354
|
+
if (json !== undefined)
|
|
355
|
+
put(record, key, json);
|
|
356
|
+
};
|
|
357
|
+
if (value instanceof Map)
|
|
358
|
+
for (const [key, item] of value)
|
|
359
|
+
keep(String(key), item);
|
|
360
|
+
else if (Guard.IsObjectNotArray(value))
|
|
361
|
+
for (const key of Object.keys(value))
|
|
362
|
+
keep(key, value[key]);
|
|
363
|
+
return record;
|
|
364
|
+
}
|
|
365
|
+
function put(record, key, json) {
|
|
366
|
+
if (key === "__proto__")
|
|
367
|
+
Object.defineProperty(record, key, {
|
|
368
|
+
value: json,
|
|
369
|
+
enumerable: true,
|
|
370
|
+
writable: true,
|
|
371
|
+
configurable: true
|
|
372
|
+
});
|
|
373
|
+
else
|
|
374
|
+
record[key] = json;
|
|
375
|
+
}
|
|
376
|
+
function readNode(value) {
|
|
377
|
+
return Guard.IsObjectNotArray(value) ? value : null;
|
|
378
|
+
}
|
|
379
|
+
function readKind(value) {
|
|
380
|
+
const kind = Guard.IsObjectNotArray(value) ? value.kind : undefined;
|
|
381
|
+
return typeof kind === "string" ? kind : undefined;
|
|
382
|
+
}
|
|
383
|
+
function pointer(path) {
|
|
384
|
+
return path.length === 0 ? "the input" : `/${path.join("/")}`;
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
export { namesOperation2, answersOnce2, answersBytes2, decodeInput2, encodeInput2, encodeOutput2, decodeOutput2 };
|
|
File without changes
|