@ipab/cli 0.1.0-rc.1 → 0.1.0-rc.11

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 (285) hide show
  1. package/README.md +234 -9
  2. package/dist/app-authoring.d.ts +15 -0
  3. package/dist/app-authoring.d.ts.map +1 -1
  4. package/dist/app-authoring.js +144 -58
  5. package/dist/app-authoring.js.map +1 -1
  6. package/dist/app-definition.d.ts +52 -57
  7. package/dist/app-definition.d.ts.map +1 -1
  8. package/dist/app-definition.js +33 -38
  9. package/dist/app-definition.js.map +1 -1
  10. package/dist/app-prebuild.d.ts +18 -0
  11. package/dist/app-prebuild.d.ts.map +1 -1
  12. package/dist/app-prebuild.js +46 -0
  13. package/dist/app-prebuild.js.map +1 -1
  14. package/dist/app-templates.d.ts +0 -1
  15. package/dist/app-templates.d.ts.map +1 -1
  16. package/dist/app-templates.js +8 -46
  17. package/dist/app-templates.js.map +1 -1
  18. package/dist/assembly.d.ts +7 -0
  19. package/dist/assembly.d.ts.map +1 -0
  20. package/dist/assembly.js +130 -0
  21. package/dist/assembly.js.map +1 -0
  22. package/dist/authoring.d.ts +7 -8
  23. package/dist/authoring.d.ts.map +1 -1
  24. package/dist/authoring.js +59 -16
  25. package/dist/authoring.js.map +1 -1
  26. package/dist/builtins/skill.ipab.car +0 -0
  27. package/dist/builtins/template.bundle-viewer.car +0 -0
  28. package/dist/builtins/template.check.car +0 -0
  29. package/dist/builtins/template.node.car +0 -0
  30. package/dist/builtins/template.web-app.car +0 -0
  31. package/dist/builtins.d.ts.map +1 -1
  32. package/dist/builtins.js +1 -23
  33. package/dist/builtins.js.map +1 -1
  34. package/dist/bundled-skills.d.ts +14 -0
  35. package/dist/bundled-skills.d.ts.map +1 -0
  36. package/dist/bundled-skills.js +34 -0
  37. package/dist/bundled-skills.js.map +1 -0
  38. package/dist/cli.d.ts +8 -2
  39. package/dist/cli.d.ts.map +1 -1
  40. package/dist/cli.js +1967 -258
  41. package/dist/cli.js.map +1 -1
  42. package/dist/config-secret.d.ts +3 -0
  43. package/dist/config-secret.d.ts.map +1 -0
  44. package/dist/config-secret.js +12 -0
  45. package/dist/config-secret.js.map +1 -0
  46. package/dist/config.d.ts +11 -2
  47. package/dist/config.d.ts.map +1 -1
  48. package/dist/config.js +166 -8
  49. package/dist/config.js.map +1 -1
  50. package/dist/content-provider.d.ts +32 -0
  51. package/dist/content-provider.d.ts.map +1 -0
  52. package/dist/content-provider.js +222 -0
  53. package/dist/content-provider.js.map +1 -0
  54. package/dist/context-types.d.ts +12 -0
  55. package/dist/context-types.d.ts.map +1 -0
  56. package/dist/context-types.js +2 -0
  57. package/dist/context-types.js.map +1 -0
  58. package/dist/context.d.ts +26 -1
  59. package/dist/context.d.ts.map +1 -1
  60. package/dist/context.js +54 -10
  61. package/dist/context.js.map +1 -1
  62. package/dist/daemon-ui.d.ts +93 -0
  63. package/dist/daemon-ui.d.ts.map +1 -0
  64. package/dist/daemon-ui.js +713 -0
  65. package/dist/daemon-ui.js.map +1 -0
  66. package/dist/daemon.d.ts +21 -0
  67. package/dist/daemon.d.ts.map +1 -0
  68. package/dist/daemon.js +317 -0
  69. package/dist/daemon.js.map +1 -0
  70. package/dist/doctor.d.ts +32 -0
  71. package/dist/doctor.d.ts.map +1 -0
  72. package/dist/doctor.js +688 -0
  73. package/dist/doctor.js.map +1 -0
  74. package/dist/errors.d.ts +1 -8
  75. package/dist/errors.d.ts.map +1 -1
  76. package/dist/errors.js +1 -20
  77. package/dist/errors.js.map +1 -1
  78. package/dist/get.d.ts +3 -0
  79. package/dist/get.d.ts.map +1 -0
  80. package/dist/get.js +80 -0
  81. package/dist/get.js.map +1 -0
  82. package/dist/history.d.ts.map +1 -1
  83. package/dist/history.js +6 -14
  84. package/dist/history.js.map +1 -1
  85. package/dist/host-error.d.ts +9 -0
  86. package/dist/host-error.d.ts.map +1 -0
  87. package/dist/host-error.js +21 -0
  88. package/dist/host-error.js.map +1 -0
  89. package/dist/identity.d.ts +16 -0
  90. package/dist/identity.d.ts.map +1 -0
  91. package/dist/identity.js +119 -0
  92. package/dist/identity.js.map +1 -0
  93. package/dist/ipc.d.ts +5 -2
  94. package/dist/ipc.d.ts.map +1 -1
  95. package/dist/ipc.js +124 -12
  96. package/dist/ipc.js.map +1 -1
  97. package/dist/kubo-install.d.ts +26 -0
  98. package/dist/kubo-install.d.ts.map +1 -0
  99. package/dist/kubo-install.js +724 -0
  100. package/dist/kubo-install.js.map +1 -0
  101. package/dist/kubo-peering.d.ts +11 -0
  102. package/dist/kubo-peering.d.ts.map +1 -0
  103. package/dist/kubo-peering.js +93 -0
  104. package/dist/kubo-peering.js.map +1 -0
  105. package/dist/kubo-peers.d.ts +12 -0
  106. package/dist/kubo-peers.d.ts.map +1 -0
  107. package/dist/kubo-peers.js +119 -0
  108. package/dist/kubo-peers.js.map +1 -0
  109. package/dist/kubo-release.d.ts +22 -0
  110. package/dist/kubo-release.d.ts.map +1 -0
  111. package/dist/kubo-release.js +176 -0
  112. package/dist/kubo-release.js.map +1 -0
  113. package/dist/kubo-topology.d.ts +19 -0
  114. package/dist/kubo-topology.d.ts.map +1 -0
  115. package/dist/kubo-topology.js +113 -0
  116. package/dist/kubo-topology.js.map +1 -0
  117. package/dist/kubo.d.ts +85 -0
  118. package/dist/kubo.d.ts.map +1 -0
  119. package/dist/kubo.js +755 -0
  120. package/dist/kubo.js.map +1 -0
  121. package/dist/pins.d.ts +16 -18
  122. package/dist/pins.d.ts.map +1 -1
  123. package/dist/pins.js +144 -106
  124. package/dist/pins.js.map +1 -1
  125. package/dist/pivot-rpc.d.ts +62 -0
  126. package/dist/pivot-rpc.d.ts.map +1 -0
  127. package/dist/pivot-rpc.js +407 -0
  128. package/dist/pivot-rpc.js.map +1 -0
  129. package/dist/pivot-service.d.ts +16 -0
  130. package/dist/pivot-service.d.ts.map +1 -0
  131. package/dist/pivot-service.js +50 -0
  132. package/dist/pivot-service.js.map +1 -0
  133. package/dist/publish-source.d.ts +3 -0
  134. package/dist/publish-source.d.ts.map +1 -0
  135. package/dist/publish-source.js +85 -0
  136. package/dist/publish-source.js.map +1 -0
  137. package/dist/runtime.d.ts +2 -0
  138. package/dist/runtime.d.ts.map +1 -1
  139. package/dist/runtime.js +9 -4
  140. package/dist/runtime.js.map +1 -1
  141. package/dist/search-index.d.ts +64 -0
  142. package/dist/search-index.d.ts.map +1 -0
  143. package/dist/search-index.js +409 -0
  144. package/dist/search-index.js.map +1 -0
  145. package/dist/search-service.d.ts +23 -0
  146. package/dist/search-service.d.ts.map +1 -0
  147. package/dist/search-service.js +116 -0
  148. package/dist/search-service.js.map +1 -0
  149. package/dist/skill-definition.d.ts +6 -0
  150. package/dist/skill-definition.d.ts.map +1 -0
  151. package/dist/skill-definition.js +38 -0
  152. package/dist/skill-definition.js.map +1 -0
  153. package/dist/skill-source.d.ts +9 -0
  154. package/dist/skill-source.d.ts.map +1 -0
  155. package/dist/skill-source.js +24 -0
  156. package/dist/skill-source.js.map +1 -0
  157. package/dist/skills.d.ts +104 -0
  158. package/dist/skills.d.ts.map +1 -0
  159. package/dist/skills.js +894 -0
  160. package/dist/skills.js.map +1 -0
  161. package/dist/source-bundle.d.ts +3 -8
  162. package/dist/source-bundle.d.ts.map +1 -1
  163. package/dist/source-bundle.js +17 -12
  164. package/dist/source-bundle.js.map +1 -1
  165. package/dist/space-path.d.ts +3 -0
  166. package/dist/space-path.d.ts.map +1 -0
  167. package/dist/space-path.js +17 -0
  168. package/dist/space-path.js.map +1 -0
  169. package/dist/space.d.ts +16 -4
  170. package/dist/space.d.ts.map +1 -1
  171. package/dist/space.js +170 -24
  172. package/dist/space.js.map +1 -1
  173. package/dist/state-storage-windows.d.ts +2 -0
  174. package/dist/state-storage-windows.d.ts.map +1 -0
  175. package/dist/state-storage-windows.js +114 -0
  176. package/dist/state-storage-windows.js.map +1 -0
  177. package/dist/state-storage.d.ts +5 -0
  178. package/dist/state-storage.d.ts.map +1 -0
  179. package/dist/state-storage.js +333 -0
  180. package/dist/state-storage.js.map +1 -0
  181. package/dist/state.d.ts +135 -13
  182. package/dist/state.d.ts.map +1 -1
  183. package/dist/state.js +577 -92
  184. package/dist/state.js.map +1 -1
  185. package/dist/swarm-envelope.d.ts +57 -0
  186. package/dist/swarm-envelope.d.ts.map +1 -0
  187. package/dist/swarm-envelope.js +299 -0
  188. package/dist/swarm-envelope.js.map +1 -0
  189. package/dist/swarm-files.d.ts +6 -0
  190. package/dist/swarm-files.d.ts.map +1 -0
  191. package/dist/swarm-files.js +116 -0
  192. package/dist/swarm-files.js.map +1 -0
  193. package/dist/swarm-meta.d.ts +15 -0
  194. package/dist/swarm-meta.d.ts.map +1 -0
  195. package/dist/swarm-meta.js +68 -0
  196. package/dist/swarm-meta.js.map +1 -0
  197. package/dist/swarm-observations.d.ts +40 -0
  198. package/dist/swarm-observations.d.ts.map +1 -0
  199. package/dist/swarm-observations.js +271 -0
  200. package/dist/swarm-observations.js.map +1 -0
  201. package/dist/swarm.d.ts +537 -0
  202. package/dist/swarm.d.ts.map +1 -0
  203. package/dist/swarm.js +4991 -0
  204. package/dist/swarm.js.map +1 -0
  205. package/dist/template-definition.d.ts +47 -52
  206. package/dist/template-definition.d.ts.map +1 -1
  207. package/dist/template-definition.js +36 -41
  208. package/dist/template-definition.js.map +1 -1
  209. package/dist/template-paths.d.ts +7 -0
  210. package/dist/template-paths.d.ts.map +1 -0
  211. package/dist/template-paths.js +23 -0
  212. package/dist/template-paths.js.map +1 -0
  213. package/dist/template-presentation.d.ts +20 -0
  214. package/dist/template-presentation.d.ts.map +1 -0
  215. package/dist/template-presentation.js +133 -0
  216. package/dist/template-presentation.js.map +1 -0
  217. package/dist/template-source.d.ts +4 -1
  218. package/dist/template-source.d.ts.map +1 -1
  219. package/dist/template-source.js +11 -4
  220. package/dist/template-source.js.map +1 -1
  221. package/dist/templates.d.ts +11 -0
  222. package/dist/templates.d.ts.map +1 -0
  223. package/dist/templates.js +53 -0
  224. package/dist/templates.js.map +1 -0
  225. package/dist/unixfs-tree.d.ts +67 -0
  226. package/dist/unixfs-tree.d.ts.map +1 -0
  227. package/dist/unixfs-tree.js +329 -0
  228. package/dist/unixfs-tree.js.map +1 -0
  229. package/package.json +14 -7
  230. package/src/app-authoring.ts +240 -76
  231. package/src/app-definition.ts +33 -39
  232. package/src/app-prebuild.ts +61 -0
  233. package/src/app-templates.ts +17 -73
  234. package/src/assembly.ts +185 -0
  235. package/src/authoring.ts +99 -18
  236. package/src/builtins.ts +2 -27
  237. package/src/bundled-skills.ts +60 -0
  238. package/src/cli.ts +2461 -323
  239. package/src/config-secret.ts +14 -0
  240. package/src/config.ts +214 -8
  241. package/src/content-provider.ts +299 -0
  242. package/src/context-types.ts +11 -0
  243. package/src/context.ts +98 -10
  244. package/src/daemon-ui.ts +812 -0
  245. package/src/daemon.ts +386 -0
  246. package/src/doctor.ts +1092 -0
  247. package/src/errors.ts +1 -25
  248. package/src/get.ts +91 -0
  249. package/src/history.ts +5 -15
  250. package/src/host-error.ts +26 -0
  251. package/src/identity.ts +175 -0
  252. package/src/ipc.ts +160 -11
  253. package/src/kubo-install.ts +936 -0
  254. package/src/kubo-peering.ts +126 -0
  255. package/src/kubo-peers.ts +144 -0
  256. package/src/kubo-release.ts +230 -0
  257. package/src/kubo-topology.ts +148 -0
  258. package/src/kubo.ts +1088 -0
  259. package/src/pins.ts +188 -126
  260. package/src/pivot-rpc.ts +601 -0
  261. package/src/pivot-service.ts +87 -0
  262. package/src/publish-source.ts +103 -0
  263. package/src/runtime.ts +16 -4
  264. package/src/search-index.ts +560 -0
  265. package/src/search-service.ts +152 -0
  266. package/src/skill-definition.ts +53 -0
  267. package/src/skill-source.ts +29 -0
  268. package/src/skills.ts +1236 -0
  269. package/src/source-bundle.ts +26 -13
  270. package/src/space-path.ts +30 -0
  271. package/src/space.ts +230 -42
  272. package/src/state-storage-windows.ts +134 -0
  273. package/src/state-storage.ts +378 -0
  274. package/src/state.ts +875 -108
  275. package/src/swarm-envelope.ts +461 -0
  276. package/src/swarm-files.ts +126 -0
  277. package/src/swarm-meta.ts +98 -0
  278. package/src/swarm-observations.ts +393 -0
  279. package/src/swarm.ts +7392 -0
  280. package/src/template-definition.ts +36 -41
  281. package/src/template-paths.ts +43 -0
  282. package/src/template-presentation.ts +151 -0
  283. package/src/template-source.ts +19 -5
  284. package/src/templates.ts +77 -0
  285. package/src/unixfs-tree.ts +401 -0
package/src/state.ts CHANGED
@@ -1,21 +1,113 @@
1
- import { mkdirSync } from "node:fs";
2
1
  import { randomUUID } from "node:crypto";
3
- import { join } from "node:path";
2
+ import { resolve } from "node:path";
4
3
  import { DatabaseSync } from "node:sqlite";
5
4
  import { CID } from "multiformats/cid";
6
5
  import type { StoreConfiguration } from "@ipab/ipfs-store";
7
6
  import {
7
+ LOCAL_SWARM_ALIAS,
8
+ LOCAL_SWARM_URL,
9
+ isLocalSwarm,
10
+ isReservedLocalHost,
11
+ rejectLegacySwarmCid,
8
12
  validateUserConfig,
13
+ swarmUrl,
9
14
  type ConfigKey,
10
15
  type ConfigValue,
11
16
  } from "./config.js";
12
- import { HostError, object, syntax } from "./errors.js";
17
+ import { HostError, object, syntax } from "./host-error.js";
18
+ import { openStateStorage } from "./state-storage.js";
13
19
 
14
20
  export interface Association {
15
21
  schemaCid: string;
16
22
  appCid: string;
17
23
  argv: string[];
18
24
  }
25
+ export function createAssociation(
26
+ schemaCid: string,
27
+ appCid: string,
28
+ argv: string[],
29
+ ): Association {
30
+ if (!argv.length || !argv.includes("%"))
31
+ syntax('Argument template must contain a whole "%" argument.');
32
+ return {
33
+ schemaCid: exactCid(schemaCid, true),
34
+ appCid: exactCid(appCid),
35
+ argv: [...argv],
36
+ };
37
+ }
38
+ export interface RegisteredSwarm {
39
+ // Keep the storage column name, but values are configuration URLs; old CID rows are rejected.
40
+ cid: string;
41
+ alias: string | null;
42
+ local?: boolean;
43
+ }
44
+ export interface LocalSwarmRecord {
45
+ headCid: string;
46
+ valueCid: string;
47
+ createdAt: string;
48
+ updatedAt: string;
49
+ }
50
+ export interface SwarmProjection {
51
+ account: string;
52
+ swarm: string;
53
+ stateCid: string;
54
+ root: string;
55
+ valueCid: string;
56
+ verifiedAt: number;
57
+ headId: string;
58
+ epoch: number;
59
+ membership: string;
60
+ }
61
+ export type SearchEntryKind = "bundle" | "dir" | "file";
62
+ export type SearchFilterKind = "all" | SearchEntryKind;
63
+ export interface SearchIndexState {
64
+ headCid: string;
65
+ indexedAt: string;
66
+ }
67
+ export interface SearchIndexRow {
68
+ path: string;
69
+ cid: string;
70
+ kind: SearchEntryKind;
71
+ title: string | null;
72
+ description: string | null;
73
+ schemaCid: string | null;
74
+ }
75
+ export interface SearchIndexDelta {
76
+ headCid: string;
77
+ indexedAt: string;
78
+ fullReset: boolean;
79
+ deleteSubtrees: readonly string[];
80
+ deleteChildrenOnly: readonly string[];
81
+ upserts: readonly SearchIndexRow[];
82
+ }
83
+ export interface SearchIndexQuery {
84
+ q: string;
85
+ prefix?: string;
86
+ kind: SearchFilterKind;
87
+ schemaCid?: string;
88
+ limit: number;
89
+ offset: number;
90
+ }
91
+ export interface SearchIndexMatch {
92
+ path: string;
93
+ cid: string;
94
+ kind: SearchEntryKind;
95
+ bundle?: {
96
+ title: string;
97
+ description: string;
98
+ schemaCid: string;
99
+ };
100
+ }
101
+ export interface SearchIndexQueryResult {
102
+ headCid: string;
103
+ indexedAt: string;
104
+ total: number;
105
+ matches: SearchIndexMatch[];
106
+ }
107
+ const projectionVersion = 2;
108
+ export function swarmAlias(value: string): void {
109
+ pinName(value);
110
+ }
19
111
  export interface RunRecord {
20
112
  id: string;
21
113
  origin: "exec" | "open";
@@ -43,9 +135,9 @@ export interface Hold {
43
135
  recordId: string | null;
44
136
  }
45
137
  export type PinMetadata =
46
- | { kind: "bundle"; typeName: string; schemaCid: string }
47
- | { kind: "schema"; typeName: string; schemaCid: string }
48
- | { kind: "content"; typeName: null; schemaCid: null };
138
+ | { kind: "bundle"; title: string; schemaCid: string }
139
+ | { kind: "schema"; title: string; schemaCid: string }
140
+ | { kind: "content"; title: null; schemaCid: null };
49
141
  export interface NamedPin {
50
142
  name: string;
51
143
  cid: string;
@@ -54,15 +146,24 @@ export interface NamedPin {
54
146
  metadata: PinMetadata | null;
55
147
  builtin?: true;
56
148
  }
149
+ export interface ContentPin {
150
+ reference: string;
151
+ owner: string;
152
+ cid: string | null;
153
+ targetCid: string | null;
154
+ swarm: string | null;
155
+ name: string | null;
156
+ status: "pending" | "ready" | "deleting";
157
+ freshness: "current" | "stale" | "missing";
158
+ error: string | null;
159
+ }
57
160
  export function bundlePinMetadata(pin: NamedPin) {
58
161
  if (pin.status !== "ready" || !pin.metadata)
59
162
  throw new HostError(
60
- `Pin "${pin.name}" is ${pin.status}; retry pin add/delete before using it.`,
163
+ `Packaged reference "${pin.name}" is ${pin.status}; reinstall a verified CLI package before using it.`,
61
164
  );
62
165
  if (pin.metadata.kind !== "bundle")
63
- throw new HostError(
64
- `Pin "${pin.name}" is not a Bundle pin. Its retention is preserved; run ipab pin delete ${pin.name}, then wrap the content in a Bundle before adding a new pin.`,
65
- );
166
+ throw new HostError(`Packaged reference "${pin.name}" is not a Bundle.`);
66
167
  return pin.metadata;
67
168
  }
68
169
 
@@ -128,31 +229,133 @@ function persistedHold(value: string, owner: string): Hold {
128
229
  }
129
230
  }
130
231
 
232
+ // SQLite can report BUSY immediately when concurrent first opens both try to
233
+ // upgrade their read lock to switch journal mode, even with a busy timeout.
234
+ function enableWal(db: DatabaseSync): void {
235
+ const until = performance.now() + 5000;
236
+ for (;;) {
237
+ try {
238
+ db.exec("PRAGMA journal_mode=WAL");
239
+ if (db.prepare("PRAGMA journal_mode").get()?.journal_mode !== "wal")
240
+ throw new HostError(
241
+ "Cannot enable WAL for the private state database.",
242
+ );
243
+ return;
244
+ } catch (error) {
245
+ if (
246
+ (((error as { errcode?: number }).errcode ?? 0) & 0xff) !== 5 ||
247
+ performance.now() >= until
248
+ )
249
+ throw error;
250
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 20);
251
+ }
252
+ }
253
+ }
254
+
131
255
  export class State {
132
256
  readonly db: DatabaseSync;
133
257
  readonly identity: string;
258
+ readonly directory: string;
259
+ readonly legacyRegistrationCount: number;
260
+ readonly legacyPinCount: number;
134
261
  constructor(
135
- readonly directory: string,
262
+ directory: string,
136
263
  private readonly builtins: readonly NamedPin[] = [],
264
+ env: NodeJS.ProcessEnv = process.env,
137
265
  ) {
138
- mkdirSync(directory, { recursive: true });
139
- this.db = new DatabaseSync(join(directory, "state.sqlite"));
140
- this.db
141
- .exec(`PRAGMA busy_timeout=5000; PRAGMA journal_mode=WAL; PRAGMA synchronous=FULL;
266
+ this.directory = resolve(directory);
267
+ this.db = new DatabaseSync(openStateStorage(this.directory, env));
268
+ try {
269
+ enableWal(this.db);
270
+ this.db.exec(`PRAGMA busy_timeout=5000; PRAGMA synchronous=FULL;
142
271
  CREATE TABLE IF NOT EXISTS identity (id TEXT NOT NULL);
143
272
  CREATE TABLE IF NOT EXISTS config (key TEXT PRIMARY KEY, value TEXT NOT NULL);
144
273
  DROP TABLE IF EXISTS aliases;
145
- CREATE TABLE IF NOT EXISTS named_pins (name TEXT PRIMARY KEY, owner TEXT UNIQUE NOT NULL, value TEXT NOT NULL);
146
- CREATE TABLE IF NOT EXISTS registrations (schema_cid TEXT PRIMARY KEY, value TEXT NOT NULL);
274
+ CREATE TABLE IF NOT EXISTS content_pins (reference TEXT PRIMARY KEY, owner TEXT UNIQUE NOT NULL, value TEXT NOT NULL);
275
+ CREATE TABLE IF NOT EXISTS swarms (cid TEXT PRIMARY KEY, alias TEXT UNIQUE);
276
+ CREATE TABLE IF NOT EXISTS swarm_headers (account TEXT NOT NULL, swarm TEXT NOT NULL, value TEXT NOT NULL, PRIMARY KEY (account,swarm));
277
+ CREATE TABLE IF NOT EXISTS swarm_projection_checkpoints (account TEXT NOT NULL, swarm TEXT NOT NULL, version INTEGER NOT NULL, state_cid TEXT NOT NULL, binding TEXT NOT NULL, PRIMARY KEY (account,swarm));
278
+ CREATE TABLE IF NOT EXISTS swarm_projection_names (account TEXT NOT NULL, swarm TEXT NOT NULL, version INTEGER NOT NULL, name TEXT NOT NULL, normalized TEXT NOT NULL, target_cid TEXT NOT NULL, PRIMARY KEY (account,swarm,name));
279
+ CREATE TABLE IF NOT EXISTS swarm_projection_registrations (account TEXT NOT NULL, swarm TEXT NOT NULL, version INTEGER NOT NULL, schema_cid TEXT NOT NULL, app_cid TEXT NOT NULL, argv TEXT NOT NULL, PRIMARY KEY (account,swarm,schema_cid));
280
+ CREATE TABLE IF NOT EXISTS swarm_search_state (swarm TEXT PRIMARY KEY, head_cid TEXT NOT NULL, indexed_at TEXT NOT NULL);
281
+ CREATE TABLE IF NOT EXISTS swarm_search_entries (swarm TEXT NOT NULL, path TEXT NOT NULL, cid TEXT NOT NULL, kind TEXT NOT NULL, title TEXT, description TEXT, schema_cid TEXT, path_lower TEXT NOT NULL, title_lower TEXT, description_lower TEXT, PRIMARY KEY (swarm,path));
282
+ CREATE INDEX IF NOT EXISTS idx_swarm_search_entries_swarm_kind ON swarm_search_entries (swarm,kind);
283
+ CREATE INDEX IF NOT EXISTS idx_swarm_search_entries_swarm_schema ON swarm_search_entries (swarm,schema_cid);
147
284
  CREATE TABLE IF NOT EXISTS runs (id TEXT PRIMARY KEY, value TEXT NOT NULL);
148
- CREATE TABLE IF NOT EXISTS holds (owner TEXT PRIMARY KEY, value TEXT NOT NULL);`);
149
- this.transaction(() => {
150
- if (!this.db.prepare("SELECT id FROM identity").get())
151
- this.db.prepare("INSERT INTO identity VALUES (?)").run(randomUUID());
152
- });
153
- this.identity = String(
154
- this.db.prepare("SELECT id FROM identity").get()!.id,
155
- );
285
+ CREATE TABLE IF NOT EXISTS holds (owner TEXT PRIMARY KEY, value TEXT NOT NULL);
286
+ CREATE TABLE IF NOT EXISTS local_swarm (id INTEGER PRIMARY KEY CHECK (id = 1), head_cid TEXT NOT NULL, value_cid TEXT NOT NULL, created_at TEXT NOT NULL, updated_at TEXT NOT NULL);`);
287
+ this.transaction(() => {
288
+ if (
289
+ this.db
290
+ .prepare(
291
+ "SELECT 1 FROM sqlite_master WHERE type='table' AND name='named_pins'",
292
+ )
293
+ .get()
294
+ ) {
295
+ if (
296
+ this.db
297
+ .prepare(
298
+ "SELECT 1 FROM sqlite_master WHERE type='table' AND name='legacy_named_pins'",
299
+ )
300
+ .get()
301
+ )
302
+ throw new HostError(
303
+ "Both named_pins and legacy_named_pins exist; preserve both and resolve the archive conflict before retrying.",
304
+ );
305
+ this.db.exec("ALTER TABLE named_pins RENAME TO legacy_named_pins");
306
+ }
307
+ this.db.exec(
308
+ "CREATE TABLE IF NOT EXISTS legacy_named_pins (name TEXT PRIMARY KEY, owner TEXT UNIQUE NOT NULL, value TEXT NOT NULL)",
309
+ );
310
+ if (
311
+ this.db
312
+ .prepare(
313
+ "SELECT 1 FROM sqlite_master WHERE type='table' AND name='registrations'",
314
+ )
315
+ .get()
316
+ ) {
317
+ if (
318
+ this.db
319
+ .prepare(
320
+ "SELECT 1 FROM sqlite_master WHERE type='table' AND name='legacy_user_registrations'",
321
+ )
322
+ .get()
323
+ )
324
+ throw new HostError(
325
+ "Both registrations and legacy_user_registrations exist in the state database. Preserve both tables and resolve the archive conflict before retrying; no User registrations were uploaded or deleted.",
326
+ );
327
+ this.db.exec(
328
+ "ALTER TABLE registrations RENAME TO legacy_user_registrations",
329
+ );
330
+ }
331
+ if (!this.db.prepare("SELECT id FROM identity").get())
332
+ this.db.prepare("INSERT INTO identity VALUES (?)").run(randomUUID());
333
+ });
334
+ this.legacyPinCount = Number(
335
+ this.db
336
+ .prepare("SELECT COUNT(*) AS count FROM legacy_named_pins")
337
+ .get()!.count,
338
+ );
339
+ this.legacyRegistrationCount = this.db
340
+ .prepare(
341
+ "SELECT 1 FROM sqlite_master WHERE type='table' AND name='legacy_user_registrations'",
342
+ )
343
+ .get()
344
+ ? Number(
345
+ this.db
346
+ .prepare(
347
+ "SELECT COUNT(*) AS count FROM legacy_user_registrations",
348
+ )
349
+ .get()!.count,
350
+ )
351
+ : 0;
352
+ this.identity = String(
353
+ this.db.prepare("SELECT id FROM identity").get()!.id,
354
+ );
355
+ } catch (error) {
356
+ this.db.close();
357
+ throw error;
358
+ }
156
359
  }
157
360
  close(): void {
158
361
  this.db.close();
@@ -168,8 +371,16 @@ export class State {
168
371
  throw error;
169
372
  }
170
373
  }
171
- config(): Partial<Record<ConfigKey, ConfigValue>> {
172
- const entries = this.db.prepare("SELECT key,value FROM config").all();
374
+ config({ includeSecrets = true }: { includeSecrets?: boolean } = {}): Partial<
375
+ Record<ConfigKey, ConfigValue>
376
+ > {
377
+ const entries = this.db
378
+ .prepare(
379
+ includeSecrets
380
+ ? "SELECT key,value FROM config"
381
+ : "SELECT key,value FROM config WHERE key != 'pointers.apiKey'",
382
+ )
383
+ .all();
173
384
  if (entries.some((row) => row.key === "store.rpc"))
174
385
  throw new HostError(
175
386
  "store.rpc is no longer supported. Run ipab config reset store.rpc, then configure store.gateway with an HTTP gateway URL. Existing Kubo pins are not migrated or released.",
@@ -197,6 +408,566 @@ export class State {
197
408
  resetConfig(key: ConfigKey | "store.rpc"): void {
198
409
  this.db.prepare("DELETE FROM config WHERE key=?").run(key);
199
410
  }
411
+ localSwarmHead(): LocalSwarmRecord | undefined {
412
+ const row = this.db
413
+ .prepare(
414
+ "SELECT head_cid, value_cid, created_at, updated_at FROM local_swarm WHERE id = 1",
415
+ )
416
+ .get();
417
+ if (!row) return undefined;
418
+ if (
419
+ typeof row.head_cid !== "string" ||
420
+ typeof row.value_cid !== "string" ||
421
+ typeof row.created_at !== "string" ||
422
+ typeof row.updated_at !== "string"
423
+ )
424
+ throw new HostError("Invalid persisted local Swarm HEAD.");
425
+ return {
426
+ headCid: exactCid(row.head_cid),
427
+ valueCid: exactCid(row.value_cid),
428
+ createdAt: row.created_at,
429
+ updatedAt: row.updated_at,
430
+ };
431
+ }
432
+ initLocalSwarmHead(record: LocalSwarmRecord): {
433
+ record: LocalSwarmRecord;
434
+ inserted: boolean;
435
+ } {
436
+ const headCid = exactCid(record.headCid);
437
+ const valCid = exactCid(record.valueCid);
438
+ return this.transaction(() => {
439
+ const result = this.db
440
+ .prepare(
441
+ "INSERT OR IGNORE INTO local_swarm (id, head_cid, value_cid, created_at, updated_at) VALUES (1, ?, ?, ?, ?)",
442
+ )
443
+ .run(headCid, valCid, record.createdAt, record.updatedAt);
444
+ if (result.changes > 0) {
445
+ return {
446
+ record: {
447
+ headCid,
448
+ valueCid: valCid,
449
+ createdAt: record.createdAt,
450
+ updatedAt: record.updatedAt,
451
+ },
452
+ inserted: true,
453
+ };
454
+ }
455
+ return {
456
+ record: this.localSwarmHead()!,
457
+ inserted: false,
458
+ };
459
+ });
460
+ }
461
+ compareAndSwapLocalSwarmHead(
462
+ expectedValueCid: string,
463
+ next: { headCid: string; valueCid: string; updatedAt: string },
464
+ ): boolean {
465
+ const headCid = exactCid(next.headCid);
466
+ const valCid = exactCid(next.valueCid);
467
+ const expected = exactCid(expectedValueCid);
468
+ return this.transaction(() => {
469
+ const result = this.db
470
+ .prepare(
471
+ "UPDATE local_swarm SET head_cid = ?, value_cid = ?, updated_at = ? WHERE id = 1 AND value_cid = ?",
472
+ )
473
+ .run(headCid, valCid, next.updatedAt, expected);
474
+ return result.changes > 0;
475
+ });
476
+ }
477
+ private rejectReservedRemoteAlias(alias: string): void {
478
+ if (alias === LOCAL_SWARM_ALIAS)
479
+ throw new HostError(
480
+ `Swarm alias "${LOCAL_SWARM_ALIAS}" is reserved for the built-in local Swarm.`,
481
+ );
482
+ }
483
+ private rejectReservedRemoteUrl(url: string): void {
484
+ if (isLocalSwarm(url) || isReservedLocalHost(url))
485
+ throw new HostError(
486
+ `Swarm URL "${url}" uses the reserved .invalid domain and cannot be registered as a remote Swarm.`,
487
+ );
488
+ }
489
+ swarms(): RegisteredSwarm[] {
490
+ return this.db
491
+ .prepare("SELECT cid,alias FROM swarms ORDER BY cid")
492
+ .all()
493
+ .map((row) => {
494
+ if (
495
+ typeof row.cid !== "string" ||
496
+ (row.alias !== null && typeof row.alias !== "string")
497
+ )
498
+ throw new HostError("Invalid persisted swarm registration.");
499
+ const cid = swarmUrl(row.cid);
500
+ if (isLocalSwarm(cid) || isReservedLocalHost(cid))
501
+ throw new HostError("Invalid persisted swarm registration.");
502
+ if (row.alias !== null) {
503
+ swarmAlias(row.alias);
504
+ if (row.alias === LOCAL_SWARM_ALIAS)
505
+ throw new HostError("Invalid persisted swarm registration.");
506
+ }
507
+ return { cid, alias: row.alias };
508
+ });
509
+ }
510
+ allSwarms(): RegisteredSwarm[] {
511
+ return [
512
+ { cid: LOCAL_SWARM_URL, alias: LOCAL_SWARM_ALIAS, local: true },
513
+ ...this.swarms(),
514
+ ];
515
+ }
516
+ resolveSwarm(reference: string): string {
517
+ if (reference === LOCAL_SWARM_ALIAS || reference === LOCAL_SWARM_URL)
518
+ return LOCAL_SWARM_URL;
519
+ if (/^https?:/.test(reference)) return swarmUrl(reference);
520
+ const entry = this.swarms().find((entry) => entry.alias === reference);
521
+ if (entry) return entry.cid;
522
+ rejectLegacySwarmCid(reference);
523
+ throw new HostError(
524
+ `Unknown swarm alias "${reference}". Run ipab swarm list.`,
525
+ );
526
+ }
527
+ registeredSwarm(reference: string): RegisteredSwarm {
528
+ const cid = this.resolveSwarm(reference);
529
+ if (isLocalSwarm(cid))
530
+ return { cid: LOCAL_SWARM_URL, alias: LOCAL_SWARM_ALIAS, local: true };
531
+ const entry = this.swarms().find((entry) => entry.cid === cid);
532
+ if (!entry)
533
+ throw new HostError(
534
+ `Swarm "${reference}" is not registered. Run ipab swarm set ALIAS ${cid}.`,
535
+ );
536
+ return entry;
537
+ }
538
+ checkSwarmAlias(alias: string, cid?: string): void {
539
+ swarmAlias(alias);
540
+ this.rejectReservedRemoteAlias(alias);
541
+ const existing = this.swarms().find((entry) => entry.alias === alias);
542
+ if (existing && existing.cid !== cid)
543
+ throw new HostError(
544
+ `Swarm alias "${alias}" is already assigned to "${existing.cid}". Choose a different alias, or explicitly retarget it with ipab swarm set ${alias} CONFIG_URL.`,
545
+ );
546
+ }
547
+ registerSwarm(cid: string, alias?: string): RegisteredSwarm {
548
+ cid = swarmUrl(cid);
549
+ this.rejectReservedRemoteUrl(cid);
550
+ return this.transaction(() => {
551
+ if (alias !== undefined) this.checkSwarmAlias(alias, cid);
552
+ return this.saveSwarmRegistration(cid, alias);
553
+ });
554
+ }
555
+ setSwarm(
556
+ alias: string,
557
+ url: string,
558
+ expectedTarget: string | null,
559
+ ): RegisteredSwarm {
560
+ swarmAlias(alias);
561
+ this.rejectReservedRemoteAlias(alias);
562
+ url = swarmUrl(url);
563
+ this.rejectReservedRemoteUrl(url);
564
+ return this.transaction(() => {
565
+ const current = this.swarms().find((entry) => entry.alias === alias);
566
+ if ((current?.cid ?? null) !== expectedTarget)
567
+ throw new HostError(
568
+ `Swarm alias "${alias}" changed while setting it. Run ipab swarm list and retry.`,
569
+ );
570
+ if (current && current.cid !== url)
571
+ this.db
572
+ .prepare("UPDATE swarms SET alias=NULL WHERE cid=?")
573
+ .run(current.cid);
574
+ return this.saveSwarmRegistration(url, alias);
575
+ });
576
+ }
577
+ private saveSwarmRegistration(cid: string, alias?: string): RegisteredSwarm {
578
+ const previous = this.swarms().find((entry) => entry.cid === cid);
579
+ const entry = { cid, alias: alias ?? previous?.alias ?? null };
580
+ this.db
581
+ .prepare("INSERT OR REPLACE INTO swarms VALUES (?,?)")
582
+ .run(cid, entry.alias);
583
+ if (this.config({ includeSecrets: false })["swarm.default"] == null)
584
+ this.setConfig("swarm.default", cid);
585
+ return entry;
586
+ }
587
+ useSwarm(reference: string): string {
588
+ return this.transaction(() => {
589
+ const entry = this.registeredSwarm(reference);
590
+ this.setConfig("swarm.default", entry.cid);
591
+ return entry.cid;
592
+ });
593
+ }
594
+ removeSwarm(reference: string): string {
595
+ return this.transaction(() => {
596
+ const cid = this.resolveSwarm(reference);
597
+ if (isLocalSwarm(cid))
598
+ throw new HostError(
599
+ `Cannot remove the built-in "${LOCAL_SWARM_ALIAS}" Swarm.`,
600
+ );
601
+ const entry = this.registeredSwarm(reference);
602
+ this.db.prepare("DELETE FROM swarms WHERE cid=?").run(entry.cid);
603
+ this.deleteSwarmCache(entry.cid);
604
+ if (this.config({ includeSecrets: false })["swarm.default"] === entry.cid)
605
+ this.resetConfig("swarm.default");
606
+ return entry.cid;
607
+ });
608
+ }
609
+ swarmHeader(account: string, swarm: string): unknown {
610
+ const row = this.db
611
+ .prepare("SELECT value FROM swarm_headers WHERE account=? AND swarm=?")
612
+ .get(account, swarm);
613
+ if (!row) return undefined;
614
+ try {
615
+ return JSON.parse(String(row.value)) as unknown;
616
+ } catch {
617
+ throw new HostError("Malformed persisted swarm header cache.");
618
+ }
619
+ }
620
+ saveSwarmHeader(account: string, swarm: string, value: unknown): void {
621
+ this.db
622
+ .prepare("INSERT OR REPLACE INTO swarm_headers VALUES (?,?,?)")
623
+ .run(account, swarm, JSON.stringify(value));
624
+ }
625
+ invalidateSwarmHeader(swarm: string): void {
626
+ this.transaction(() => {
627
+ this.deleteSwarmCache(swarm);
628
+ });
629
+ }
630
+ private deleteSwarmCache(swarm: string): void {
631
+ this.db.prepare("DELETE FROM swarm_headers WHERE swarm=?").run(swarm);
632
+ for (const table of [
633
+ "swarm_projection_checkpoints",
634
+ "swarm_projection_names",
635
+ "swarm_projection_registrations",
636
+ ])
637
+ this.db.prepare(`DELETE FROM ${table} WHERE swarm=?`).run(swarm);
638
+ }
639
+ private checkProjectionHeader(binding: SwarmProjection): void {
640
+ const cached = this.swarmHeader(binding.account, binding.swarm) as
641
+ | {
642
+ head: { root: string; cid: string };
643
+ stateCid?: string;
644
+ verifiedAt: number;
645
+ headId: string;
646
+ epoch?: number;
647
+ }
648
+ | undefined;
649
+ if (
650
+ !cached ||
651
+ cached.head.root !== binding.root ||
652
+ cached.head.cid !== binding.valueCid ||
653
+ cached.verifiedAt !== binding.verifiedAt ||
654
+ cached.headId !== binding.headId ||
655
+ (cached.epoch !== undefined && cached.epoch !== binding.epoch) ||
656
+ (cached.stateCid !== undefined && cached.stateCid !== binding.stateCid)
657
+ )
658
+ throw new HostError("Swarm header changed; retry the verified read.");
659
+ }
660
+ projectSwarm(
661
+ binding: SwarmProjection,
662
+ names: Readonly<Record<string, CID>>,
663
+ registrations: () => readonly Association[],
664
+ ): void {
665
+ this.transaction(() => {
666
+ this.checkProjectionHeader(binding);
667
+ const cached = this.swarmHeader(binding.account, binding.swarm) as Record<
668
+ string,
669
+ unknown
670
+ >;
671
+ if (cached.stateCid === undefined)
672
+ this.saveSwarmHeader(binding.account, binding.swarm, {
673
+ ...cached,
674
+ stateCid: binding.stateCid,
675
+ });
676
+ const old = this.db
677
+ .prepare(
678
+ "SELECT version,state_cid,binding FROM swarm_projection_checkpoints WHERE account=? AND swarm=?",
679
+ )
680
+ .get(binding.account, binding.swarm);
681
+ const encoded = JSON.stringify(binding);
682
+ if (old?.version === projectionVersion && old.binding === encoded) return;
683
+ // A new Publication may reference the same State: only provenance changes.
684
+ if (
685
+ old?.version !== projectionVersion ||
686
+ old.state_cid !== binding.stateCid
687
+ ) {
688
+ for (const table of [
689
+ "swarm_projection_names",
690
+ "swarm_projection_registrations",
691
+ ])
692
+ this.db
693
+ .prepare(`DELETE FROM ${table} WHERE account=? AND swarm=?`)
694
+ .run(binding.account, binding.swarm);
695
+ const insertName = this.db.prepare(
696
+ "INSERT INTO swarm_projection_names VALUES (?,?,?,?,?,?)",
697
+ );
698
+ for (const [name, target] of Object.entries(names))
699
+ insertName.run(
700
+ binding.account,
701
+ binding.swarm,
702
+ projectionVersion,
703
+ name,
704
+ name.toLowerCase(),
705
+ target.toString(),
706
+ );
707
+ const insertRegistration = this.db.prepare(
708
+ "INSERT INTO swarm_projection_registrations VALUES (?,?,?,?,?,?)",
709
+ );
710
+ for (const item of registrations())
711
+ insertRegistration.run(
712
+ binding.account,
713
+ binding.swarm,
714
+ projectionVersion,
715
+ item.schemaCid,
716
+ item.appCid,
717
+ JSON.stringify(item.argv),
718
+ );
719
+ }
720
+ this.db
721
+ .prepare(
722
+ "INSERT OR REPLACE INTO swarm_projection_checkpoints VALUES (?,?,?,?,?)",
723
+ )
724
+ .run(
725
+ binding.account,
726
+ binding.swarm,
727
+ projectionVersion,
728
+ binding.stateCid,
729
+ encoded,
730
+ );
731
+ });
732
+ }
733
+ private checkProjection(binding: SwarmProjection): void {
734
+ this.checkProjectionHeader(binding);
735
+ if (
736
+ !this.db
737
+ .prepare(
738
+ "SELECT 1 FROM swarm_projection_checkpoints WHERE account=? AND swarm=? AND version=? AND binding=?",
739
+ )
740
+ .get(
741
+ binding.account,
742
+ binding.swarm,
743
+ projectionVersion,
744
+ JSON.stringify(binding),
745
+ )
746
+ )
747
+ throw new HostError("Swarm projection changed; retry the verified read.");
748
+ }
749
+ searchSwarmNames(
750
+ binding: SwarmProjection,
751
+ query: string,
752
+ ): { name: string; targetCid: string }[] {
753
+ return this.transaction(() => {
754
+ this.checkProjection(binding);
755
+ return this.db
756
+ .prepare(
757
+ "SELECT name,target_cid FROM swarm_projection_names WHERE account=? AND swarm=? AND version=? AND instr(normalized,?)>0",
758
+ )
759
+ .all(
760
+ binding.account,
761
+ binding.swarm,
762
+ projectionVersion,
763
+ query.toLowerCase(),
764
+ )
765
+ .map((row) => ({
766
+ name: String(row.name),
767
+ targetCid: String(row.target_cid),
768
+ }))
769
+ .sort((left, right) =>
770
+ left.name < right.name ? -1 : left.name > right.name ? 1 : 0,
771
+ );
772
+ });
773
+ }
774
+ searchIndexState(swarm: string): SearchIndexState | null {
775
+ const row = this.db
776
+ .prepare(
777
+ "SELECT head_cid, indexed_at FROM swarm_search_state WHERE swarm = ?",
778
+ )
779
+ .get(swarm);
780
+ if (!row) return null;
781
+ return {
782
+ headCid: String(row.head_cid),
783
+ indexedAt: String(row.indexed_at),
784
+ };
785
+ }
786
+ applySearchIndexDelta(swarm: string, delta: SearchIndexDelta): void {
787
+ this.transaction(() => {
788
+ if (delta.fullReset) {
789
+ this.db
790
+ .prepare("DELETE FROM swarm_search_entries WHERE swarm = ?")
791
+ .run(swarm);
792
+ } else {
793
+ const deleteSubtree = this.db.prepare(
794
+ "DELETE FROM swarm_search_entries WHERE swarm = ? AND (path = ? OR (path >= ? AND path < ?))",
795
+ );
796
+ for (const prefix of delta.deleteSubtrees) {
797
+ deleteSubtree.run(swarm, prefix, `${prefix}/`, `${prefix}0`);
798
+ }
799
+ const deleteChildren = this.db.prepare(
800
+ "DELETE FROM swarm_search_entries WHERE swarm = ? AND path >= ? AND path < ?",
801
+ );
802
+ for (const prefix of delta.deleteChildrenOnly) {
803
+ deleteChildren.run(swarm, `${prefix}/`, `${prefix}0`);
804
+ }
805
+ }
806
+ const upsert = this.db.prepare(
807
+ "INSERT OR REPLACE INTO swarm_search_entries (swarm, path, cid, kind, title, description, schema_cid, path_lower, title_lower, description_lower) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
808
+ );
809
+ for (const entry of delta.upserts) {
810
+ upsert.run(
811
+ swarm,
812
+ entry.path,
813
+ entry.cid,
814
+ entry.kind,
815
+ entry.title,
816
+ entry.description,
817
+ entry.schemaCid,
818
+ entry.path.toLowerCase(),
819
+ entry.title !== null ? entry.title.toLowerCase() : null,
820
+ entry.description !== null ? entry.description.toLowerCase() : null,
821
+ );
822
+ }
823
+ this.db
824
+ .prepare(
825
+ "INSERT OR REPLACE INTO swarm_search_state (swarm, head_cid, indexed_at) VALUES (?, ?, ?)",
826
+ )
827
+ .run(swarm, delta.headCid, delta.indexedAt);
828
+ });
829
+ }
830
+ querySearchIndex(
831
+ swarm: string,
832
+ params: SearchIndexQuery,
833
+ ): SearchIndexQueryResult | null {
834
+ this.db.exec("BEGIN");
835
+ try {
836
+ const stateRow = this.db
837
+ .prepare(
838
+ "SELECT head_cid, indexed_at FROM swarm_search_state WHERE swarm = ?",
839
+ )
840
+ .get(swarm);
841
+ if (!stateRow) {
842
+ this.db.exec("COMMIT");
843
+ return null;
844
+ }
845
+ const needle = params.q.toLowerCase();
846
+ const conditions: string[] = [
847
+ "swarm = ?",
848
+ "(instr(path_lower, ?) > 0 OR (title_lower IS NOT NULL AND instr(title_lower, ?) > 0) OR (description_lower IS NOT NULL AND instr(description_lower, ?) > 0))",
849
+ ];
850
+ const whereValues: (string | number)[] = [swarm, needle, needle, needle];
851
+ if (params.prefix !== undefined) {
852
+ conditions.push("(path = ? OR (path >= ? AND path < ?))");
853
+ whereValues.push(
854
+ params.prefix,
855
+ `${params.prefix}/`,
856
+ `${params.prefix}0`,
857
+ );
858
+ }
859
+ if (params.kind !== "all") {
860
+ conditions.push("kind = ?");
861
+ whereValues.push(params.kind);
862
+ }
863
+ if (params.schemaCid !== undefined) {
864
+ conditions.push("schema_cid = ?");
865
+ whereValues.push(params.schemaCid);
866
+ }
867
+ const whereSql = conditions.join(" AND ");
868
+ const countRow = this.db
869
+ .prepare(
870
+ `SELECT COUNT(*) AS total FROM swarm_search_entries WHERE ${whereSql}`,
871
+ )
872
+ .get(...whereValues);
873
+ const total = Number(countRow?.total ?? 0);
874
+ const needleLen = needle.length;
875
+ const rows = this.db
876
+ .prepare(
877
+ `SELECT path, cid, kind, title, description, schema_cid
878
+ FROM swarm_search_entries
879
+ WHERE ${whereSql}
880
+ ORDER BY
881
+ CASE
882
+ WHEN path_lower = ? THEN 0
883
+ WHEN substr(path_lower, 1, ?) = ? THEN 1
884
+ WHEN title_lower IS NOT NULL AND title_lower = ? THEN 2
885
+ WHEN title_lower IS NOT NULL AND substr(title_lower, 1, ?) = ? THEN 3
886
+ WHEN instr(path_lower, ?) > 0 THEN 4
887
+ WHEN title_lower IS NOT NULL AND instr(title_lower, ?) > 0 THEN 5
888
+ ELSE 6
889
+ END ASC,
890
+ path ASC
891
+ LIMIT ? OFFSET ?`,
892
+ )
893
+ .all(
894
+ ...whereValues,
895
+ needle,
896
+ needleLen,
897
+ needle,
898
+ needle,
899
+ needleLen,
900
+ needle,
901
+ needle,
902
+ needle,
903
+ params.limit,
904
+ params.offset,
905
+ );
906
+ this.db.exec("COMMIT");
907
+ const matches: SearchIndexMatch[] = rows.map((row) => {
908
+ const kind = String(row.kind) as SearchEntryKind;
909
+ const match: SearchIndexMatch = {
910
+ path: String(row.path),
911
+ cid: String(row.cid),
912
+ kind,
913
+ };
914
+ if (
915
+ kind === "bundle" &&
916
+ typeof row.title === "string" &&
917
+ typeof row.description === "string" &&
918
+ typeof row.schema_cid === "string"
919
+ ) {
920
+ match.bundle = {
921
+ title: row.title,
922
+ description: row.description,
923
+ schemaCid: row.schema_cid,
924
+ };
925
+ }
926
+ return match;
927
+ });
928
+ return {
929
+ headCid: String(stateRow.head_cid),
930
+ indexedAt: String(stateRow.indexed_at),
931
+ total,
932
+ matches,
933
+ };
934
+ } catch (error) {
935
+ this.db.exec("ROLLBACK");
936
+ throw error;
937
+ }
938
+ }
939
+ projectedSwarmRegistrations(
940
+ binding: SwarmProjection,
941
+ schemaCid?: string,
942
+ ): Association[] {
943
+ return this.transaction(() => {
944
+ this.checkProjection(binding);
945
+ const rows =
946
+ schemaCid === undefined
947
+ ? this.db
948
+ .prepare(
949
+ "SELECT schema_cid,app_cid,argv FROM swarm_projection_registrations WHERE account=? AND swarm=? AND version=?",
950
+ )
951
+ .all(binding.account, binding.swarm, projectionVersion)
952
+ : this.db
953
+ .prepare(
954
+ "SELECT schema_cid,app_cid,argv FROM swarm_projection_registrations WHERE account=? AND swarm=? AND version=? AND schema_cid=?",
955
+ )
956
+ .all(
957
+ binding.account,
958
+ binding.swarm,
959
+ projectionVersion,
960
+ schemaCid,
961
+ );
962
+ return rows
963
+ .map((row) => ({
964
+ schemaCid: String(row.schema_cid),
965
+ appCid: String(row.app_cid),
966
+ argv: JSON.parse(String(row.argv)) as string[],
967
+ }))
968
+ .sort((left, right) => left.schemaCid.localeCompare(right.schemaCid));
969
+ });
970
+ }
200
971
  resolve(value: string, schema = false): string {
201
972
  try {
202
973
  return exactCid(value, schema);
@@ -204,43 +975,26 @@ export class State {
204
975
  try {
205
976
  CID.parse(value);
206
977
  } catch {
207
- const pin = this.pin(value);
978
+ const pin = value.startsWith("builtin:") ? this.pin(value) : undefined;
208
979
  if (pin) {
209
980
  const metadata = bundlePinMetadata(pin);
210
981
  if (schema) return metadata.schemaCid;
211
982
  return exactCid(pin.cid, schema);
212
983
  }
213
984
  throw new HostError(
214
- `Unknown CID or pin "${value}". Run ipab pin list.`,
985
+ `Unknown CID or packaged builtin reference "${value}". Local content aliases are unsupported; use an exact CID or a Swarm IPAB URI.`,
215
986
  );
216
987
  }
217
988
  throw error;
218
989
  }
219
990
  }
220
- resolvePin(name: string): string | undefined {
221
- const pin = this.pin(name);
222
- if (!pin) return undefined;
223
- bundlePinMetadata(pin);
224
- return exactCid(pin.cid);
225
- }
226
991
  pins(): NamedPin[] {
227
- const user = this.db
228
- .prepare("SELECT name,owner,value FROM named_pins ORDER BY name")
229
- .all()
230
- .map((row) =>
231
- this.readPin(String(row.name), String(row.owner), String(row.value)),
232
- );
233
- return [...user, ...this.builtins];
992
+ return [...this.builtins];
234
993
  }
235
994
  pin(name: string): NamedPin | undefined {
236
995
  const builtin = this.builtins.find((pin) => pin.name === name);
237
996
  if (builtin) return builtin;
238
- const row = this.db
239
- .prepare("SELECT owner,value FROM named_pins WHERE name=?")
240
- .get(name);
241
- return row
242
- ? this.readPin(name, String(row.owner), String(row.value))
243
- : undefined;
997
+ return undefined;
244
998
  }
245
999
  private readPin(name: string, owner: string, value: string): NamedPin {
246
1000
  const data = object(JSON.parse(value) as unknown, "named pin");
@@ -258,20 +1012,20 @@ export class State {
258
1012
  if (data.metadata !== null) {
259
1013
  const value = object(data.metadata, "pin type metadata");
260
1014
  if (value.kind === "content") {
261
- if (value.typeName !== null || value.schemaCid !== null)
1015
+ if (value.title !== null || value.schemaCid !== null)
262
1016
  throw new HostError("Invalid persisted pin type metadata.");
263
- metadata = { kind: "content", typeName: null, schemaCid: null };
1017
+ metadata = { kind: "content", title: null, schemaCid: null };
264
1018
  } else {
265
1019
  if (
266
1020
  (value.kind !== "bundle" && value.kind !== "schema") ||
267
- typeof value.typeName !== "string" ||
268
- !value.typeName.trim() ||
1021
+ typeof value.title !== "string" ||
1022
+ !value.title.trim() ||
269
1023
  typeof value.schemaCid !== "string"
270
1024
  )
271
1025
  throw new HostError("Invalid persisted pin type metadata.");
272
1026
  metadata = {
273
1027
  kind: value.kind,
274
- typeName: value.typeName,
1028
+ title: value.title,
275
1029
  schemaCid: exactCid(value.schemaCid, true),
276
1030
  };
277
1031
  }
@@ -285,73 +1039,86 @@ export class State {
285
1039
  metadata,
286
1040
  };
287
1041
  }
288
- savePin(pin: NamedPin): void {
289
- pinName(pin.name);
1042
+ archivedPins(): NamedPin[] {
1043
+ return this.db
1044
+ .prepare("SELECT name,owner,value FROM legacy_named_pins ORDER BY name")
1045
+ .all()
1046
+ .map((row) =>
1047
+ this.readPin(String(row.name), String(row.owner), String(row.value)),
1048
+ );
1049
+ }
1050
+ contentPins(): ContentPin[] {
1051
+ return this.db
1052
+ .prepare(
1053
+ "SELECT reference,owner,value FROM content_pins ORDER BY reference",
1054
+ )
1055
+ .all()
1056
+ .map((row) => {
1057
+ const pin = JSON.parse(String(row.value)) as ContentPin;
1058
+ if (
1059
+ pin.reference !== row.reference ||
1060
+ pin.owner !== row.owner ||
1061
+ !["pending", "ready", "deleting"].includes(pin.status) ||
1062
+ !["current", "stale", "missing"].includes(pin.freshness) ||
1063
+ (pin.error !== null && typeof pin.error !== "string") ||
1064
+ (pin.cid !== null && typeof pin.cid !== "string") ||
1065
+ (pin.targetCid !== null && typeof pin.targetCid !== "string") ||
1066
+ (pin.swarm !== null && typeof pin.swarm !== "string") ||
1067
+ (pin.name !== null && typeof pin.name !== "string")
1068
+ )
1069
+ throw new HostError(
1070
+ "Invalid persisted content pin; recovery is blocked.",
1071
+ );
1072
+ if (pin.cid) exactCid(pin.cid);
1073
+ if (pin.targetCid) exactCid(pin.targetCid);
1074
+ if (pin.swarm) swarmUrl(pin.swarm);
1075
+ if (
1076
+ (pin.swarm === null) !== (pin.name === null) ||
1077
+ (pin.swarm === null &&
1078
+ (exactCid(pin.reference) !== pin.reference ||
1079
+ (pin.cid !== null && pin.cid !== pin.reference))) ||
1080
+ (pin.swarm !== null &&
1081
+ (!pin.reference.startsWith("ipab://") ||
1082
+ (pin.name === "" &&
1083
+ !/^ipab:\/\/[^/]+\/$/u.test(pin.reference)))) ||
1084
+ (pin.status === "ready" && (!pin.cid || !pin.targetCid))
1085
+ )
1086
+ throw new HostError(
1087
+ "Invalid persisted pin reference/version binding; recovery is blocked.",
1088
+ );
1089
+ return pin;
1090
+ });
1091
+ }
1092
+ contentPin(reference: string): ContentPin | undefined {
1093
+ return this.contentPins().find((pin) => pin.reference === reference);
1094
+ }
1095
+ saveContentPin(pin: ContentPin): void {
290
1096
  if (
291
1097
  !this.db
292
1098
  .prepare(
293
- "INSERT INTO named_pins VALUES (?,?,?) ON CONFLICT(name) DO UPDATE SET value=excluded.value WHERE owner=excluded.owner",
1099
+ "INSERT INTO content_pins VALUES (?,?,?) ON CONFLICT(reference) DO UPDATE SET value=excluded.value WHERE owner=excluded.owner",
294
1100
  )
295
- .run(pin.name, pin.owner, JSON.stringify(pin)).changes
1101
+ .run(pin.reference, pin.owner, JSON.stringify(pin)).changes
296
1102
  )
297
- throw new HostError(`Pin name "${pin.name}" is occupied.`);
1103
+ throw new HostError("Content pin reference is occupied.");
1104
+ }
1105
+ deleteContentPin(reference: string): void {
1106
+ this.db
1107
+ .prepare("DELETE FROM content_pins WHERE reference=?")
1108
+ .run(reference);
298
1109
  }
299
1110
  isPinOwner(owner: string): boolean {
300
1111
  return Boolean(
301
- this.db.prepare("SELECT 1 FROM named_pins WHERE owner=?").get(owner),
1112
+ this.db
1113
+ .prepare(
1114
+ "SELECT 1 FROM content_pins WHERE owner=? UNION ALL SELECT 1 FROM legacy_named_pins WHERE owner=?",
1115
+ )
1116
+ .get(owner, owner),
302
1117
  );
303
1118
  }
304
1119
  deletePin(name: string): void {
305
1120
  pinName(name);
306
- this.db.prepare("DELETE FROM named_pins WHERE name=?").run(name);
307
- }
308
- registrations(): Association[] {
309
- return this.db
310
- .prepare("SELECT value FROM registrations ORDER BY schema_cid")
311
- .all()
312
- .map((row) => JSON.parse(String(row.value)) as Association);
313
- }
314
- association(schemaCid: string): Association | undefined {
315
- const row = this.db
316
- .prepare("SELECT value FROM registrations WHERE schema_cid=?")
317
- .get(schemaCid);
318
- return row ? (JSON.parse(String(row.value)) as Association) : undefined;
319
- }
320
- setAssociation(
321
- schema: string,
322
- app: string,
323
- argv: string[],
324
- replace: boolean,
325
- ): Association {
326
- const value: Association = {
327
- schemaCid: this.resolve(schema, true),
328
- appCid: this.resolve(app),
329
- argv,
330
- };
331
- if (!argv.length || !argv.includes("%"))
332
- syntax('Argument template must contain a whole "%" argument.');
333
- this.transaction(() => {
334
- const old = this.association(value.schemaCid);
335
- if (old && JSON.stringify(old) !== JSON.stringify(value) && !replace)
336
- throw new HostError(
337
- "Schema has another association; use --replace before --.",
338
- );
339
- this.db
340
- .prepare("INSERT OR REPLACE INTO registrations VALUES (?,?)")
341
- .run(value.schemaCid, JSON.stringify(value));
342
- });
343
- return value;
344
- }
345
- removeAssociation(schema: string): string {
346
- const cid = this.resolve(schema, true);
347
- if (
348
- !this.db.prepare("DELETE FROM registrations WHERE schema_cid=?").run(cid)
349
- .changes
350
- )
351
- throw new HostError(
352
- "No association exists for this Schema. Run ipab register list.",
353
- );
354
- return cid;
1121
+ this.db.prepare("DELETE FROM legacy_named_pins WHERE name=?").run(name);
355
1122
  }
356
1123
  runs(): RunRecord[] {
357
1124
  return this.db