@ipab/cli 0.1.0-rc.5 → 0.1.0-rc.6

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 (94) hide show
  1. package/README.md +82 -15
  2. package/dist/app-templates.js +1 -1
  3. package/dist/app-templates.js.map +1 -1
  4. package/dist/builtins/skill.ipab.car +0 -0
  5. package/dist/builtins/template.node.car +0 -0
  6. package/dist/builtins/template.web-app.car +0 -0
  7. package/dist/cli.d.ts +3 -1
  8. package/dist/cli.d.ts.map +1 -1
  9. package/dist/cli.js +561 -272
  10. package/dist/cli.js.map +1 -1
  11. package/dist/content-provider.d.ts +1 -1
  12. package/dist/content-provider.d.ts.map +1 -1
  13. package/dist/content-provider.js +4 -3
  14. package/dist/content-provider.js.map +1 -1
  15. package/dist/context.d.ts +0 -1
  16. package/dist/context.d.ts.map +1 -1
  17. package/dist/context.js +0 -10
  18. package/dist/context.js.map +1 -1
  19. package/dist/doctor.d.ts +29 -0
  20. package/dist/doctor.d.ts.map +1 -0
  21. package/dist/doctor.js +576 -0
  22. package/dist/doctor.js.map +1 -0
  23. package/dist/identity.d.ts +1 -1
  24. package/dist/identity.d.ts.map +1 -1
  25. package/dist/identity.js +9 -9
  26. package/dist/identity.js.map +1 -1
  27. package/dist/ipc.d.ts +1 -2
  28. package/dist/ipc.d.ts.map +1 -1
  29. package/dist/ipc.js +1 -10
  30. package/dist/ipc.js.map +1 -1
  31. package/dist/kubo-install.d.ts +18 -1
  32. package/dist/kubo-install.d.ts.map +1 -1
  33. package/dist/kubo-install.js +424 -61
  34. package/dist/kubo-install.js.map +1 -1
  35. package/dist/kubo-release.d.ts +19 -0
  36. package/dist/kubo-release.d.ts.map +1 -1
  37. package/dist/kubo-release.js +164 -0
  38. package/dist/kubo-release.js.map +1 -1
  39. package/dist/kubo.d.ts +1 -0
  40. package/dist/kubo.d.ts.map +1 -1
  41. package/dist/kubo.js +102 -96
  42. package/dist/kubo.js.map +1 -1
  43. package/dist/pins.d.ts +15 -17
  44. package/dist/pins.d.ts.map +1 -1
  45. package/dist/pins.js +144 -106
  46. package/dist/pins.js.map +1 -1
  47. package/dist/publish-source.d.ts +3 -0
  48. package/dist/publish-source.d.ts.map +1 -0
  49. package/dist/publish-source.js +85 -0
  50. package/dist/publish-source.js.map +1 -0
  51. package/dist/runtime.d.ts.map +1 -1
  52. package/dist/runtime.js +1 -3
  53. package/dist/runtime.js.map +1 -1
  54. package/dist/state-storage-windows.js +1 -1
  55. package/dist/state-storage.d.ts +3 -1
  56. package/dist/state-storage.d.ts.map +1 -1
  57. package/dist/state-storage.js +38 -7
  58. package/dist/state-storage.js.map +1 -1
  59. package/dist/state.d.ts +40 -6
  60. package/dist/state.d.ts.map +1 -1
  61. package/dist/state.js +208 -82
  62. package/dist/state.js.map +1 -1
  63. package/dist/swarm-envelope.d.ts +1 -0
  64. package/dist/swarm-envelope.d.ts.map +1 -1
  65. package/dist/swarm-envelope.js +12 -0
  66. package/dist/swarm-envelope.js.map +1 -1
  67. package/dist/swarm.d.ts +64 -8
  68. package/dist/swarm.d.ts.map +1 -1
  69. package/dist/swarm.js +858 -106
  70. package/dist/swarm.js.map +1 -1
  71. package/package.json +4 -4
  72. package/src/app-templates.ts +1 -1
  73. package/src/cli.ts +702 -338
  74. package/src/content-provider.ts +4 -2
  75. package/src/context.ts +0 -10
  76. package/src/doctor.ts +902 -0
  77. package/src/identity.ts +10 -10
  78. package/src/ipc.ts +0 -8
  79. package/src/kubo-install.ts +562 -78
  80. package/src/kubo-release.ts +213 -0
  81. package/src/kubo.ts +134 -106
  82. package/src/pins.ts +188 -126
  83. package/src/publish-source.ts +103 -0
  84. package/src/runtime.ts +0 -3
  85. package/src/state-storage-windows.ts +1 -1
  86. package/src/state-storage.ts +53 -7
  87. package/src/state.ts +357 -98
  88. package/src/swarm-envelope.ts +14 -0
  89. package/src/swarm.ts +1234 -125
  90. package/dist/setup.d.ts +0 -8
  91. package/dist/setup.d.ts.map +0 -1
  92. package/dist/setup.js +0 -27
  93. package/dist/setup.js.map +0 -1
  94. package/src/setup.ts +0 -34
package/src/pins.ts CHANGED
@@ -5,19 +5,14 @@ import { openBundle } from "@ipab/bundle";
5
5
  import { HostError, message } from "./errors.js";
6
6
  import { alive, type StoreFactory } from "./history.js";
7
7
  import {
8
- exactCid,
9
- pinName,
10
8
  bundlePinMetadata,
9
+ exactCid,
10
+ type ContentPin,
11
11
  type NamedPin,
12
- type PinMetadata,
13
12
  type State,
14
13
  } from "./state.js";
15
14
 
16
15
  export function pinDetails(pin: NamedPin) {
17
- if (pin.status !== "ready" || !pin.metadata)
18
- throw new HostError(
19
- `Pin "${pin.name}" is ${pin.status}. Retry ipab pin add ${pin.name} ${pin.cid}, or ipab pin delete ${pin.name}.`,
20
- );
21
16
  return {
22
17
  name: pin.name,
23
18
  cid: pin.cid,
@@ -26,15 +21,7 @@ export function pinDetails(pin: NamedPin) {
26
21
  };
27
22
  }
28
23
 
29
- function requiredPin(state: State, name: string): NamedPin {
30
- pinName(name);
31
- const pin = state.pin(name);
32
- if (!pin)
33
- throw new HostError(`Pin "${name}" does not exist. Run ipab pin list.`);
34
- return pin;
35
- }
36
-
37
- function idleHold(state: State, pin: NamedPin) {
24
+ function claim(state: State, pin: ContentPin) {
38
25
  const hold = state.hold(pin.owner);
39
26
  if (!hold)
40
27
  throw new HostError(
@@ -42,159 +29,234 @@ function idleHold(state: State, pin: NamedPin) {
42
29
  );
43
30
  if (hold.pid !== null && alive(hold.pid))
44
31
  throw new HostError(
45
- `Pin "${pin.name}" has an active operation; retry after it finishes.`,
32
+ `Pin ${pin.reference} has an active operation; retry after it finishes.`,
46
33
  );
47
- return hold;
34
+ state.saveHold({ ...hold, pid: process.pid });
48
35
  }
49
-
50
- async function classify(
51
- cid: string,
52
- store: IpfsStore,
53
- ): Promise<Extract<PinMetadata, { kind: "bundle" }>> {
54
- const root = CID.parse(cid);
55
- const resolveCid = (cid: CID, options: { signal?: AbortSignal }) =>
56
- store.block.get(cid.toString(), options);
57
- const bundle = await openBundle(root, { resolveCid });
58
- return {
59
- kind: "bundle",
60
- title: bundle.manifest.title,
61
- schemaCid: bundle.schemaKey,
62
- };
36
+ export function refreshPinClaim(
37
+ state: State,
38
+ saved: ContentPin,
39
+ ): ContentPin | undefined {
40
+ return state.transaction(() => {
41
+ const current = state.contentPin(saved.reference);
42
+ if (
43
+ !current ||
44
+ current.owner !== saved.owner ||
45
+ current.status === "deleting"
46
+ )
47
+ return undefined;
48
+ claim(state, current);
49
+ return current;
50
+ });
63
51
  }
64
52
 
65
- export async function addPin(
53
+ export function reservePin(
66
54
  state: State,
67
- name: string,
68
- input: string,
55
+ reference: string,
69
56
  configuration: IpfsStore["configuration"],
70
- factory: StoreFactory = (config) => new IpfsStore(config),
71
- ) {
72
- pinName(name);
73
- const cid = exactCid(input);
74
- const pin = state.transaction(() => {
75
- const old = state.pin(name);
57
+ shared?: { swarm: string; name: string },
58
+ ): ContentPin {
59
+ return state.transaction(() => {
60
+ const old = state.contentPin(reference);
76
61
  if (old) {
77
- if (old.status !== "pending" || old.cid !== cid)
78
- throw new HostError(
79
- `Pin name "${name}" is occupied; no replace is supported.`,
80
- );
81
- const hold = idleHold(state, old);
82
- state.saveHold({ ...hold, pid: process.pid });
62
+ if (old.status === "deleting")
63
+ throw new HostError("Pin deletion is incomplete; retry unpin first.");
64
+ claim(state, old);
83
65
  return old;
84
66
  }
85
- const owner = `ipab:${state.identity}:pin:${randomUUID()}`;
86
- const reserved: NamedPin = {
87
- name,
88
- cid,
89
- owner,
67
+ const pin: ContentPin = {
68
+ reference,
69
+ owner: `ipab:${state.identity}:pin:${randomUUID()}`,
70
+ cid: null,
71
+ targetCid: null,
72
+ swarm: shared?.swarm ?? null,
73
+ name: shared?.name ?? null,
90
74
  status: "pending",
91
- metadata: null,
75
+ freshness: "stale",
76
+ error: null,
92
77
  };
93
- state.savePin(reserved);
94
- // Reserve the name and original backend before any Store side effect.
78
+ state.saveContentPin(pin);
95
79
  state.saveHold({
96
- owner,
80
+ owner: pin.owner,
97
81
  backend: configuration,
98
82
  roots: [],
99
83
  pid: process.pid,
100
84
  session: null,
101
85
  recordId: null,
102
86
  });
103
- return reserved;
87
+ return pin;
104
88
  });
105
- let store: IpfsStore | undefined;
106
- let finished = false;
89
+ }
90
+
91
+ /** Confirm the complete new version before reducing this owner's saved roots. */
92
+ export async function retainPin(
93
+ state: State,
94
+ pin: ContentPin,
95
+ store: IpfsStore,
96
+ version: { cid: string; targetCid: string; roots: readonly string[] },
97
+ ): Promise<ContentPin> {
98
+ const backend = state.hold(pin.owner)!.backend;
99
+ let base: IpfsStore | undefined;
100
+ let original: IpfsStore | undefined;
107
101
  try {
108
- store = factory(state.hold(pin.owner)!.backend);
109
- await store.recoverOwner(pin.owner, () => state.hold(pin.owner)!.roots);
110
- const metadata = await classify(cid, store);
111
- await store.retain(pin.owner, [cid]);
112
- state.transaction(() => {
113
- state.savePin({ ...pin, metadata });
114
- state.saveHold({ ...state.hold(pin.owner)!, roots: [cid] });
102
+ if (JSON.stringify(backend) !== JSON.stringify(store.configuration)) {
103
+ base = new IpfsStore(backend);
104
+ original = base.withLocalSource({
105
+ block: { get: (cid, options) => store.block.get(cid, options) },
106
+ });
107
+ }
108
+ const retainedStore = original ?? store;
109
+ await base?.close();
110
+ await retainedStore.recoverOwner(
111
+ pin.owner,
112
+ () => state.hold(pin.owner)!.roots,
113
+ );
114
+ await openBundle(CID.parse(version.cid), {
115
+ resolveCid: (cid) => retainedStore.block.get(cid.toString()),
115
116
  });
116
- await store.confirmRetained(pin.owner, [cid]);
117
- await store.close();
118
- store = undefined;
119
- const ready: NamedPin = { ...pin, status: "ready", metadata };
117
+ const roots = [...new Set(version.roots.map((root) => exactCid(root)))];
118
+ if (
119
+ !roots.includes(exactCid(version.cid)) ||
120
+ !roots.includes(exactCid(version.targetCid))
121
+ )
122
+ throw new HostError(
123
+ "Pin roots must include its exact payload and target version.",
124
+ );
125
+ await retainedStore.retain(pin.owner, roots);
126
+ const hold = state.hold(pin.owner)!;
127
+ state.saveHold({ ...hold, roots: [...new Set([...hold.roots, ...roots])] });
128
+ await retainedStore.confirmRetained(pin.owner, roots);
129
+ const ready: ContentPin = {
130
+ ...pin,
131
+ cid: version.cid,
132
+ targetCid: version.targetCid,
133
+ status: "ready",
134
+ freshness: "current",
135
+ error: null,
136
+ };
120
137
  state.transaction(() => {
121
- state.savePin(ready);
122
- state.saveHold({ ...state.hold(pin.owner)!, pid: null });
138
+ state.saveContentPin(ready);
139
+ state.saveHold({ ...state.hold(pin.owner)!, roots });
123
140
  });
124
- finished = true;
125
- return pinDetails(ready);
141
+ await retainedStore.reconcile(
142
+ pin.owner,
143
+ () => state.hold(pin.owner)!.roots,
144
+ );
145
+ return ready;
126
146
  } catch (cause) {
147
+ const current = state.contentPin(pin.reference)!;
148
+ state.saveContentPin({
149
+ ...current,
150
+ freshness: "stale",
151
+ error: message(cause),
152
+ });
127
153
  throw new HostError(
128
- `Pin add incomplete for "${name}": ${message(cause)}. Durable recovery data is preserved; retry the same add or delete this pending pin.`,
154
+ `Pin ${pin.reference} is stale: ${message(cause)}. Its last verified version and durable recovery data are preserved; retry pin or unpin.`,
129
155
  1,
130
156
  "PIN_INCOMPLETE",
131
157
  );
132
158
  } finally {
133
159
  try {
134
- await store?.close();
160
+ await original?.close();
161
+ await base?.close();
135
162
  } finally {
136
163
  const hold = state.hold(pin.owner);
137
- if (hold && !finished) state.saveHold({ ...hold, pid: null });
164
+ if (hold) state.saveHold({ ...hold, pid: null });
138
165
  }
139
166
  }
140
167
  }
141
168
 
142
- export async function deletePin(
169
+ export async function pinCid(
143
170
  state: State,
144
- name: string,
145
- factory: StoreFactory = (config) => new IpfsStore(config),
171
+ input: string,
172
+ store: IpfsStore,
173
+ roots: readonly string[] = [input],
146
174
  ) {
147
- const pin = state.transaction(() => {
148
- const pin = requiredPin(state, name);
149
- const hold = idleHold(state, pin);
150
- state.savePin({ ...pin, status: "deleting" });
151
- state.saveHold({ ...hold, roots: [], pid: process.pid });
152
- return pin;
175
+ const cid = exactCid(input);
176
+ const pin = reservePin(state, cid, store.configuration);
177
+ return retainPin(state, pin, store, { cid, targetCid: cid, roots });
178
+ }
179
+
180
+ export function failedPin(
181
+ state: State,
182
+ reference: string,
183
+ cause: unknown,
184
+ missing = false,
185
+ ) {
186
+ const pin = state.contentPin(reference);
187
+ if (!pin) return;
188
+ state.saveContentPin({
189
+ ...pin,
190
+ freshness: missing ? "missing" : "stale",
191
+ error: message(cause),
153
192
  });
154
- let store: IpfsStore | undefined;
155
- try {
156
- store = factory(state.hold(pin.owner)!.backend);
157
- await store.recoverOwner(pin.owner, () => state.hold(pin.owner)!.roots);
158
- await store.reconcile(pin.owner, () => state.hold(pin.owner)!.roots);
159
- await store.close();
160
- store = undefined;
193
+ const hold = state.hold(pin.owner);
194
+ if (hold && !missing) state.saveHold({ ...hold, pid: null });
195
+ }
196
+
197
+ export async function unpin(
198
+ state: State,
199
+ reference: string,
200
+ factory: StoreFactory = (config) => new IpfsStore(config),
201
+ ) {
202
+ const pin = state.contentPin(reference);
203
+ const archived = state.archivedPins().filter((pin) => pin.cid === reference);
204
+ const owners = [...(pin ? [pin] : []), ...archived];
205
+ for (const record of owners) {
161
206
  state.transaction(() => {
162
- state.deletePin(name);
163
- state.deleteHold(pin.owner);
207
+ if ("reference" in record) claim(state, record);
208
+ else {
209
+ const hold = state.hold(record.owner);
210
+ if (!hold)
211
+ throw new HostError(
212
+ "Archived pin retention metadata is missing; recovery is blocked.",
213
+ );
214
+ if (hold.pid !== null && alive(hold.pid))
215
+ throw new HostError("Archived pin has an active operation.");
216
+ state.saveHold({ ...hold, pid: process.pid });
217
+ }
218
+ if ("reference" in record)
219
+ state.saveContentPin({ ...record, status: "deleting" });
220
+ state.saveHold({ ...state.hold(record.owner)!, roots: [] });
164
221
  });
165
- return {
166
- removed: [name],
167
- retentionClaimsReleased: true,
168
- garbageCollectionGuaranteed: false,
169
- };
170
- } catch (cause) {
171
- throw new HostError(
172
- `Pin deletion incomplete for "${name}": ${message(cause)}. Retry ipab pin delete ${name}; original backend and recovery data are preserved. No GC requested.`,
173
- 1,
174
- "RELEASE_FAILED",
175
- "cleanup",
176
- );
177
- } finally {
222
+ let store: IpfsStore | undefined;
178
223
  try {
179
- await store?.close();
224
+ store = factory(state.hold(record.owner)!.backend);
225
+ await store.recoverOwner(
226
+ record.owner,
227
+ () => state.hold(record.owner)!.roots,
228
+ );
229
+ await store.reconcile(
230
+ record.owner,
231
+ () => state.hold(record.owner)!.roots,
232
+ );
233
+ await store.close();
234
+ store = undefined;
235
+ state.transaction(() => {
236
+ if ("reference" in record) state.deleteContentPin(record.reference);
237
+ else state.deletePin(record.name);
238
+ state.deleteHold(record.owner);
239
+ });
240
+ } catch (cause) {
241
+ throw new HostError(
242
+ `Unpin incomplete for ${reference}: ${message(cause)}. Retry the same unpin; original Store ownership and recovery data are preserved. No GC requested.`,
243
+ 1,
244
+ "RELEASE_FAILED",
245
+ "cleanup",
246
+ );
180
247
  } finally {
181
- const hold = state.hold(pin.owner);
182
- if (hold) state.saveHold({ ...hold, pid: null });
248
+ try {
249
+ await store?.close();
250
+ } finally {
251
+ const hold = state.hold(record.owner);
252
+ if (hold) state.saveHold({ ...hold, pid: null });
253
+ }
183
254
  }
184
255
  }
185
- }
186
-
187
- export function renamePin(state: State, oldName: string, newName: string) {
188
- pinName(newName);
189
- return state.transaction(() => {
190
- const pin = requiredPin(state, oldName);
191
- const details = pinDetails(pin);
192
- idleHold(state, pin);
193
- if (oldName === newName) return details;
194
- if (state.pin(newName))
195
- throw new HostError(`Pin name "${newName}" is occupied.`);
196
- state.deletePin(oldName);
197
- state.savePin({ ...pin, name: newName });
198
- return { ...details, name: newName };
199
- });
256
+ return {
257
+ reference,
258
+ releasedOwners: owners.map((record) => record.owner),
259
+ retentionClaimsReleased: true,
260
+ garbageCollectionGuaranteed: false,
261
+ };
200
262
  }
@@ -0,0 +1,103 @@
1
+ import { lstat } from "node:fs/promises";
2
+ import { basename, dirname, extname, resolve } from "node:path";
3
+ import { CID } from "multiformats/cid";
4
+ import { CarBlockIterator } from "@ipld/car/iterator";
5
+ import { encodeBundleCar, memoryTree, readBytes } from "@ipab/bundle-builder";
6
+ import { filesystemTree } from "@ipab/bundle-builder/node";
7
+ import { bundleLimits } from "@ipab/bundle";
8
+ import type { IpfsStore } from "@ipab/ipfs-store";
9
+ import { HostError } from "./errors.js";
10
+ import { importBundle, nodeError, selectedTree } from "./authoring.js";
11
+ import { captureSource, sourceFingerprint } from "./source-bundle.js";
12
+ import { exactCid } from "./state.js";
13
+
14
+ export async function publicationSource(
15
+ input: string,
16
+ store: IpfsStore,
17
+ ): Promise<string> {
18
+ try {
19
+ CID.parse(input);
20
+ return exactCid(input);
21
+ } catch {
22
+ // Non-CID inputs must be explicit existing local sources.
23
+ }
24
+ const path = resolve(input);
25
+ let stat;
26
+ try {
27
+ stat = await lstat(path);
28
+ } catch (cause) {
29
+ if (nodeError(cause, "ENOENT"))
30
+ throw new HostError(
31
+ "Publication SOURCE must be an exact CID, a CAR, a regular file or a directory.",
32
+ );
33
+ throw cause;
34
+ }
35
+ if (stat.isSymbolicLink() || (!stat.isFile() && !stat.isDirectory()))
36
+ throw new HostError(
37
+ "Publication SOURCE must be a regular file or directory, never a symlink.",
38
+ );
39
+ if (stat.isFile() && extname(path).toLowerCase() === ".car")
40
+ return (await importBundle(path, () => Promise.resolve(store))).cid;
41
+ let tree;
42
+ let snapshot: Map<string, Uint8Array> | undefined;
43
+ if (stat.isDirectory()) {
44
+ try {
45
+ await lstat(resolve(path, ".bundle.yaml"));
46
+ tree = await selectedTree(path, undefined, resolve(path, "dist"), {});
47
+ } catch (cause) {
48
+ if (!nodeError(cause, "ENOENT")) throw cause;
49
+ snapshot = await captureSource(path, []);
50
+ tree = memoryTree(snapshot);
51
+ }
52
+ } else {
53
+ const name = basename(path);
54
+ const types: Record<string, string> = {
55
+ ".json": "application/json",
56
+ ".yaml": "application/yaml",
57
+ ".yml": "application/yaml",
58
+ ".md": "text/markdown",
59
+ ".txt": "text/plain",
60
+ };
61
+ const contentType = types[extname(path).toLowerCase()];
62
+ if (!contentType || name.startsWith("."))
63
+ throw new HostError(
64
+ "File entry/type is ambiguous. Put the file in a directory with an explicit .bundle.yaml and referenced type file; standalone .json, .yaml, .yml, .md and .txt files are supported.",
65
+ );
66
+ const data = await readBytes(
67
+ await filesystemTree(dirname(path)),
68
+ name,
69
+ bundleLimits.bytes,
70
+ {},
71
+ );
72
+ const bytes = (value: unknown) =>
73
+ new TextEncoder().encode(JSON.stringify(value));
74
+ tree = memoryTree(
75
+ new Map([
76
+ [
77
+ ".bundle.yaml",
78
+ bytes({ title: name, entry: name, type: ".bundle-type.yaml" }),
79
+ ],
80
+ [".bundle-type.yaml", bytes({ contentType })],
81
+ [name, data],
82
+ ]),
83
+ );
84
+ }
85
+ const encoded = await encodeBundleCar(tree);
86
+ try {
87
+ for await (const block of await CarBlockIterator.fromIterable(
88
+ encoded.stream,
89
+ ))
90
+ await store.put(block.cid, block.bytes);
91
+ if (
92
+ snapshot &&
93
+ sourceFingerprint(snapshot) !==
94
+ sourceFingerprint(await captureSource(path, []))
95
+ )
96
+ throw new HostError(
97
+ "Publication source changed while capturing its Bundle; retry.",
98
+ );
99
+ return encoded.cid.toString();
100
+ } finally {
101
+ await encoded.close();
102
+ }
103
+ }
package/src/runtime.ts CHANGED
@@ -10,7 +10,6 @@ import { ContextServer } from "./ipc.js";
10
10
  import { loadApp, OutputSpace } from "./space.js";
11
11
  import type { RunRecord, State } from "./state.js";
12
12
  import { ExecutionLogs } from "./logs.js";
13
- import { verifyStateStorage } from "./state-storage.js";
14
13
  import type { BundleInspection } from "./context.js";
15
14
 
16
15
  export interface Invocation {
@@ -122,7 +121,6 @@ export async function execute(
122
121
  );
123
122
  phase = "startup";
124
123
  const runtime = join(state.directory, "runtime");
125
- verifyStateStorage(state.directory);
126
124
  await mkdir(runtime, { recursive: true, mode: 0o700 });
127
125
  await mkdir(directory, { mode: 0o700 });
128
126
  directoryCreated = true;
@@ -171,7 +169,6 @@ export async function execute(
171
169
  stop(error);
172
170
  },
173
171
  invocation.appCid,
174
- (name) => state.resolvePin(name),
175
172
  options.resolveBundleReference,
176
173
  );
177
174
  const result = await new Promise<{
@@ -37,7 +37,7 @@ function Check-Path($path) {
37
37
  $attrs = [IO.File]::GetAttributes($path)
38
38
  if ($attrs -band [IO.FileAttributes]::ReparsePoint) { throw 'Invalid state path' }
39
39
  $dir = [bool]($attrs -band [IO.FileAttributes]::Directory)
40
- $isDir = $path -eq $root -or [IO.Path]::GetFileName($path) -in 'runtime','logs','kubo-bin','swarm-nodes','swarm-credentials'
40
+ $isDir = $path -eq $root -or [IO.Path]::GetFileName($path) -in 'runtime','logs','kubo-bin','kubo-cache','swarm-nodes','swarm-credentials'
41
41
  if ($dir -ne $isDir) { throw 'Invalid state type' }
42
42
  if ($dir) { $acl = [IO.Directory]::GetAccessControl($path) }
43
43
  else { $acl = [IO.File]::GetAccessControl($path) }
@@ -31,13 +31,18 @@ const directories = [
31
31
  "runtime",
32
32
  "logs",
33
33
  "kubo-bin",
34
+ "kubo-cache",
34
35
  "swarm-nodes",
35
36
  "swarm-credentials",
36
37
  ];
37
38
  const windows = () => process.platform === "win32";
38
- function unsafe(): never {
39
+ function unsafe(reason?: string): never {
39
40
  throw new HostError(
40
- "State storage requires a dedicated, account-only regular directory and files. Stop IPAB processes, back up your state, and migrate only known IPAB files to a new private --state-dir; do not change permissions on a shared directory.",
41
+ "State storage requires a dedicated, account-only regular directory and files. " +
42
+ (reason ??
43
+ "Stop IPAB processes, back up your state, and migrate only known IPAB files to a new private --state-dir; do not change permissions on a shared directory."),
44
+ 1,
45
+ "UNSAFE_STATE_STORAGE",
41
46
  );
42
47
  }
43
48
 
@@ -222,7 +227,10 @@ function access(directory: string, initialize: boolean, sealed = false): void {
222
227
  const entries: Entry[] = [];
223
228
  for (const name of root ? readdirSync(directory) : []) {
224
229
  const dir = directories.includes(name);
225
- if (!dir && !files.includes(name)) unsafe();
230
+ if (!dir && !files.includes(name))
231
+ unsafe(
232
+ `Unexpected entry ${JSON.stringify(name)} in the state directory. Move backups or unrelated entries outside this directory; keep state.sqlite and the IPAB runtime directories in place. No files were moved or deleted.`,
233
+ );
226
234
  const info = lstatSync(join(directory, name), { throwIfNoEntry: false });
227
235
  // SQLite may unlink a transient sidecar as another connection closes.
228
236
  if (!info) {
@@ -314,16 +322,54 @@ export function prepareStateStorage(
314
322
  const path = join(directory, database);
315
323
  createFile(path);
316
324
  return path;
317
- } catch {
325
+ } catch (cause) {
326
+ if (cause instanceof HostError && cause.code === "UNSAFE_STATE_STORAGE")
327
+ throw cause;
318
328
  unsafe();
319
329
  }
320
330
  }
321
331
 
322
- export function verifyStateStorage(directory: string): void {
332
+ export function openStateStorage(
333
+ directory: string,
334
+ env: NodeJS.ProcessEnv = process.env,
335
+ ): string {
336
+ directory = resolve(directory);
337
+ const markerInfo = lstatSync(join(directory, marker), {
338
+ throwIfNoEntry: false,
339
+ });
340
+ if (!markerInfo) return prepareStateStorage(directory, env);
341
+ const root = lstatSync(directory);
342
+ if (
343
+ !root.isDirectory() ||
344
+ !markerInfo.isFile() ||
345
+ markerInfo.nlink !== 1 ||
346
+ markerInfo.size !== 0
347
+ )
348
+ unsafe();
349
+ const path = join(directory, database);
350
+ const info = lstatSync(path, { throwIfNoEntry: false });
351
+ if (!info) return prepareStateStorage(directory, env);
352
+ if (!info.isFile() || info.nlink !== 1) unsafe();
353
+ return path;
354
+ }
355
+
356
+ export function verifyStateStorage(
357
+ directory: string,
358
+ env: NodeJS.ProcessEnv = process.env,
359
+ ): void {
323
360
  try {
324
- checkLocation(resolve(directory), process.env);
361
+ checkLocation(resolve(directory), env);
325
362
  access(directory, false);
326
- } catch {
363
+ } catch (cause) {
364
+ if (cause instanceof HostError && cause.code === "UNSAFE_STATE_STORAGE")
365
+ throw cause;
327
366
  unsafe();
328
367
  }
329
368
  }
369
+
370
+ export function verifyStateLocation(
371
+ directory: string,
372
+ env: NodeJS.ProcessEnv,
373
+ ): void {
374
+ checkLocation(resolve(directory), env);
375
+ }