@ipab/cli 0.0.0-stage → 0.1.0-rc.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.
Files changed (120) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +19 -2
  3. package/dist/app-authoring.d.ts +23 -0
  4. package/dist/app-authoring.d.ts.map +1 -0
  5. package/dist/app-authoring.js +449 -0
  6. package/dist/app-authoring.js.map +1 -0
  7. package/dist/app-definition.d.ts +109 -0
  8. package/dist/app-definition.d.ts.map +1 -0
  9. package/dist/app-definition.js +207 -0
  10. package/dist/app-definition.js.map +1 -0
  11. package/dist/app-prebuild.d.ts +12 -0
  12. package/dist/app-prebuild.d.ts.map +1 -0
  13. package/dist/app-prebuild.js +231 -0
  14. package/dist/app-prebuild.js.map +1 -0
  15. package/dist/app-templates.d.ts +13 -0
  16. package/dist/app-templates.d.ts.map +1 -0
  17. package/dist/app-templates.js +287 -0
  18. package/dist/app-templates.js.map +1 -0
  19. package/dist/authoring.d.ts +72 -0
  20. package/dist/authoring.d.ts.map +1 -0
  21. package/dist/authoring.js +440 -0
  22. package/dist/authoring.js.map +1 -0
  23. package/dist/builtins/template.node.car +0 -0
  24. package/dist/builtins/template.web-app.car +0 -0
  25. package/dist/builtins.d.ts +6 -0
  26. package/dist/builtins.d.ts.map +1 -0
  27. package/dist/builtins.js +46 -0
  28. package/dist/builtins.js.map +1 -0
  29. package/dist/child.d.ts +5 -0
  30. package/dist/child.d.ts.map +1 -0
  31. package/dist/child.js +28 -0
  32. package/dist/child.js.map +1 -0
  33. package/dist/cli.d.ts +24 -0
  34. package/dist/cli.d.ts.map +1 -0
  35. package/dist/cli.js +1072 -0
  36. package/dist/cli.js.map +1 -0
  37. package/dist/config.d.ts +26 -0
  38. package/dist/config.d.ts.map +1 -0
  39. package/dist/config.js +156 -0
  40. package/dist/config.js.map +1 -0
  41. package/dist/context.d.ts +42 -0
  42. package/dist/context.d.ts.map +1 -0
  43. package/dist/context.js +164 -0
  44. package/dist/context.js.map +1 -0
  45. package/dist/errors.d.ts +10 -0
  46. package/dist/errors.d.ts.map +1 -0
  47. package/dist/errors.js +40 -0
  48. package/dist/errors.js.map +1 -0
  49. package/dist/history.d.ts +34 -0
  50. package/dist/history.d.ts.map +1 -0
  51. package/dist/history.js +286 -0
  52. package/dist/history.js.map +1 -0
  53. package/dist/ipc.d.ts +26 -0
  54. package/dist/ipc.d.ts.map +1 -0
  55. package/dist/ipc.js +332 -0
  56. package/dist/ipc.js.map +1 -0
  57. package/dist/logs.d.ts +15 -0
  58. package/dist/logs.d.ts.map +1 -0
  59. package/dist/logs.js +118 -0
  60. package/dist/logs.js.map +1 -0
  61. package/dist/main.d.ts +3 -0
  62. package/dist/main.d.ts.map +1 -0
  63. package/dist/main.js +4 -0
  64. package/dist/main.js.map +1 -0
  65. package/dist/pins.d.ts +33 -0
  66. package/dist/pins.d.ts.map +1 -0
  67. package/dist/pins.js +183 -0
  68. package/dist/pins.js.map +1 -0
  69. package/dist/runtime.d.ts +20 -0
  70. package/dist/runtime.d.ts.map +1 -0
  71. package/dist/runtime.js +237 -0
  72. package/dist/runtime.js.map +1 -0
  73. package/dist/source-bundle.d.ts +16 -0
  74. package/dist/source-bundle.d.ts.map +1 -0
  75. package/dist/source-bundle.js +103 -0
  76. package/dist/source-bundle.js.map +1 -0
  77. package/dist/space.d.ts +33 -0
  78. package/dist/space.d.ts.map +1 -0
  79. package/dist/space.js +269 -0
  80. package/dist/space.js.map +1 -0
  81. package/dist/state.d.ts +92 -0
  82. package/dist/state.d.ts.map +1 -0
  83. package/dist/state.js +324 -0
  84. package/dist/state.js.map +1 -0
  85. package/dist/supported-schemas.d.ts +5 -0
  86. package/dist/supported-schemas.d.ts.map +1 -0
  87. package/dist/supported-schemas.js +90 -0
  88. package/dist/supported-schemas.js.map +1 -0
  89. package/dist/template-definition.d.ts +115 -0
  90. package/dist/template-definition.d.ts.map +1 -0
  91. package/dist/template-definition.js +188 -0
  92. package/dist/template-definition.js.map +1 -0
  93. package/dist/template-source.d.ts +12 -0
  94. package/dist/template-source.d.ts.map +1 -0
  95. package/dist/template-source.js +97 -0
  96. package/dist/template-source.js.map +1 -0
  97. package/package.json +67 -3
  98. package/src/app-authoring.ts +614 -0
  99. package/src/app-definition.ts +256 -0
  100. package/src/app-prebuild.ts +289 -0
  101. package/src/app-templates.ts +382 -0
  102. package/src/authoring.ts +610 -0
  103. package/src/builtins.ts +55 -0
  104. package/src/child.ts +32 -0
  105. package/src/cli.ts +1285 -0
  106. package/src/config.ts +220 -0
  107. package/src/context.ts +232 -0
  108. package/src/errors.ts +46 -0
  109. package/src/history.ts +391 -0
  110. package/src/ipc.ts +358 -0
  111. package/src/logs.ts +132 -0
  112. package/src/main.ts +4 -0
  113. package/src/pins.ts +214 -0
  114. package/src/runtime.ts +300 -0
  115. package/src/source-bundle.ts +136 -0
  116. package/src/space.ts +379 -0
  117. package/src/state.ts +416 -0
  118. package/src/supported-schemas.ts +151 -0
  119. package/src/template-definition.ts +242 -0
  120. package/src/template-source.ts +128 -0
package/src/state.ts ADDED
@@ -0,0 +1,416 @@
1
+ import { mkdirSync } from "node:fs";
2
+ import { randomUUID } from "node:crypto";
3
+ import { join } from "node:path";
4
+ import { DatabaseSync } from "node:sqlite";
5
+ import { CID } from "multiformats/cid";
6
+ import type { StoreConfiguration } from "@ipab/ipfs-store";
7
+ import {
8
+ validateUserConfig,
9
+ type ConfigKey,
10
+ type ConfigValue,
11
+ } from "./config.js";
12
+ import { HostError, object, syntax } from "./errors.js";
13
+
14
+ export interface Association {
15
+ schemaCid: string;
16
+ appCid: string;
17
+ argv: string[];
18
+ }
19
+ export interface RunRecord {
20
+ id: string;
21
+ origin: "exec" | "open";
22
+ appCid: string;
23
+ argv: string[];
24
+ startedAt: string;
25
+ endedAt: string;
26
+ status: "succeeded" | "failed" | "cancelled";
27
+ outputCid: string | null;
28
+ appExitCode: number | null;
29
+ log?: "complete" | "incomplete";
30
+ error: { phase: string; code: string; message: string } | null;
31
+ retention: {
32
+ owned: boolean;
33
+ state: "none" | "retained" | "releasing" | "pending";
34
+ owner?: string;
35
+ };
36
+ }
37
+ export interface Hold {
38
+ owner: string;
39
+ backend: StoreConfiguration;
40
+ roots: string[];
41
+ pid: number | null;
42
+ session: string | null;
43
+ recordId: string | null;
44
+ }
45
+ export interface PinMetadata {
46
+ kind: "bundle" | "schema" | "content";
47
+ typeName: string | null;
48
+ schemaCid: string | null;
49
+ }
50
+ export interface NamedPin {
51
+ name: string;
52
+ cid: string;
53
+ owner: string;
54
+ status: "pending" | "ready" | "deleting";
55
+ metadata: PinMetadata | null;
56
+ builtin?: true;
57
+ }
58
+
59
+ export function exactCid(value: string, schema = false): string {
60
+ let cid: CID;
61
+ try {
62
+ cid = CID.parse(value).toV1();
63
+ } catch {
64
+ syntax("Expected a valid CID.");
65
+ }
66
+ if (schema && (cid.code !== 0x71 || cid.multihash.code !== 0x12))
67
+ syntax("Schema must be a DAG-CBOR SHA-256 block CID.");
68
+ return cid.toString();
69
+ }
70
+
71
+ export function pinName(value: string, builtin = false): void {
72
+ if (value.startsWith("builtin:")) {
73
+ if (builtin && /^builtin:[A-Za-z][A-Za-z0-9._-]*$/.test(value)) return;
74
+ syntax(
75
+ "Built-in pins are read-only and cannot be added, deleted or renamed.",
76
+ );
77
+ }
78
+ if (!/^[A-Za-z][A-Za-z0-9._-]*$/.test(value))
79
+ syntax("Invalid pin name; builtin names are reserved.");
80
+ try {
81
+ CID.parse(value);
82
+ } catch {
83
+ return;
84
+ }
85
+ syntax("A pin name must not itself be a CID.");
86
+ }
87
+
88
+ function persistedHold(value: string, owner: string): Hold {
89
+ try {
90
+ const data = object(JSON.parse(value) as unknown, "retention metadata");
91
+ object(data.backend, "original Store configuration");
92
+ if (
93
+ data.owner !== owner ||
94
+ !Array.isArray(data.roots) ||
95
+ data.roots.some((root: unknown) => typeof root !== "string") ||
96
+ (data.pid !== null &&
97
+ (!Number.isSafeInteger(data.pid) || Number(data.pid) <= 0)) ||
98
+ (data.session !== null && typeof data.session !== "string") ||
99
+ (data.recordId !== null && typeof data.recordId !== "string")
100
+ )
101
+ throw new Error("Invalid retention fields.");
102
+ for (const root of data.roots as string[]) exactCid(root);
103
+ return data as unknown as Hold;
104
+ } catch {
105
+ throw new HostError(
106
+ "Invalid persisted retention metadata; cleanup is blocked.",
107
+ 1,
108
+ "STATE_INVALID",
109
+ );
110
+ }
111
+ }
112
+
113
+ export class State {
114
+ readonly db: DatabaseSync;
115
+ readonly identity: string;
116
+ constructor(
117
+ readonly directory: string,
118
+ private readonly builtins: readonly NamedPin[] = [],
119
+ ) {
120
+ mkdirSync(directory, { recursive: true });
121
+ this.db = new DatabaseSync(join(directory, "state.sqlite"));
122
+ this.db
123
+ .exec(`PRAGMA busy_timeout=5000; PRAGMA journal_mode=WAL; PRAGMA synchronous=FULL;
124
+ CREATE TABLE IF NOT EXISTS identity (id TEXT NOT NULL);
125
+ CREATE TABLE IF NOT EXISTS config (key TEXT PRIMARY KEY, value TEXT NOT NULL);
126
+ CREATE TABLE IF NOT EXISTS aliases (name TEXT PRIMARY KEY, cid TEXT NOT NULL);
127
+ CREATE TABLE IF NOT EXISTS named_pins (name TEXT PRIMARY KEY, owner TEXT UNIQUE NOT NULL, value TEXT NOT NULL);
128
+ CREATE TABLE IF NOT EXISTS registrations (schema_cid TEXT PRIMARY KEY, value TEXT NOT NULL);
129
+ CREATE TABLE IF NOT EXISTS runs (id TEXT PRIMARY KEY, value TEXT NOT NULL);
130
+ CREATE TABLE IF NOT EXISTS holds (owner TEXT PRIMARY KEY, value TEXT NOT NULL);`);
131
+ this.transaction(() => {
132
+ if (!this.db.prepare("SELECT id FROM identity").get())
133
+ this.db.prepare("INSERT INTO identity VALUES (?)").run(randomUUID());
134
+ });
135
+ this.identity = String(
136
+ this.db.prepare("SELECT id FROM identity").get()!.id,
137
+ );
138
+ }
139
+ close(): void {
140
+ this.db.close();
141
+ }
142
+ transaction<T>(operation: () => T): T {
143
+ this.db.exec("BEGIN IMMEDIATE");
144
+ try {
145
+ const result = operation();
146
+ this.db.exec("COMMIT");
147
+ return result;
148
+ } catch (error) {
149
+ this.db.exec("ROLLBACK");
150
+ throw error;
151
+ }
152
+ }
153
+ config(): Partial<Record<ConfigKey, ConfigValue>> {
154
+ const entries = this.db.prepare("SELECT key,value FROM config").all();
155
+ try {
156
+ return validateUserConfig(
157
+ Object.fromEntries(
158
+ entries.map((row) => [
159
+ row.key,
160
+ JSON.parse(String(row.value)) as unknown,
161
+ ]),
162
+ ),
163
+ );
164
+ } catch {
165
+ throw new HostError(
166
+ "Malformed user configuration; inspect the state database configuration.",
167
+ );
168
+ }
169
+ }
170
+ setConfig(key: ConfigKey, value: ConfigValue): void {
171
+ this.db
172
+ .prepare("INSERT OR REPLACE INTO config VALUES (?,?)")
173
+ .run(key, JSON.stringify(value));
174
+ }
175
+ resetConfig(key: ConfigKey): void {
176
+ this.db.prepare("DELETE FROM config WHERE key=?").run(key);
177
+ }
178
+ aliases(): { name: string; cid: string }[] {
179
+ return this.db
180
+ .prepare("SELECT name,cid FROM aliases ORDER BY name")
181
+ .all()
182
+ .map((row) => ({
183
+ name: String(row.name),
184
+ cid: exactCid(String(row.cid)),
185
+ }));
186
+ }
187
+ resolve(value: string, schema = false): string {
188
+ try {
189
+ return exactCid(value, schema);
190
+ } catch (error) {
191
+ try {
192
+ CID.parse(value);
193
+ } catch {
194
+ const pin = this.pin(value);
195
+ if (pin) {
196
+ if (pin.status !== "ready")
197
+ throw new HostError(
198
+ `Pin "${value}" is ${pin.status}; retry pin add/delete before using it.`,
199
+ );
200
+ return exactCid(pin.cid, schema);
201
+ }
202
+ if (this.db.prepare("SELECT 1 FROM aliases WHERE name=?").get(value))
203
+ throw new HostError(
204
+ `Legacy Alias "${value}" is not a pin. Read its CID from the preserved aliases table and run ipab pin add NAME CID to verify and retain it.`,
205
+ );
206
+ throw new HostError(
207
+ `Unknown CID or pin "${value}". Run ipab pin list.`,
208
+ );
209
+ }
210
+ throw error;
211
+ }
212
+ }
213
+ pins(): NamedPin[] {
214
+ const user = this.db
215
+ .prepare("SELECT name,owner,value FROM named_pins ORDER BY name")
216
+ .all()
217
+ .map((row) =>
218
+ this.readPin(String(row.name), String(row.owner), String(row.value)),
219
+ );
220
+ return [...user, ...this.builtins];
221
+ }
222
+ pin(name: string): NamedPin | undefined {
223
+ const builtin = this.builtins.find((pin) => pin.name === name);
224
+ if (builtin) return builtin;
225
+ const row = this.db
226
+ .prepare("SELECT owner,value FROM named_pins WHERE name=?")
227
+ .get(name);
228
+ return row
229
+ ? this.readPin(name, String(row.owner), String(row.value))
230
+ : undefined;
231
+ }
232
+ private readPin(name: string, owner: string, value: string): NamedPin {
233
+ const data = object(JSON.parse(value) as unknown, "named pin");
234
+ if (
235
+ data.name !== name ||
236
+ data.owner !== owner ||
237
+ typeof data.cid !== "string" ||
238
+ (data.status !== "pending" &&
239
+ data.status !== "ready" &&
240
+ data.status !== "deleting")
241
+ )
242
+ throw new HostError("Invalid persisted named pin; recovery is blocked.");
243
+ exactCid(data.cid);
244
+ let metadata: PinMetadata | null = null;
245
+ if (data.metadata !== null) {
246
+ const value = object(data.metadata, "pin type metadata");
247
+ if (value.kind === "content") {
248
+ if (value.typeName !== null || value.schemaCid !== null)
249
+ throw new HostError("Invalid persisted pin type metadata.");
250
+ metadata = { kind: "content", typeName: null, schemaCid: null };
251
+ } else {
252
+ if (
253
+ (value.kind !== "bundle" && value.kind !== "schema") ||
254
+ typeof value.typeName !== "string" ||
255
+ typeof value.schemaCid !== "string"
256
+ )
257
+ throw new HostError("Invalid persisted pin type metadata.");
258
+ metadata = {
259
+ kind: value.kind,
260
+ typeName: value.typeName,
261
+ schemaCid: exactCid(value.schemaCid, true),
262
+ };
263
+ }
264
+ } else if (data.status === "ready")
265
+ throw new HostError("Ready pin is missing type metadata.");
266
+ return {
267
+ name,
268
+ cid: data.cid,
269
+ owner,
270
+ status: data.status,
271
+ metadata,
272
+ };
273
+ }
274
+ savePin(pin: NamedPin): void {
275
+ pinName(pin.name);
276
+ if (
277
+ !this.db
278
+ .prepare(
279
+ "INSERT INTO named_pins VALUES (?,?,?) ON CONFLICT(name) DO UPDATE SET value=excluded.value WHERE owner=excluded.owner",
280
+ )
281
+ .run(pin.name, pin.owner, JSON.stringify(pin)).changes
282
+ )
283
+ throw new HostError(`Pin name "${pin.name}" is occupied.`);
284
+ }
285
+ isPinOwner(owner: string): boolean {
286
+ return Boolean(
287
+ this.db.prepare("SELECT 1 FROM named_pins WHERE owner=?").get(owner),
288
+ );
289
+ }
290
+ deletePin(name: string): void {
291
+ pinName(name);
292
+ this.db.prepare("DELETE FROM named_pins WHERE name=?").run(name);
293
+ }
294
+ registrations(): Association[] {
295
+ return this.db
296
+ .prepare("SELECT value FROM registrations ORDER BY schema_cid")
297
+ .all()
298
+ .map((row) => JSON.parse(String(row.value)) as Association);
299
+ }
300
+ association(schemaCid: string): Association | undefined {
301
+ const row = this.db
302
+ .prepare("SELECT value FROM registrations WHERE schema_cid=?")
303
+ .get(schemaCid);
304
+ return row ? (JSON.parse(String(row.value)) as Association) : undefined;
305
+ }
306
+ setAssociation(
307
+ schema: string,
308
+ app: string,
309
+ argv: string[],
310
+ replace: boolean,
311
+ ): Association {
312
+ const value: Association = {
313
+ schemaCid: this.resolve(schema, true),
314
+ appCid: this.resolve(app),
315
+ argv,
316
+ };
317
+ if (!argv.length || !argv.includes("%"))
318
+ syntax('Argument template must contain a whole "%" argument.');
319
+ this.transaction(() => {
320
+ const old = this.association(value.schemaCid);
321
+ if (old && JSON.stringify(old) !== JSON.stringify(value) && !replace)
322
+ throw new HostError(
323
+ "Schema has another association; use --replace before --.",
324
+ );
325
+ this.db
326
+ .prepare("INSERT OR REPLACE INTO registrations VALUES (?,?)")
327
+ .run(value.schemaCid, JSON.stringify(value));
328
+ });
329
+ return value;
330
+ }
331
+ removeAssociation(schema: string): string {
332
+ const cid = this.resolve(schema, true);
333
+ if (
334
+ !this.db.prepare("DELETE FROM registrations WHERE schema_cid=?").run(cid)
335
+ .changes
336
+ )
337
+ throw new HostError(
338
+ "No association exists for this Schema. Run ipab register list.",
339
+ );
340
+ return cid;
341
+ }
342
+ runs(): RunRecord[] {
343
+ return this.db
344
+ .prepare("SELECT value FROM runs")
345
+ .all()
346
+ .map((row) => JSON.parse(String(row.value)) as RunRecord);
347
+ }
348
+ private matchingRunIds(prefix: string): string[] {
349
+ // Prefixes are literal identifiers, not GLOB patterns.
350
+ const pattern = `${prefix.replaceAll("[", "[[]").replaceAll("*", "[*]").replaceAll("?", "[?]")}*`;
351
+ return this.db
352
+ .prepare("SELECT id FROM runs WHERE id GLOB ? ORDER BY id LIMIT 2")
353
+ .all(pattern)
354
+ .map((row) => String(row.id));
355
+ }
356
+ shortRunId(id: string): string {
357
+ let length = Math.min(8, id.length);
358
+ while (
359
+ length < id.length &&
360
+ this.matchingRunIds(id.slice(0, length)).length > 1
361
+ )
362
+ length++;
363
+ return id.slice(0, length);
364
+ }
365
+ resolveRunId(value: string): string {
366
+ if (this.db.prepare("SELECT id FROM runs WHERE id=?").get(value))
367
+ return value;
368
+ if (value.length >= 8) {
369
+ const matches = this.matchingRunIds(value);
370
+ if (matches.length === 1) return matches[0]!;
371
+ if (matches.length > 1)
372
+ throw new HostError(
373
+ `Ambiguous run ID prefix "${value}"; use more characters or the full ID.`,
374
+ );
375
+ }
376
+ throw new HostError(
377
+ `Execution record "${value}" does not exist. Run ipab history list.`,
378
+ );
379
+ }
380
+ run(id: string): RunRecord {
381
+ const row = this.db.prepare("SELECT value FROM runs WHERE id=?").get(id);
382
+ if (!row)
383
+ throw new HostError(
384
+ `Execution record "${id}" does not exist. Run ipab history list.`,
385
+ );
386
+ return JSON.parse(String(row.value)) as RunRecord;
387
+ }
388
+ saveRun(record: RunRecord): void {
389
+ this.db
390
+ .prepare("INSERT OR REPLACE INTO runs VALUES (?,?)")
391
+ .run(record.id, JSON.stringify(record));
392
+ }
393
+ deleteRun(id: string): void {
394
+ this.db.prepare("DELETE FROM runs WHERE id=?").run(id);
395
+ }
396
+ holds(): Hold[] {
397
+ return this.db
398
+ .prepare("SELECT owner,value FROM holds")
399
+ .all()
400
+ .map((row) => persistedHold(String(row.value), String(row.owner)));
401
+ }
402
+ hold(owner: string): Hold | undefined {
403
+ const row = this.db
404
+ .prepare("SELECT value FROM holds WHERE owner=?")
405
+ .get(owner);
406
+ return row ? persistedHold(String(row.value), owner) : undefined;
407
+ }
408
+ saveHold(hold: Hold): void {
409
+ this.db
410
+ .prepare("INSERT OR REPLACE INTO holds VALUES (?,?)")
411
+ .run(hold.owner, JSON.stringify(hold));
412
+ }
413
+ deleteHold(owner: string): void {
414
+ this.db.prepare("DELETE FROM holds WHERE owner=?").run(owner);
415
+ }
416
+ }
@@ -0,0 +1,151 @@
1
+ import { CarBlockIterator } from "@ipld/car/iterator";
2
+ import {
3
+ blockLength,
4
+ createWriter,
5
+ headerLength,
6
+ } from "@ipld/car/buffer-writer";
7
+ import {
8
+ bundleLimits,
9
+ ContentBundleError,
10
+ decodeSchema,
11
+ encodeSchema,
12
+ parseData,
13
+ type SchemaBlock,
14
+ } from "@ipab/bundle";
15
+ import {
16
+ readBytes,
17
+ streamChunks,
18
+ type ReadonlyFileTree,
19
+ type ReadOptions,
20
+ } from "@ipab/bundle-builder";
21
+ import { HostError } from "./errors.js";
22
+
23
+ export const supportedSchemasPath = "resources/supported-schemas.car";
24
+ const carBytes = bundleLimits.bytes + bundleLimits.files * 128;
25
+
26
+ function budget(signal?: AbortSignal) {
27
+ let work = 0;
28
+ return {
29
+ nodes: bundleLimits.nodes,
30
+ depth: bundleLimits.validationDepth,
31
+ jsonDepth: bundleLimits.jsonDepth,
32
+ schemaBytes: bundleLimits.schemaBytes,
33
+ charge(this: void) {
34
+ signal?.throwIfAborted();
35
+ if (++work > bundleLimits.nodes)
36
+ throw new ContentBundleError(
37
+ "LIMIT_EXCEEDED",
38
+ "Supported Schemas aggregate work budget exceeded.",
39
+ );
40
+ },
41
+ };
42
+ }
43
+
44
+ export async function buildSupportedSchemas(
45
+ tree: ReadonlyFileTree,
46
+ paths: ReadonlySet<string>,
47
+ options: ReadOptions = {},
48
+ ): Promise<Uint8Array | undefined> {
49
+ if (!paths.size) return undefined;
50
+ if (paths.size > bundleLimits.files)
51
+ throw new HostError("Too many supported Schema source files.");
52
+ const limits = budget(options.signal);
53
+ const blocks = new Map<string, SchemaBlock>();
54
+ let total = 0;
55
+ for (const path of paths) {
56
+ const bytes = await readBytes(
57
+ tree,
58
+ path,
59
+ bundleLimits.schemaBytes,
60
+ options,
61
+ );
62
+ total += bytes.length;
63
+ if (total > bundleLimits.parsingBytes)
64
+ throw new ContentBundleError(
65
+ "LIMIT_EXCEEDED",
66
+ "Supported Schemas source byte budget exceeded.",
67
+ );
68
+ const block = await encodeSchema(
69
+ parseData(
70
+ bytes,
71
+ "application/json",
72
+ limits.nodes,
73
+ limits.jsonDepth,
74
+ limits.charge,
75
+ ),
76
+ limits,
77
+ );
78
+ blocks.set(block.cid.toString(), block);
79
+ }
80
+ const ordered = [...blocks.entries()]
81
+ .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))
82
+ .map(([, block]) => block);
83
+ const roots = ordered.map((block) => block.cid);
84
+ const size =
85
+ headerLength({ roots }) +
86
+ ordered.reduce((size, block) => size + blockLength(block), 0);
87
+ if (size > carBytes)
88
+ throw new ContentBundleError(
89
+ "LIMIT_EXCEEDED",
90
+ "Supported Schemas CAR byte budget exceeded.",
91
+ );
92
+ const writer = createWriter(new ArrayBuffer(size), { roots });
93
+ for (const block of ordered) writer.write(block);
94
+ return writer.close();
95
+ }
96
+
97
+ export async function readSupportedSchemas(
98
+ stream: ReadableStream<Uint8Array>,
99
+ signal?: AbortSignal,
100
+ ): Promise<ReadonlySet<string>> {
101
+ const chunks = streamChunks(stream, signal ? { signal } : {});
102
+ const limits = budget(signal);
103
+ let total = 0;
104
+ const bounded = async function* () {
105
+ for await (const chunk of chunks) {
106
+ total += chunk.length;
107
+ if (total > carBytes)
108
+ throw new ContentBundleError(
109
+ "LIMIT_EXCEEDED",
110
+ "Supported Schemas CAR byte budget exceeded.",
111
+ );
112
+ yield chunk;
113
+ }
114
+ };
115
+ try {
116
+ const iterator = await CarBlockIterator.fromIterable(bounded());
117
+ const roots = await iterator.getRoots();
118
+ if (!roots.length || roots.length > bundleLimits.files)
119
+ throw new HostError(
120
+ "Supported Schemas CAR requires a bounded nonempty root list.",
121
+ );
122
+ const supported = new Set(roots.map((root) => root.toString()));
123
+ if (
124
+ supported.size !== roots.length ||
125
+ roots.some(
126
+ (root) =>
127
+ root.version !== 1 ||
128
+ root.code !== 0x71 ||
129
+ root.multihash.code !== 0x12,
130
+ )
131
+ )
132
+ throw new HostError(
133
+ "Supported Schemas CAR requires unique CIDv1 DAG-CBOR SHA-256 roots.",
134
+ );
135
+ const seen = new Set<string>();
136
+ for await (const block of iterator) {
137
+ const key = block.cid.toString();
138
+ if (!supported.has(key) || seen.has(key))
139
+ throw new HostError(
140
+ "Supported Schemas CAR has an unrelated or duplicate block record.",
141
+ );
142
+ await decodeSchema(block.cid, block.bytes, limits);
143
+ seen.add(key);
144
+ }
145
+ if (seen.size !== supported.size)
146
+ throw new HostError("Supported Schemas CAR is missing a root block.");
147
+ return supported;
148
+ } finally {
149
+ await chunks.return(undefined);
150
+ }
151
+ }