@ipab/cli 0.0.0 → 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 +18 -1
  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 +60 -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/runtime.ts ADDED
@@ -0,0 +1,300 @@
1
+ import { spawn, type ChildProcess } from "node:child_process";
2
+ import { randomUUID } from "node:crypto";
3
+ import { mkdir, writeFile, unlink, rmdir } from "node:fs/promises";
4
+ import { join } from "node:path";
5
+ import { fileURLToPath } from "node:url";
6
+ import type { IpfsStore } from "@ipab/ipfs-store";
7
+ import { HostError, message } from "./errors.js";
8
+ import { Ownership, saveHistory } from "./history.js";
9
+ import { ContextServer } from "./ipc.js";
10
+ import { loadApp, OutputSpace } from "./space.js";
11
+ import type { RunRecord, State } from "./state.js";
12
+ import { ExecutionLogs } from "./logs.js";
13
+
14
+ export interface Invocation {
15
+ origin: "exec" | "open";
16
+ appCid: string;
17
+ argv: string[];
18
+ }
19
+ export interface ExecutionOptions {
20
+ history: boolean;
21
+ retain: boolean;
22
+ diagnostic: (text: string) => void;
23
+ log?: boolean;
24
+ signal?: AbortSignal;
25
+ inputSchema?: string;
26
+ }
27
+
28
+ export async function execute(
29
+ state: State,
30
+ store: IpfsStore,
31
+ invocation: Invocation,
32
+ options: ExecutionOptions,
33
+ ): Promise<{ exitCode: number; record: RunRecord }> {
34
+ if (options.log && !options.history)
35
+ throw new HostError("Execution logging requires history.enabled=true.");
36
+ const id = randomUUID();
37
+ const session = `ipab-output:${state.identity}:${id}`;
38
+ const record: RunRecord = {
39
+ id,
40
+ ...invocation,
41
+ startedAt: new Date().toISOString(),
42
+ endedAt: "",
43
+ status: "failed",
44
+ outputCid: null,
45
+ appExitCode: null,
46
+ error: null,
47
+ retention: { owned: false, state: "none" },
48
+ };
49
+ const owner = await Ownership.create(state, store, `run:${id}`, session);
50
+ const controller = new AbortController();
51
+ const output = new OutputSpace(store, owner, session, controller.signal);
52
+ let child: ChildProcess | undefined;
53
+ let server: ContextServer | undefined;
54
+ let timer: NodeJS.Timeout | undefined;
55
+ let logs: ExecutionLogs | undefined;
56
+ let forwarding: Promise<void>[] = [];
57
+ let logFailure: unknown;
58
+ let exitCode = 1;
59
+ let cancellation = 0;
60
+ let phase = "validation";
61
+ const directory = join(state.directory, "runtime", id);
62
+ const entry = join(directory, "app.cjs");
63
+ let directoryCreated = false;
64
+ let entryCreated = false;
65
+ const stop = (error: Error, code = 1) => {
66
+ controller.abort(error);
67
+ if (code !== 1) cancellation = code;
68
+ if (child && child.exitCode === null && child.signalCode === null) {
69
+ child.kill(code === 130 ? "SIGINT" : "SIGTERM");
70
+ timer ??= setTimeout(() => {
71
+ child?.kill("SIGKILL");
72
+ }, 2000);
73
+ timer.unref();
74
+ }
75
+ };
76
+ const interrupt = () => {
77
+ stop(
78
+ new HostError("Execution cancelled.", 130, "CANCELLED", "execution"),
79
+ 130,
80
+ );
81
+ };
82
+ const terminate = () => {
83
+ stop(
84
+ new HostError("Execution cancelled.", 143, "CANCELLED", "execution"),
85
+ 143,
86
+ );
87
+ };
88
+ const abort = () => {
89
+ stop(
90
+ new HostError("Execution cancelled.", 130, "CANCELLED", "execution"),
91
+ 130,
92
+ );
93
+ };
94
+ process.on("SIGINT", interrupt);
95
+ process.on("SIGTERM", terminate);
96
+ options.signal?.addEventListener("abort", abort, { once: true });
97
+ try {
98
+ if (options.signal?.aborted) abort();
99
+ controller.signal.throwIfAborted();
100
+ const app = await loadApp(
101
+ invocation.appCid,
102
+ store,
103
+ owner,
104
+ controller.signal,
105
+ );
106
+ if (
107
+ invocation.origin === "open" &&
108
+ !app.supportedSchemas.has(options.inputSchema ?? "")
109
+ )
110
+ throw new HostError(
111
+ `Registered App ${invocation.appCid} does not declare support for Schema ${options.inputSchema ?? "(missing)"}. Rebuild the App with this complete definition in ipab.yaml supportedSchemas and update its pin/register association, or use ipab exec explicitly.`,
112
+ 1,
113
+ "APP_SCHEMA_UNSUPPORTED",
114
+ "validation",
115
+ );
116
+ phase = "startup";
117
+ await mkdir(directory, { recursive: true });
118
+ directoryCreated = true;
119
+ await writeFile(entry, app.source, { flag: "wx", mode: 0o600 });
120
+ entryCreated = true;
121
+ controller.signal.throwIfAborted();
122
+ if (options.log) {
123
+ record.log = "incomplete";
124
+ logs = await ExecutionLogs.create(state.directory, id);
125
+ }
126
+ child = spawn(
127
+ process.execPath,
128
+ [
129
+ fileURLToPath(new URL("../dist/child.js", import.meta.url)),
130
+ entry,
131
+ ...invocation.argv,
132
+ ],
133
+ {
134
+ stdio: [
135
+ "inherit",
136
+ logs ? "pipe" : "inherit",
137
+ logs ? "pipe" : "inherit",
138
+ "ipc",
139
+ ],
140
+ serialization: "advanced",
141
+ shell: false,
142
+ },
143
+ );
144
+ if (logs) {
145
+ forwarding = [
146
+ logs.forward(child.stdout!, process.stdout, "stdout"),
147
+ logs.forward(child.stderr!, process.stderr, "stderr"),
148
+ ].map((task) =>
149
+ task.catch((error: unknown) => {
150
+ logFailure ??= error;
151
+ stop(new HostError(`Execution logging failed: ${message(error)}`));
152
+ }),
153
+ );
154
+ }
155
+ server = new ContextServer(
156
+ child,
157
+ store,
158
+ owner,
159
+ output,
160
+ (error) => {
161
+ stop(error);
162
+ },
163
+ invocation.appCid,
164
+ );
165
+ const result = await new Promise<{
166
+ code: number | null;
167
+ signal: NodeJS.Signals | null;
168
+ }>((resolve, reject) => {
169
+ child!.once("error", reject);
170
+ child!.once("close", (code, signal) => {
171
+ resolve({ code, signal });
172
+ });
173
+ });
174
+ record.appExitCode = result.code;
175
+ await Promise.all(forwarding);
176
+ if (logs) {
177
+ await logs.close();
178
+ logs = undefined;
179
+ if (logFailure)
180
+ throw new HostError(
181
+ `Execution logging failed: ${message(logFailure)}`,
182
+ 1,
183
+ "LOG_FAILED",
184
+ "logging",
185
+ );
186
+ record.log = "complete";
187
+ }
188
+ phase = "execution";
189
+ await server.close();
190
+ server = undefined;
191
+ if (controller.signal.aborted && !cancellation)
192
+ controller.signal.throwIfAborted();
193
+ if (cancellation || result.signal) {
194
+ cancellation ||= result.signal === "SIGINT" ? 130 : 143;
195
+ throw new HostError(
196
+ "Execution cancelled.",
197
+ cancellation,
198
+ "CANCELLED",
199
+ "execution",
200
+ );
201
+ }
202
+ controller.signal.throwIfAborted();
203
+ if (result.code !== 0)
204
+ throw new HostError(
205
+ `App exited with code ${result.code}.`,
206
+ result.code ?? 1,
207
+ "APP_EXIT",
208
+ "execution",
209
+ );
210
+ phase = "commit";
211
+ record.outputCid = await output.finalize();
212
+ record.status = "succeeded";
213
+ exitCode = 0;
214
+ } catch (error) {
215
+ const failure =
216
+ error instanceof HostError
217
+ ? error
218
+ : new HostError(message(error), 1, "EXECUTION_FAILED", phase);
219
+ record.status = cancellation ? "cancelled" : "failed";
220
+ record.error = {
221
+ phase: failure.phase === "state" ? phase : failure.phase,
222
+ code: failure.code,
223
+ message: message(failure),
224
+ };
225
+ exitCode =
226
+ cancellation ||
227
+ (record.appExitCode && record.appExitCode !== 0
228
+ ? record.appExitCode
229
+ : failure.exitCode);
230
+ options.diagnostic(`Error: ${message(failure)}`);
231
+ } finally {
232
+ if (timer) clearTimeout(timer);
233
+ process.off("SIGINT", interrupt);
234
+ process.off("SIGTERM", terminate);
235
+ options.signal?.removeEventListener("abort", abort);
236
+ const cleanupError = (error: unknown, errorPhase: string) => {
237
+ options.diagnostic(
238
+ `Error: ${errorPhase} failed: ${message(error)} Ownership remains recoverable.`,
239
+ );
240
+ record.status = record.status === "cancelled" ? "cancelled" : "failed";
241
+ record.error = {
242
+ phase: errorPhase,
243
+ code: "CLEANUP_FAILED",
244
+ message: message(error),
245
+ };
246
+ if (exitCode === 0) exitCode = 1;
247
+ };
248
+ await Promise.all(forwarding);
249
+ try {
250
+ await logs?.close();
251
+ } catch (error) {
252
+ cleanupError(error, "logging");
253
+ }
254
+ try {
255
+ await server?.close();
256
+ } catch (error) {
257
+ cleanupError(error, "cleanup");
258
+ }
259
+ try {
260
+ if (entryCreated) await unlink(entry);
261
+ if (directoryCreated) await rmdir(directory);
262
+ } catch (error) {
263
+ cleanupError(error, "cleanup");
264
+ }
265
+ record.endedAt = new Date().toISOString();
266
+ try {
267
+ if (options.history)
268
+ await saveHistory(state, store, record, options.retain);
269
+ else if (record.outputCid && options.retain)
270
+ options.diagnostic(
271
+ "History is disabled: output has no history-owned retention and may be reclaimed by its backend.",
272
+ );
273
+ } catch (error) {
274
+ cleanupError(error, "history");
275
+ }
276
+ try {
277
+ await owner.release();
278
+ } catch (error) {
279
+ cleanupError(error, "cleanup");
280
+ }
281
+ if (options.history) {
282
+ // Do not resurrect a record concurrently removed after its committed publication.
283
+ try {
284
+ state.transaction(() => {
285
+ if (state.db.prepare("SELECT id FROM runs WHERE id=?").get(id)) {
286
+ const current = state.run(id);
287
+ if (current.retention.state === "releasing")
288
+ record.retention = current.retention;
289
+ state.saveRun(record);
290
+ }
291
+ });
292
+ } catch (error) {
293
+ cleanupError(error, "history");
294
+ }
295
+ options.diagnostic(`Execution: ${id}`);
296
+ }
297
+ if (record.outputCid) options.diagnostic(`Output: ${record.outputCid}`);
298
+ }
299
+ return { exitCode, record };
300
+ }
@@ -0,0 +1,136 @@
1
+ import { relative, isAbsolute, sep } from "node:path";
2
+ import { createHash } from "node:crypto";
3
+ import ignore from "ignore";
4
+ import { stringify } from "yaml";
5
+ import { bundleLimits } from "@ipab/bundle";
6
+ import { listTree, readBytes } from "@ipab/bundle-builder";
7
+ import { filesystemTree } from "@ipab/bundle-builder/node";
8
+ import { nodeError, type AuthoringOptions } from "./authoring.js";
9
+ import { HostError } from "./errors.js";
10
+
11
+ export const sourceSchema = {
12
+ name: "IPAB App Source",
13
+ description:
14
+ "App project source snapshot; build inputs are ordinary resources.",
15
+ entry: {
16
+ path: "package.json",
17
+ contentType: "application/json",
18
+ schema: { type: "object" },
19
+ defaultValue: {},
20
+ },
21
+ } as const;
22
+
23
+ export async function captureSource(
24
+ root: string,
25
+ excludedOutputs: readonly string[],
26
+ options: AuthoringOptions = {},
27
+ ) {
28
+ const key = (path: string) =>
29
+ process.platform === "win32" ? path.toLowerCase() : path;
30
+ const outputs = excludedOutputs.flatMap((output) => {
31
+ const path = relative(root, output);
32
+ return path &&
33
+ !isAbsolute(path) &&
34
+ path !== ".." &&
35
+ !path.startsWith(`..${sep}`)
36
+ ? [key(path.split(sep).join("/"))]
37
+ : [];
38
+ });
39
+ const rules = new Map<string, ReturnType<typeof ignore>>();
40
+ const excluded = (path: string, directory: boolean) => {
41
+ const normalized = key(path);
42
+ if (
43
+ normalized
44
+ .split("/")
45
+ .some((part) => [".git", "node_modules"].includes(part)) ||
46
+ normalized === ".bundle-ignore" ||
47
+ normalized === "dist" ||
48
+ normalized.startsWith("dist/") ||
49
+ normalized.split("/")[0]!.startsWith(".ipab-app-") ||
50
+ outputs.some(
51
+ (output) =>
52
+ normalized === output || normalized.startsWith(`${output}/`),
53
+ )
54
+ )
55
+ return true;
56
+ let ignored = false;
57
+ for (const [prefix, matcher] of rules) {
58
+ if (prefix && !path.startsWith(prefix)) continue;
59
+ const match = matcher.test(
60
+ `${path.slice(prefix.length)}${directory ? "/" : ""}`,
61
+ );
62
+ if (match.ignored) ignored = true;
63
+ else if (match.unignored) ignored = false;
64
+ }
65
+ return ignored;
66
+ };
67
+ const original = await filesystemTree(root);
68
+ const selected = await filesystemTree(root, { exclude: excluded });
69
+ const files = new Map<string, Uint8Array>();
70
+ let bytes = 0;
71
+ let paths = 0;
72
+ const visit = async (directory: string, depth: number): Promise<void> => {
73
+ if (depth > bundleLimits.depth)
74
+ throw new HostError(
75
+ "Source snapshot exceeds the Bundle tree depth limit.",
76
+ );
77
+ const prefix = directory ? `${directory}/` : "";
78
+ try {
79
+ const text = await readBytes(
80
+ original,
81
+ `${prefix}.gitignore`,
82
+ 64 * 1024,
83
+ options,
84
+ );
85
+ rules.set(
86
+ prefix,
87
+ ignore({ ignorecase: false }).add(
88
+ new TextDecoder("utf-8", { fatal: true }).decode(text),
89
+ ),
90
+ );
91
+ } catch (cause) {
92
+ if (!nodeError(cause, "ENOENT")) throw cause;
93
+ }
94
+ for (const entry of await listTree(selected, directory, options)) {
95
+ if (++paths > bundleLimits.files)
96
+ throw new HostError("Source snapshot exceeds the Bundle path limit.");
97
+ const path = `${prefix}${entry.name}`;
98
+ if (entry.kind === "directory") await visit(path, depth + 1);
99
+ else {
100
+ const content = await readBytes(
101
+ selected,
102
+ path,
103
+ bundleLimits.bytes - bytes,
104
+ options,
105
+ );
106
+ bytes += content.length;
107
+ files.set(path, content);
108
+ }
109
+ }
110
+ };
111
+ await visit("", 0);
112
+ if (!files.has(".bundle.yaml")) {
113
+ if (excluded(".bundle.yaml", false))
114
+ throw new HostError("Source .bundle.yaml is excluded by .gitignore.");
115
+ files.set(
116
+ ".bundle.yaml",
117
+ new TextEncoder().encode(stringify(sourceSchema)),
118
+ );
119
+ }
120
+ if (!files.has("package.json"))
121
+ throw new HostError("Source package.json is excluded by .gitignore.");
122
+ return files;
123
+ }
124
+
125
+ export function sourceFingerprint(
126
+ files: ReadonlyMap<string, Uint8Array>,
127
+ ): string {
128
+ const hash = createHash("sha256");
129
+ for (const [path, bytes] of [...files].sort(([a], [b]) =>
130
+ a < b ? -1 : a > b ? 1 : 0,
131
+ )) {
132
+ hash.update(JSON.stringify([path, bytes.length]));
133
+ hash.update(bytes);
134
+ }
135
+ return hash.digest("hex");
136
+ }