@ipab/cli 0.1.0-rc.10 → 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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ipab/cli",
3
- "version": "0.1.0-rc.10",
3
+ "version": "0.1.0-rc.11",
4
4
  "private": false,
5
5
  "description": "Node subprocess IPAB host.",
6
6
  "type": "module",
@@ -42,7 +42,7 @@
42
42
  "dependencies": {
43
43
  "@ipld/dag-cbor": "10.0.2",
44
44
  "liquidjs": "10.30.1",
45
- "@ipab/web-app": "0.1.0-rc.5",
45
+ "@ipab/web-app": "0.1.0-rc.6",
46
46
  "esbuild": "0.28.2",
47
47
  "@ipab/bundle-builder": "0.1.0-rc.9",
48
48
  "@ipld/car": "5.4.6",
package/src/authoring.ts CHANGED
@@ -46,7 +46,8 @@ import {
46
46
  import type { EncodedBundleCar } from "@ipab/bundle-builder";
47
47
  import { filesystemTree } from "@ipab/bundle-builder/node";
48
48
  import type { IpfsStore } from "@ipab/ipfs-store";
49
- import { HostError } from "./errors.js";
49
+ import { HostError, message } from "./errors.js";
50
+ import type { Ownership } from "./history.js";
50
51
  import { builtinAppSchema, schemaAlias } from "./app-definition.js";
51
52
  import {
52
53
  builtinTemplateSchema,
@@ -249,6 +250,62 @@ function cidInput(source: string): CID | undefined {
249
250
  return undefined;
250
251
  }
251
252
  }
253
+ export async function localBundleDirectory(
254
+ source: string,
255
+ ): Promise<string | undefined> {
256
+ if (
257
+ source.startsWith("ipab:") ||
258
+ source.startsWith("builtin:") ||
259
+ cidInput(source)
260
+ )
261
+ return undefined;
262
+ const path = resolve(source);
263
+ const stat = await existing(path);
264
+ if (!stat)
265
+ throw new HostError(
266
+ `Local open input does not exist: ${path}. Pass a Content Bundle directory containing .bundle.yaml, a Bundle CID or an IPAB URI.`,
267
+ );
268
+ if (!stat.isDirectory() || stat.isSymbolicLink())
269
+ throw new HostError(
270
+ `Local open input must be a regular Content Bundle directory, not a file or symbolic link: ${path}.`,
271
+ );
272
+ return path;
273
+ }
274
+ export async function snapshotBundle(
275
+ source: string,
276
+ owner: Ownership,
277
+ session: string,
278
+ options: AuthoringOptions = {},
279
+ ): Promise<string> {
280
+ try {
281
+ const encoded = await encodeBundleCar(
282
+ await selectedTree(source, undefined, undefined, options),
283
+ options,
284
+ );
285
+ try {
286
+ const iterator = await CarBlockIterator.fromIterable(
287
+ streamChunks(encoded.stream, options),
288
+ );
289
+ for await (const block of iterator)
290
+ await owner.store.stageBlock(session, block.cid, block.bytes, options);
291
+ await owner.store.finishImport(
292
+ session,
293
+ encoded.cid,
294
+ owner.owner,
295
+ options,
296
+ );
297
+ const cid = encoded.cid.toString();
298
+ await owner.retain([cid], options.signal);
299
+ return cid;
300
+ } finally {
301
+ await encoded.close();
302
+ }
303
+ } catch (cause) {
304
+ throw new HostError(
305
+ `Cannot open local Bundle directory ${source}: ${message(cause)} Ensure .bundle.yaml, its type definition and entry form a valid Content Bundle.`,
306
+ );
307
+ }
308
+ }
252
309
  async function artifact(source: string, options: AuthoringOptions) {
253
310
  if (source.startsWith("builtin:")) {
254
311
  schemaAlias(source);
package/src/cli.ts CHANGED
@@ -6,8 +6,10 @@ import { randomUUID } from "node:crypto";
6
6
  import { CID } from "multiformats/cid";
7
7
  import stringWidth from "string-width";
8
8
  import {
9
+ LOCAL_SWARM_ALIAS,
9
10
  configKey,
10
11
  effectiveConfig,
12
+ isLocalSwarm,
11
13
  parseValue,
12
14
  publicUrl,
13
15
  stateLocation,
@@ -39,7 +41,9 @@ import {
39
41
  buildBundle,
40
42
  inspectBundle,
41
43
  importBundle,
44
+ localBundleDirectory,
42
45
  nodeError,
46
+ snapshotBundle,
43
47
  } from "./authoring.js";
44
48
  import { initApp } from "./app-authoring.js";
45
49
  import { assembleBundle } from "./assembly.js";
@@ -768,7 +772,7 @@ const commandHelp: Record<
768
772
  open: {
769
773
  summary: "Open content with its registered App",
770
774
  arguments: [
771
- "CONTENT Bundle CID, packaged builtin reference or Swarm IPAB URI.",
775
+ "CONTENT Local Bundle directory, Bundle CID, packaged builtin reference or Swarm IPAB URI.",
772
776
  ],
773
777
  options: [
774
778
  "--log Record stdout/stderr; requires history enabled.",
@@ -777,12 +781,13 @@ const commandHelp: Record<
777
781
  "--no-refresh Override swarm.forceRefresh and use valid cached headers.",
778
782
  ],
779
783
  examples: [
780
- "ipab open CONTENT_CID",
784
+ "ipab open .",
781
785
  "ipab open --log --refresh ipab:///documents/readme",
782
786
  "ipab open ipab:///",
783
787
  ],
784
788
  notes: [
785
789
  "Requires a saved registration and App support for the exact content type.",
790
+ "Local directories must contain valid Bundle metadata; quote paths with spaces. Snapshots honor .bundle-ignore without compiling, publishing, pinning, writing CAR files or updating the source.",
786
791
  "An empty URI Name (ipab:/// or ipab://ALIAS/) resolves to that Swarm's verified root State CID, not its publication CID. The root binding cannot be overwritten.",
787
792
  "Uses only the content URI's Swarm, otherwise --swarm, otherwise swarm.default. A selected Swarm is required.",
788
793
  "A registered App's retrieval, compatibility or execution failure never triggers fallback.",
@@ -957,7 +962,7 @@ const commandHelp: Record<
957
962
 
958
963
  export function help(path = ""): string {
959
964
  const globalOptions = `Global options (before COMMAND):
960
- --swarm URL|ALIAS Select shared swarm (otherwise swarm.default; URI swarm takes precedence)
965
+ --swarm URL|ALIAS Select Swarm (defaults to built-in local Swarm or saved swarm.default; URI swarm takes precedence)
961
966
  --state-dir PATH Set a dedicated, account-private local state directory
962
967
  --store-gateway URL Use a read-only upstream HTTP gateway
963
968
  --json Output management/development metadata, not App stdio`;
@@ -1911,7 +1916,7 @@ async function performCli(
1911
1916
  if (parsed.path === "templates list") {
1912
1917
  const items = await swarmTemplates(context, configUrl);
1913
1918
  const alias = state
1914
- .swarms()
1919
+ .allSwarms()
1915
1920
  .find((swarm) => swarm.cid === configUrl)?.alias;
1916
1921
  emit(
1917
1922
  { items },
@@ -1931,7 +1936,7 @@ async function performCli(
1931
1936
  if (parsed.flags.json) io.out(JSON.stringify(item));
1932
1937
  else {
1933
1938
  const alias = state
1934
- .swarms()
1939
+ .allSwarms()
1935
1940
  .find((swarm) => swarm.cid === configUrl)?.alias;
1936
1941
  const swarm = alias ?? configUrl;
1937
1942
  const reference = formatNameReference(swarm, item.name);
@@ -2051,7 +2056,7 @@ async function performCli(
2051
2056
  if (parsed.path === "register list") {
2052
2057
  const items = await swarmRegistrations(context, configUrl);
2053
2058
  const alias = state
2054
- .swarms()
2059
+ .allSwarms()
2055
2060
  .find((swarm) => swarm.cid === configUrl)?.alias;
2056
2061
  results.push({ items });
2057
2062
  human.push(
@@ -2158,27 +2163,25 @@ async function performCli(
2158
2163
  break;
2159
2164
  }
2160
2165
  case "swarm list": {
2161
- const result = { swarms: state.swarms(), ...selection() };
2166
+ const result = { swarms: state.allSwarms(), ...selection() };
2162
2167
  emit(
2163
2168
  {
2164
2169
  ...result,
2165
2170
  swarms: result.swarms.map((entry) => ({
2166
2171
  configUrl: entry.cid,
2167
2172
  alias: entry.alias,
2173
+ local: Boolean(entry.local),
2168
2174
  })),
2169
2175
  },
2170
2176
  [
2171
2177
  ...alignedRows(
2172
2178
  result.swarms.map((entry) => [
2173
- `${entry.cid === result.effectiveCurrent ? "*" : " "} ${entry.alias ?? entry.cid}`,
2179
+ `${entry.cid === result.effectiveCurrent ? "*" : " "} ${entry.alias ?? entry.cid}${entry.local ? " [local]" : ""}`,
2174
2180
  entry.cid,
2175
2181
  ]),
2176
2182
  ),
2177
- ...(result.swarms.length ? [] : ["No registered Swarms."]),
2178
- ...(result.effectiveCurrent === null
2179
- ? ["Use ipab swarm use <alias> to select a default Swarm."]
2180
- : []),
2181
- ...(result.effectiveCurrent !== result.savedCurrent
2183
+ ...(result.source === "flag" &&
2184
+ result.effectiveCurrent !== result.savedCurrent
2182
2185
  ? [
2183
2186
  `Selected via --swarm: ${printable(String(result.swarms.find((entry) => entry.cid === result.effectiveCurrent)?.alias ?? result.effectiveCurrent ?? "(none)"))}; saved default: ${printable(String(result.swarms.find((entry) => entry.cid === result.savedCurrent)?.alias ?? result.savedCurrent ?? "(none)"))}.`,
2184
2187
  ]
@@ -2346,6 +2349,17 @@ async function performCli(
2346
2349
  requireSwarm(),
2347
2350
  Boolean(parsed.options.refresh || parsed.options.force),
2348
2351
  );
2352
+ if (result.mode === "local") {
2353
+ emit(
2354
+ result,
2355
+ [
2356
+ "Swarm: local (Built-in single-machine Swarm)",
2357
+ "Mode: local",
2358
+ "Members: local user only (single-machine; no remote collaborators or HOME identity required)",
2359
+ ].join("\n"),
2360
+ );
2361
+ break;
2362
+ }
2349
2363
  emit(
2350
2364
  result,
2351
2365
  [
@@ -2446,7 +2460,7 @@ async function performCli(
2446
2460
  break;
2447
2461
  }
2448
2462
  if (parsed.path === "search") {
2449
- const registrations = state.swarms();
2463
+ const registrations = state.allSwarms();
2450
2464
  const scope = parsed.options.all
2451
2465
  ? registrations
2452
2466
  : [
@@ -2483,6 +2497,43 @@ async function performCli(
2483
2497
  }
2484
2498
  if (parsed.path === "swarm status") {
2485
2499
  const cid = requireSwarm();
2500
+ const status = await inspectSwarmStatus(
2501
+ context,
2502
+ cid,
2503
+ Boolean(parsed.options.refresh || parsed.options.force),
2504
+ );
2505
+ store = context.store;
2506
+ if (status.mode === "local") {
2507
+ emit(
2508
+ {
2509
+ mode: "local",
2510
+ configUrl: cid,
2511
+ root: status.head.root,
2512
+ valueCid: status.head.cid,
2513
+ properties: {
2514
+ name: status.config.name,
2515
+ description: status.config.description,
2516
+ },
2517
+ local: status.local,
2518
+ },
2519
+ [
2520
+ "Swarm",
2521
+ " Mode: local (built-in single-machine Swarm)",
2522
+ ` Name: ${printable(status.config.name)}`,
2523
+ ` Description: ${printable(status.config.description)}`,
2524
+ " Config URL:",
2525
+ ` ${cid}`,
2526
+ "",
2527
+ "Content",
2528
+ " HEAD (publication root):",
2529
+ ` ${status.head.root}`,
2530
+ " Content CID (HEAD value):",
2531
+ ` ${status.head.cid}`,
2532
+ ` Names: ${status.local.names} (Templates: ${status.local.templates}, Skills: ${status.local.skills}, Registrations: ${status.local.registrations})`,
2533
+ ].join("\n"),
2534
+ );
2535
+ break;
2536
+ }
2486
2537
  const {
2487
2538
  head,
2488
2539
  config,
@@ -2490,13 +2541,8 @@ async function performCli(
2490
2541
  cache,
2491
2542
  lastWriter,
2492
2543
  state: contentState,
2493
- } = await inspectSwarmStatus(
2494
- context,
2495
- cid,
2496
- Boolean(parsed.options.refresh || parsed.options.force),
2497
- );
2544
+ } = status;
2498
2545
  const fingerprint = await keyId(config.owner);
2499
- store = context.store;
2500
2546
  emit(
2501
2547
  {
2502
2548
  configUrl: cid,
@@ -2712,6 +2758,10 @@ async function performCli(
2712
2758
  break;
2713
2759
  } else if (parsed.path === "swarm approve") {
2714
2760
  const selected = requireSwarm();
2761
+ if (isLocalSwarm(selected))
2762
+ throw new HostError(
2763
+ `The built-in "${LOCAL_SWARM_ALIAS}" Swarm is a single-machine Swarm and does not support swarm approve.`,
2764
+ );
2715
2765
  if (first === "-" && !parsed.options.yes)
2716
2766
  syntax(
2717
2767
  "Reading a Request from stdin requires explicit --yes; no interactive confirmation is available.",
@@ -3216,16 +3266,22 @@ async function performCli(
3216
3266
  store = new IpfsStore(await storeConfiguration(value("store.gateway")));
3217
3267
  const context = swarmContext();
3218
3268
  readContext = context;
3219
- const target = (
3220
- await resolveReference(
3221
- context,
3222
- first!,
3223
- selectedSwarm,
3224
- (reference) => state!.resolve(reference),
3225
- Boolean(parsed.options.raw),
3226
- "local-first",
3227
- )
3228
- ).cid;
3269
+ const directory =
3270
+ parsed.path === "open"
3271
+ ? await localBundleDirectory(first!)
3272
+ : undefined;
3273
+ const target = directory
3274
+ ? undefined
3275
+ : (
3276
+ await resolveReference(
3277
+ context,
3278
+ first!,
3279
+ selectedSwarm,
3280
+ (reference) => state!.resolve(reference),
3281
+ Boolean(parsed.options.raw),
3282
+ "local-first",
3283
+ )
3284
+ ).cid;
3229
3285
  store = context.store;
3230
3286
  const resolveBundleReference = async (
3231
3287
  reference: string,
@@ -3289,14 +3345,17 @@ async function performCli(
3289
3345
  let appCid: string;
3290
3346
  let appArgv: string[];
3291
3347
  if (parsed.path === "open") {
3292
- const root = target;
3348
+ const session = directory ? `open:${randomUUID()}` : null;
3293
3349
  const owner = await Ownership.create(
3294
3350
  state,
3295
3351
  store,
3296
3352
  `open:${randomUUID()}`,
3297
- null,
3353
+ session,
3298
3354
  );
3299
3355
  try {
3356
+ const root = directory
3357
+ ? await snapshotBundle(directory, owner, session!)
3358
+ : target!;
3300
3359
  const content = await validatedBundle(root, store, owner);
3301
3360
  const schema = content.schemaKey;
3302
3361
  let association: Association | undefined;
@@ -3354,7 +3413,7 @@ async function performCli(
3354
3413
  await owner.release();
3355
3414
  }
3356
3415
  } else {
3357
- appCid = target;
3416
+ appCid = target!;
3358
3417
  appArgv = parsed.positional.slice(1);
3359
3418
  }
3360
3419
  appExitCode = (
package/src/config.ts CHANGED
@@ -33,9 +33,26 @@ export interface ConfigItem {
33
33
  value: ConfigValue;
34
34
  source: Source;
35
35
  }
36
+ export const LOCAL_SWARM_ALIAS = "local";
37
+ export const LOCAL_SWARM_URL =
38
+ "https://example.invalid/v1/0000000000000000/0000000000000000";
39
+
40
+ export function isLocalSwarm(value: string): boolean {
41
+ return value === LOCAL_SWARM_URL;
42
+ }
43
+
44
+ export function isReservedLocalHost(value: string): boolean {
45
+ try {
46
+ const host = new URL(value).hostname.toLowerCase();
47
+ return host === "invalid" || host.endsWith(".invalid");
48
+ } catch {
49
+ return false;
50
+ }
51
+ }
52
+
36
53
  export const defaults: Record<ConfigKey, ConfigValue> = {
37
54
  "daemon.uiPort": 0,
38
- "swarm.default": null,
55
+ "swarm.default": LOCAL_SWARM_URL,
39
56
  "swarm.listen": "lan",
40
57
  "swarm.pivot": false,
41
58
  "swarm.cacheTtl": 300,
@@ -135,7 +152,8 @@ export function parseValue(
135
152
  if (text && typeof value === "string") {
136
153
  if (key === "daemon.uiPort" && value === "default") return defaults[key];
137
154
  if (key.startsWith("swarm.") && value === "default")
138
- return key === "swarm.cacheTtl" ||
155
+ return key === "swarm.default" ||
156
+ key === "swarm.cacheTtl" ||
139
157
  key === "swarm.syncInterval" ||
140
158
  key === "swarm.forceRefresh" ||
141
159
  key === "swarm.pivot" ||
package/src/doctor.ts CHANGED
@@ -15,7 +15,10 @@ import { RESOURCE_ID_PATTERN, ScopeClient } from "@ipab/bundle/pointer/scope";
15
15
  import { nodeError } from "./authoring.js";
16
16
  import { accountIdentity, protectedPath, secureNew } from "./identity.js";
17
17
  import {
18
+ LOCAL_SWARM_ALIAS,
18
19
  effectiveConfig,
20
+ isLocalSwarm,
21
+ isReservedLocalHost,
19
22
  swarmUrl,
20
23
  validateUserConfig,
21
24
  type ConfigKey,
@@ -684,17 +687,24 @@ async function inspect(
684
687
  )
685
688
  throw new Error("Invalid registry.");
686
689
  const url = swarmUrl(row.cid);
687
- if (url !== row.cid || urls.has(url))
690
+ if (
691
+ url !== row.cid ||
692
+ urls.has(url) ||
693
+ isLocalSwarm(url) ||
694
+ isReservedLocalHost(url)
695
+ )
688
696
  throw new Error("Invalid registry.");
689
697
  urls.add(url);
690
698
  if (row.alias !== null) {
691
699
  swarmAlias(row.alias);
692
- if (aliases.has(row.alias)) throw new Error("Duplicate alias.");
700
+ if (row.alias === LOCAL_SWARM_ALIAS || aliases.has(row.alias))
701
+ throw new Error("Duplicate alias.");
693
702
  aliases.add(row.alias);
694
703
  }
695
704
  }
696
705
  if (
697
706
  typeof user["swarm.default"] === "string" &&
707
+ !isLocalSwarm(user["swarm.default"]) &&
698
708
  !urls.has(user["swarm.default"])
699
709
  )
700
710
  throw new Error("Unregistered default.");
package/src/get.ts CHANGED
@@ -65,7 +65,8 @@ export async function getBundle(
65
65
  "Download destination must not cross a symlink or file.",
66
66
  );
67
67
  } catch (cause) {
68
- if (!nodeError(cause, "ENOENT")) throw cause;
68
+ if (!nodeError(cause, "ENOENT") && !nodeError(cause, "ENOTDIR"))
69
+ throw cause;
69
70
  }
70
71
  if (dirname(current) === current) break;
71
72
  }
package/src/state.ts CHANGED
@@ -4,6 +4,10 @@ import { DatabaseSync } from "node:sqlite";
4
4
  import { CID } from "multiformats/cid";
5
5
  import type { StoreConfiguration } from "@ipab/ipfs-store";
6
6
  import {
7
+ LOCAL_SWARM_ALIAS,
8
+ LOCAL_SWARM_URL,
9
+ isLocalSwarm,
10
+ isReservedLocalHost,
7
11
  rejectLegacySwarmCid,
8
12
  validateUserConfig,
9
13
  swarmUrl,
@@ -35,6 +39,13 @@ export interface RegisteredSwarm {
35
39
  // Keep the storage column name, but values are configuration URLs; old CID rows are rejected.
36
40
  cid: string;
37
41
  alias: string | null;
42
+ local?: boolean;
43
+ }
44
+ export interface LocalSwarmRecord {
45
+ headCid: string;
46
+ valueCid: string;
47
+ createdAt: string;
48
+ updatedAt: string;
38
49
  }
39
50
  export interface SwarmProjection {
40
51
  account: string;
@@ -271,7 +282,8 @@ export class State {
271
282
  CREATE INDEX IF NOT EXISTS idx_swarm_search_entries_swarm_kind ON swarm_search_entries (swarm,kind);
272
283
  CREATE INDEX IF NOT EXISTS idx_swarm_search_entries_swarm_schema ON swarm_search_entries (swarm,schema_cid);
273
284
  CREATE TABLE IF NOT EXISTS runs (id TEXT PRIMARY KEY, value TEXT NOT NULL);
274
- CREATE TABLE IF NOT EXISTS holds (owner TEXT PRIMARY KEY, value TEXT NOT NULL);`);
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);`);
275
287
  this.transaction(() => {
276
288
  if (
277
289
  this.db
@@ -396,6 +408,84 @@ export class State {
396
408
  resetConfig(key: ConfigKey | "store.rpc"): void {
397
409
  this.db.prepare("DELETE FROM config WHERE key=?").run(key);
398
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
+ }
399
489
  swarms(): RegisteredSwarm[] {
400
490
  return this.db
401
491
  .prepare("SELECT cid,alias FROM swarms ORDER BY cid")
@@ -407,11 +497,25 @@ export class State {
407
497
  )
408
498
  throw new HostError("Invalid persisted swarm registration.");
409
499
  const cid = swarmUrl(row.cid);
410
- if (row.alias !== null) swarmAlias(row.alias);
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
+ }
411
507
  return { cid, alias: row.alias };
412
508
  });
413
509
  }
510
+ allSwarms(): RegisteredSwarm[] {
511
+ return [
512
+ { cid: LOCAL_SWARM_URL, alias: LOCAL_SWARM_ALIAS, local: true },
513
+ ...this.swarms(),
514
+ ];
515
+ }
414
516
  resolveSwarm(reference: string): string {
517
+ if (reference === LOCAL_SWARM_ALIAS || reference === LOCAL_SWARM_URL)
518
+ return LOCAL_SWARM_URL;
415
519
  if (/^https?:/.test(reference)) return swarmUrl(reference);
416
520
  const entry = this.swarms().find((entry) => entry.alias === reference);
417
521
  if (entry) return entry.cid;
@@ -422,6 +526,8 @@ export class State {
422
526
  }
423
527
  registeredSwarm(reference: string): RegisteredSwarm {
424
528
  const cid = this.resolveSwarm(reference);
529
+ if (isLocalSwarm(cid))
530
+ return { cid: LOCAL_SWARM_URL, alias: LOCAL_SWARM_ALIAS, local: true };
425
531
  const entry = this.swarms().find((entry) => entry.cid === cid);
426
532
  if (!entry)
427
533
  throw new HostError(
@@ -431,6 +537,7 @@ export class State {
431
537
  }
432
538
  checkSwarmAlias(alias: string, cid?: string): void {
433
539
  swarmAlias(alias);
540
+ this.rejectReservedRemoteAlias(alias);
434
541
  const existing = this.swarms().find((entry) => entry.alias === alias);
435
542
  if (existing && existing.cid !== cid)
436
543
  throw new HostError(
@@ -439,6 +546,7 @@ export class State {
439
546
  }
440
547
  registerSwarm(cid: string, alias?: string): RegisteredSwarm {
441
548
  cid = swarmUrl(cid);
549
+ this.rejectReservedRemoteUrl(cid);
442
550
  return this.transaction(() => {
443
551
  if (alias !== undefined) this.checkSwarmAlias(alias, cid);
444
552
  return this.saveSwarmRegistration(cid, alias);
@@ -450,7 +558,9 @@ export class State {
450
558
  expectedTarget: string | null,
451
559
  ): RegisteredSwarm {
452
560
  swarmAlias(alias);
561
+ this.rejectReservedRemoteAlias(alias);
453
562
  url = swarmUrl(url);
563
+ this.rejectReservedRemoteUrl(url);
454
564
  return this.transaction(() => {
455
565
  const current = this.swarms().find((entry) => entry.alias === alias);
456
566
  if ((current?.cid ?? null) !== expectedTarget)
@@ -483,6 +593,11 @@ export class State {
483
593
  }
484
594
  removeSwarm(reference: string): string {
485
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
+ );
486
601
  const entry = this.registeredSwarm(reference);
487
602
  this.db.prepare("DELETE FROM swarms WHERE cid=?").run(entry.cid);
488
603
  this.deleteSwarmCache(entry.cid);