@ipab/cli 0.0.0 → 0.1.0-rc.1

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 +24 -1
  3. package/dist/app-authoring.d.ts +22 -0
  4. package/dist/app-authoring.d.ts.map +1 -0
  5. package/dist/app-authoring.js +448 -0
  6. package/dist/app-authoring.js.map +1 -0
  7. package/dist/app-definition.d.ts +103 -0
  8. package/dist/app-definition.d.ts.map +1 -0
  9. package/dist/app-definition.js +201 -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 +295 -0
  18. package/dist/app-templates.js.map +1 -0
  19. package/dist/authoring.d.ts +63 -0
  20. package/dist/authoring.d.ts.map +1 -0
  21. package/dist/authoring.js +411 -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 +41 -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 +1110 -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 +154 -0
  40. package/dist/config.js.map +1 -0
  41. package/dist/context.d.ts +43 -0
  42. package/dist/context.d.ts.map +1 -0
  43. package/dist/context.js +174 -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 +27 -0
  54. package/dist/ipc.d.ts.map +1 -0
  55. package/dist/ipc.js +341 -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 +165 -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 +15 -0
  74. package/dist/source-bundle.d.ts.map +1 -0
  75. package/dist/source-bundle.js +102 -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 +102 -0
  82. package/dist/state.d.ts.map +1 -0
  83. package/dist/state.js +335 -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 +98 -0
  90. package/dist/template-definition.d.ts.map +1 -0
  91. package/dist/template-definition.js +179 -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 +60 -3
  98. package/src/app-authoring.ts +616 -0
  99. package/src/app-definition.ts +250 -0
  100. package/src/app-prebuild.ts +289 -0
  101. package/src/app-templates.ts +395 -0
  102. package/src/authoring.ts +577 -0
  103. package/src/builtins.ts +49 -0
  104. package/src/child.ts +32 -0
  105. package/src/cli.ts +1330 -0
  106. package/src/config.ts +221 -0
  107. package/src/context.ts +242 -0
  108. package/src/errors.ts +46 -0
  109. package/src/history.ts +391 -0
  110. package/src/ipc.ts +366 -0
  111. package/src/logs.ts +132 -0
  112. package/src/main.ts +4 -0
  113. package/src/pins.ts +200 -0
  114. package/src/runtime.ts +301 -0
  115. package/src/source-bundle.ts +135 -0
  116. package/src/space.ts +379 -0
  117. package/src/state.ts +430 -0
  118. package/src/supported-schemas.ts +151 -0
  119. package/src/template-definition.ts +233 -0
  120. package/src/template-source.ts +128 -0
package/src/history.ts ADDED
@@ -0,0 +1,391 @@
1
+ import { IpfsStore, type StoreConfiguration } from "@ipab/ipfs-store";
2
+ import type { SQLInputValue } from "node:sqlite";
3
+ import { HostError, message, syntax } from "./errors.js";
4
+ import type { Hold, RunRecord, State } from "./state.js";
5
+ import { removeLogs } from "./logs.js";
6
+
7
+ export interface Filters {
8
+ app?: string;
9
+ status?: RunRecord["status"];
10
+ since?: number;
11
+ until?: number;
12
+ }
13
+
14
+ export function timestamp(value: string): number {
15
+ if (
16
+ !/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,3})?(?:Z|[+-]\d{2}:\d{2})$/.test(
17
+ value,
18
+ )
19
+ )
20
+ syntax(
21
+ "Time must be RFC3339 with Z or an explicit timezone offset and at most three fractional second digits.",
22
+ );
23
+ const number = Date.parse(value);
24
+ const [, year, month, day, hour, minute, second] =
25
+ /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})/.exec(value)!;
26
+ const calendar = new Date(0);
27
+ calendar.setUTCFullYear(Number(year), Number(month), 0);
28
+ const days = calendar.getUTCDate();
29
+ if (
30
+ !Number.isFinite(number) ||
31
+ Number(month) < 1 ||
32
+ Number(month) > 12 ||
33
+ Number(day) < 1 ||
34
+ Number(day) > days ||
35
+ Number(hour) > 23 ||
36
+ Number(minute) > 59 ||
37
+ Number(second) > 59
38
+ )
39
+ syntax("Invalid RFC3339 timestamp.");
40
+ return number;
41
+ }
42
+
43
+ export function filters(
44
+ state: State,
45
+ options: Record<string, string | boolean>,
46
+ ): Filters {
47
+ const result: Filters = {};
48
+ if (typeof options.app === "string") result.app = state.resolve(options.app);
49
+ if (typeof options.status === "string") {
50
+ if (!["succeeded", "failed", "cancelled"].includes(options.status))
51
+ syntax("Invalid execution status.");
52
+ result.status = options.status as RunRecord["status"];
53
+ }
54
+ if (typeof options.since === "string")
55
+ result.since = timestamp(options.since);
56
+ if (typeof options.until === "string")
57
+ result.until = timestamp(options.until);
58
+ if (
59
+ result.since !== undefined &&
60
+ result.until !== undefined &&
61
+ result.since >= result.until
62
+ )
63
+ syntax("--since must precede --until.");
64
+ return result;
65
+ }
66
+
67
+ const endedTime =
68
+ "CAST(round((julianday(json_extract(value,'$.endedAt'))-2440587.5)*86400000) AS INTEGER)";
69
+ function selection(
70
+ filter: Filters,
71
+ before?: RunRecord,
72
+ ): { where: string; parameters: SQLInputValue[] } {
73
+ const conditions: string[] = [];
74
+ const parameters: SQLInputValue[] = [];
75
+ for (const [field, value] of [
76
+ ["appCid", filter.app],
77
+ ["status", filter.status],
78
+ ] as const) {
79
+ if (value !== undefined) {
80
+ conditions.push(`json_extract(value,'$.${field}')=?`);
81
+ parameters.push(value);
82
+ }
83
+ }
84
+ if (filter.since !== undefined) {
85
+ conditions.push(`${endedTime}>=?`);
86
+ parameters.push(filter.since);
87
+ }
88
+ if (filter.until !== undefined) {
89
+ conditions.push(`${endedTime}<?`);
90
+ parameters.push(filter.until);
91
+ }
92
+ if (before) {
93
+ conditions.push(`(${endedTime}<? OR (${endedTime}=? AND id<?))`);
94
+ parameters.push(
95
+ Date.parse(before.endedAt),
96
+ Date.parse(before.endedAt),
97
+ before.id,
98
+ );
99
+ }
100
+ return {
101
+ where: conditions.length ? `WHERE ${conditions.join(" AND ")}` : "",
102
+ parameters,
103
+ };
104
+ }
105
+
106
+ export function selectedIds(state: State, filter: Filters): string[] {
107
+ const query = selection(filter);
108
+ return state.db
109
+ .prepare(
110
+ `SELECT id FROM runs ${query.where} ORDER BY ${endedTime} DESC,id DESC`,
111
+ )
112
+ .all(...query.parameters)
113
+ .map((row) => String(row.id));
114
+ }
115
+
116
+ export function listHistory(
117
+ state: State,
118
+ filter: Filters,
119
+ limit: number,
120
+ before?: string,
121
+ ): {
122
+ items: Omit<RunRecord, "origin" | "appExitCode" | "error" | "retention">[];
123
+ nextBefore: string | null;
124
+ } {
125
+ const query = selection(
126
+ filter,
127
+ before !== undefined ? state.run(before) : undefined,
128
+ );
129
+ const records = state.db
130
+ .prepare(
131
+ `SELECT value FROM runs ${query.where} ORDER BY ${endedTime} DESC,id DESC LIMIT ?`,
132
+ )
133
+ .all(
134
+ ...query.parameters,
135
+ limit < Number.MAX_SAFE_INTEGER ? limit + 1 : limit,
136
+ )
137
+ .map((row) => JSON.parse(String(row.value)) as RunRecord);
138
+ const page = records.slice(0, limit);
139
+ return {
140
+ items: page.map(
141
+ ({ id, appCid, argv, startedAt, endedAt, status, outputCid }) => ({
142
+ id,
143
+ appCid,
144
+ argv,
145
+ startedAt,
146
+ endedAt,
147
+ status,
148
+ outputCid,
149
+ }),
150
+ ),
151
+ nextBefore: records.length > page.length ? page.at(-1)!.id : null,
152
+ };
153
+ }
154
+
155
+ export function alive(pid: number): boolean {
156
+ try {
157
+ process.kill(pid, 0);
158
+ return true;
159
+ } catch (error) {
160
+ return (error as NodeJS.ErrnoException).code !== "ESRCH";
161
+ }
162
+ }
163
+
164
+ export class Ownership {
165
+ constructor(
166
+ readonly state: State,
167
+ readonly store: IpfsStore,
168
+ readonly owner: string,
169
+ ) {}
170
+ static async create(
171
+ state: State,
172
+ store: IpfsStore,
173
+ id: string,
174
+ session: string | null,
175
+ ): Promise<Ownership> {
176
+ const owner = `ipab:${state.identity}:${id}`;
177
+ const hold: Hold = {
178
+ owner,
179
+ backend: store.configuration,
180
+ roots: [],
181
+ pid: process.pid,
182
+ session,
183
+ recordId: null,
184
+ };
185
+ state.saveHold(hold);
186
+ const deadline = Date.now() + 30_000;
187
+ for (;;) {
188
+ try {
189
+ store.registerOwner(owner, []);
190
+ break;
191
+ } catch (error) {
192
+ if (
193
+ (error as { code?: unknown }).code !== "retention_unfinished" ||
194
+ Date.now() >= deadline
195
+ ) {
196
+ state.saveHold({ ...hold, pid: null });
197
+ throw error;
198
+ }
199
+ await new Promise((resolve) => setTimeout(resolve, 10));
200
+ }
201
+ }
202
+ return new Ownership(state, store, owner);
203
+ }
204
+ async retain(roots: string[], signal?: AbortSignal): Promise<void> {
205
+ const current = this.state.hold(this.owner)!;
206
+ const added = roots.filter((root) => !current.roots.includes(root));
207
+ if (!added.length) return;
208
+ await this.store.retain(this.owner, added, signal ? { signal } : {});
209
+ // Read again after await: concurrent requests must not lose each other's references.
210
+ const latest = this.state.hold(this.owner)!;
211
+ this.state.saveHold({
212
+ ...latest,
213
+ roots: [...new Set([...latest.roots, ...added])],
214
+ });
215
+ await this.store.confirmRetained(
216
+ this.owner,
217
+ added,
218
+ signal ? { signal } : {},
219
+ );
220
+ }
221
+ async release(): Promise<void> {
222
+ const hold = this.state.hold(this.owner);
223
+ if (!hold) return;
224
+ this.state.saveHold({ ...hold, roots: [] });
225
+ try {
226
+ if (hold.session) await this.store.discardImport(hold.session);
227
+ await this.store.recoverOwner(
228
+ this.owner,
229
+ () => this.state.hold(this.owner)?.roots ?? [],
230
+ );
231
+ await this.store.reconcile(
232
+ this.owner,
233
+ () => this.state.hold(this.owner)?.roots ?? [],
234
+ );
235
+ this.state.deleteHold(this.owner);
236
+ } catch (error) {
237
+ const current = this.state.hold(this.owner);
238
+ if (current) this.state.saveHold({ ...current, pid: null });
239
+ throw error;
240
+ }
241
+ }
242
+ }
243
+
244
+ export type StoreFactory = (config: StoreConfiguration) => IpfsStore;
245
+ const createStore: StoreFactory = (config) => new IpfsStore(config);
246
+
247
+ export async function recoverInactive(
248
+ state: State,
249
+ factory: StoreFactory = createStore,
250
+ ): Promise<void> {
251
+ for (const hold of state.holds()) {
252
+ if (
253
+ hold.recordId ||
254
+ state.isPinOwner(hold.owner) ||
255
+ (hold.pid !== null && alive(hold.pid))
256
+ )
257
+ continue;
258
+ const store = factory(hold.backend);
259
+ try {
260
+ await store.recoverOwner(
261
+ hold.owner,
262
+ () => state.hold(hold.owner)?.roots ?? [],
263
+ {
264
+ isIdle: () => {
265
+ const current = state.hold(hold.owner);
266
+ return !current || current.pid === null || !alive(current.pid);
267
+ },
268
+ },
269
+ );
270
+ const current = state.hold(hold.owner);
271
+ if (current && (current.pid === null || !alive(current.pid))) {
272
+ await new Ownership(state, store, hold.owner).release();
273
+ }
274
+ } finally {
275
+ await store.close();
276
+ }
277
+ }
278
+ }
279
+
280
+ export async function saveHistory(
281
+ state: State,
282
+ store: IpfsStore,
283
+ record: RunRecord,
284
+ retained: boolean,
285
+ ): Promise<void> {
286
+ if (!retained || !record.outputCid) {
287
+ state.saveRun(record);
288
+ return;
289
+ }
290
+ const ownership = await Ownership.create(
291
+ state,
292
+ store,
293
+ `history:${record.id}`,
294
+ null,
295
+ );
296
+ record.retention = { owned: true, state: "pending", owner: ownership.owner };
297
+ try {
298
+ await store.retain(ownership.owner, [record.outputCid]);
299
+ state.transaction(() => {
300
+ const hold = state.hold(ownership.owner)!;
301
+ state.saveHold({
302
+ ...hold,
303
+ roots: [record.outputCid!],
304
+ recordId: record.id,
305
+ });
306
+ state.saveRun(record);
307
+ });
308
+ await store.confirmRetained(ownership.owner, [record.outputCid]);
309
+ state.transaction(() => {
310
+ record.retention.state = "retained";
311
+ state.saveRun(record);
312
+ state.saveHold({ ...state.hold(ownership.owner)!, pid: null });
313
+ });
314
+ } catch (error) {
315
+ state.saveHold({ ...state.hold(ownership.owner)!, pid: null });
316
+ throw error;
317
+ }
318
+ }
319
+
320
+ export async function removeHistory(
321
+ state: State,
322
+ ids: readonly string[],
323
+ factory: StoreFactory = createStore,
324
+ ): Promise<{
325
+ removed: string[];
326
+ retentionClaimsReleased: true;
327
+ garbageCollectionGuaranteed: false;
328
+ }> {
329
+ const removed: string[] = [];
330
+ for (const id of ids) {
331
+ try {
332
+ const record = state.run(id);
333
+ if (record.retention.owned) {
334
+ const hold = record.retention.owner
335
+ ? state.hold(record.retention.owner)
336
+ : undefined;
337
+ if (!hold)
338
+ throw new HostError(
339
+ "Retention ownership metadata is missing; deletion is blocked.",
340
+ );
341
+ if (hold.pid !== null && alive(hold.pid))
342
+ throw new HostError(
343
+ "Record retention commit is active; retry after it finishes.",
344
+ );
345
+ const store = factory(hold.backend);
346
+ try {
347
+ state.transaction(() => {
348
+ const latest = state.run(id);
349
+ latest.retention.state = "releasing";
350
+ state.saveRun(latest);
351
+ state.saveHold({ ...hold, roots: [], pid: null });
352
+ });
353
+ // These callbacks read persisted references while the Store participant mutex is held.
354
+ await store.recoverOwner(
355
+ hold.owner,
356
+ () => state.hold(hold.owner)?.roots ?? [],
357
+ );
358
+ await store.reconcile(
359
+ hold.owner,
360
+ () => state.hold(hold.owner)?.roots ?? [],
361
+ );
362
+ if (record.log) await removeLogs(state.directory, id);
363
+ state.transaction(() => {
364
+ state.deleteRun(id);
365
+ state.deleteHold(hold.owner);
366
+ });
367
+ } finally {
368
+ await store.close();
369
+ }
370
+ } else {
371
+ if (record.log) await removeLogs(state.directory, id);
372
+ state.deleteRun(id);
373
+ }
374
+ removed.push(id);
375
+ } catch (error) {
376
+ throw new HostError(
377
+ `History removal incomplete. Completed: ${JSON.stringify(removed)}; remaining: ${JSON.stringify(
378
+ ids.filter((target) => !removed.includes(target)),
379
+ )}. ${message(error)} Ownership remains recoverable; no garbage collection requested.`,
380
+ 1,
381
+ "RELEASE_FAILED",
382
+ "cleanup",
383
+ );
384
+ }
385
+ }
386
+ return {
387
+ removed,
388
+ retentionClaimsReleased: true,
389
+ garbageCollectionGuaranteed: false,
390
+ };
391
+ }