@acrylblends/blends-frame 0.1.1 → 0.1.3

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 (38) hide show
  1. package/lib/app-plugins.d.ts +32 -5
  2. package/lib/client.js +31886 -367
  3. package/lib/client.js.map +1 -1
  4. package/lib/contract.d.ts +116 -0
  5. package/lib/github-connect.d.ts +44 -0
  6. package/lib/graph-contract.d.ts +85 -0
  7. package/lib/graph-inspect.d.ts +16 -0
  8. package/lib/index.d.ts +20 -3
  9. package/lib/index.js +1040 -36
  10. package/lib/index.js.map +1 -1
  11. package/lib/plain.d.ts +26 -0
  12. package/lib/plugin-graph.d.ts +38 -0
  13. package/lib/registry.d.ts +71 -0
  14. package/lib/types/client/AppSection.d.ts +10 -0
  15. package/lib/types/client/BlendsFrame.d.ts +7 -1
  16. package/lib/types/client/GraphView.d.ts +22 -0
  17. package/lib/types/client/NameYourApp.d.ts +10 -0
  18. package/lib/types/client/PluginsSection.d.ts +11 -1
  19. package/lib/types/client/RegistryView.d.ts +11 -0
  20. package/lib/types/client/SettingsExpand.d.ts +6 -0
  21. package/lib/types/client/ShareChooser.d.ts +21 -0
  22. package/lib/types/client/desktop-app.d.ts +65 -0
  23. package/lib/types/client/graph-api.d.ts +11 -0
  24. package/lib/types/client/graph-canvas.d.ts +63 -0
  25. package/lib/types/client/graph-link.d.ts +21 -0
  26. package/lib/types/client/graph-model.d.ts +23 -0
  27. package/lib/types/client/graph-styles.d.ts +3 -0
  28. package/lib/types/client/index.d.ts +1 -1
  29. package/lib/types/client/plain-failure.d.ts +10 -0
  30. package/lib/types/client/plugins-navigator.d.ts +37 -7
  31. package/lib/types/client/registry-api.d.ts +21 -0
  32. package/lib/types/client/registry-list.d.ts +14 -0
  33. package/lib/types/client/settings-fullscreen.d.ts +13 -0
  34. package/lib/types/client/theme-switch.d.ts +27 -0
  35. package/lib/types/contract.d.ts +116 -0
  36. package/lib/types/graph-contract.d.ts +85 -0
  37. package/lib/types/graph-inspect.d.ts +16 -0
  38. package/package.json +9 -7
package/lib/index.js CHANGED
@@ -1,16 +1,16 @@
1
1
  import { appGeneration } from "./app-generation.js";
2
2
  import { createRequire } from "node:module";
3
- import { execFile, execFileSync } from "node:child_process";
3
+ import { execFile, execFileSync, spawn, spawnSync } from "node:child_process";
4
4
  import { cpSync, existsSync, mkdirSync, readFileSync, readdirSync, realpathSync, rmSync, statSync, watch, writeFileSync } from "node:fs";
5
5
  import { mkdir, readFile, readdir, rename, writeFile } from "node:fs/promises";
6
6
  import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
7
7
  import { Acryl } from "acrylblends";
8
8
  import { error } from "@acrylblends/loopback-http";
9
9
  import { INVALID_JSON, jsonBody, ownPage, privateApi, readJson } from "@acrylblends/loopback-http/router";
10
+ import { PluginStore, StoreConflictError, bumpVersion, gitCli, githubCli, parseVersion, savePlugin, sharePlugin, storeRootOf } from "@webboxes/plugin-hub";
10
11
  import { GitRunner, Versions } from "@acrylblends/versions";
11
12
  import * as workspaceHost from "@acrylblends/workspace";
12
13
  import { promisify } from "node:util";
13
- import { PluginStore, bumpVersion, gitCli, githubCli, parseVersion, sharePlugin, storeRootOf } from "@webboxes/plugin-hub";
14
14
  import { pathToFileURL } from "node:url";
15
15
  import { digestFolder } from "@webboxes/blends-core";
16
16
  import { parseDocument } from "yaml";
@@ -43,7 +43,7 @@ const FRAME_GIT_PULL_PATH = `${FRAME_API_PREFIX}/git/pull`;
43
43
  const FRAME_SNAPSHOT_CAPTURE_PATH = `${FRAME_API_PREFIX}/snapshot/capture`;
44
44
  /** @throws when the value is not a push plan. */
45
45
  function parsePushPlan(value) {
46
- if (!isRecord$1(value)) throw new Error("push plan: not a plan");
46
+ if (!isRecord$2(value)) throw new Error("push plan: not a plan");
47
47
  const { branch, remote, target, address, versions, createsBranch, head } = value;
48
48
  if (!isName(branch) || !isName(remote) || !isName(target) || !isName(address)) throw new Error("push plan: names");
49
49
  if (!isCount(versions) || typeof createsBranch !== "boolean" || typeof head !== "string" || !/^[0-9a-f]{40,64}$/u.test(head)) throw new Error("push plan: versions");
@@ -73,12 +73,12 @@ function branchNameProblem(name) {
73
73
  if (!/^[A-Za-z0-9][A-Za-z0-9._/-]*$/u.test(name)) return "Use letters, digits, - _ . and /, starting with a letter or digit.";
74
74
  if (name.includes("..") || name.includes("//") || name.endsWith("/") || name.endsWith(".") || name.endsWith(".lock")) return "That is not a name git accepts.";
75
75
  }
76
- function isRecord$1(value) {
76
+ function isRecord$2(value) {
77
77
  return value !== null && typeof value === "object" && !Array.isArray(value);
78
78
  }
79
79
  /** @throws an Error naming the field when the answer is not a frame state. */
80
80
  function parseFrameState(value) {
81
- if (!isRecord$1(value)) throw new Error("frame state: not an object");
81
+ if (!isRecord$2(value)) throw new Error("frame state: not an object");
82
82
  const { appName, appRoot, appPage, branches, head, unsaved, upstreamHead } = value;
83
83
  if (typeof appName !== "string" || appName === "") throw new Error("frame state: appName");
84
84
  if (typeof appRoot !== "string" || appRoot === "") throw new Error("frame state: appRoot");
@@ -88,7 +88,7 @@ function parseFrameState(value) {
88
88
  if (unsaved !== void 0 && (typeof unsaved !== "number" || !Number.isInteger(unsaved) || unsaved < 0)) throw new Error("frame state: unsaved");
89
89
  if (upstreamHead !== void 0 && (typeof upstreamHead !== "string" || upstreamHead === "")) throw new Error("frame state: upstreamHead");
90
90
  const parsed = branches.map((branch) => {
91
- if (!isRecord$1(branch) || typeof branch.name !== "string" || typeof branch.current !== "boolean") throw new Error("frame state: branch");
91
+ if (!isRecord$2(branch) || typeof branch.name !== "string" || typeof branch.current !== "boolean") throw new Error("frame state: branch");
92
92
  return {
93
93
  name: branch.name,
94
94
  current: branch.current
@@ -110,26 +110,41 @@ const FRAME_PLUGINS_SWITCH_PATH = `${FRAME_API_PREFIX}/plugins/switch`;
110
110
  const FRAME_PLUGINS_SHARE_PLAN_PATH = `${FRAME_API_PREFIX}/plugins/share-plan`;
111
111
  /** POST `{ name, confirm }`: publish it, only when `confirm` is the plan the person said yes to and it still holds. */
112
112
  const FRAME_PLUGINS_SHARE_PATH = `${FRAME_API_PREFIX}/plugins/share`;
113
+ /** POST `{ name }`: keep a packed copy of this local plugin on this machine (the app's plugin store); nothing leaves the machine. */
114
+ const FRAME_PLUGINS_SAVE_PATH = `${FRAME_API_PREFIX}/plugins/save`;
115
+ /** GET: the public plugin registry (cordisplugins.github.io), each entry marked when this app already has it; read fresh by the Host, never by the page. */
116
+ const FRAME_PLUGINS_REGISTRY_PATH = `${FRAME_API_PREFIX}/plugins/registry`;
117
+ /** GET: whether this computer can share to GitHub (the helper program is installed and signed in), read before the person is asked anything. */
118
+ const FRAME_PLUGINS_GITHUB_PATH = `${FRAME_API_PREFIX}/plugins/github`;
119
+ /** POST: start GitHub's browser sign-in (a one-time code for github.com/login/device); GET: where it is; DELETE: stop one still waiting. */
120
+ const FRAME_PLUGINS_GITHUB_CONNECT_PATH = `${FRAME_API_PREFIX}/plugins/github/connect`;
121
+ /** POST `{ source }`: pull one released plugin (`github:<owner>/<repo>@<version>`) into the running app, through the app's plugin-share checks. */
122
+ const FRAME_PLUGINS_PULL_PATH = `${FRAME_API_PREFIX}/plugins/pull`;
113
123
  const GITHUB_NAME = /^[A-Za-z0-9][A-Za-z0-9._-]*$/u;
114
124
  /** @throws when the value is not a share plan. */
115
125
  function parseSharePlan(value) {
116
- if (!isRecord$1(value)) throw new Error("share plan: not a plan");
117
- const { owner, repo, version, visibility, createsRepository, released } = value;
126
+ if (!isRecord$2(value)) throw new Error("share plan: not a plan");
127
+ const { owner, repo, version, visibility, createsRepository, released, license, registry } = value;
118
128
  if (typeof owner !== "string" || !GITHUB_NAME.test(owner) || typeof repo !== "string" || !GITHUB_NAME.test(repo)) throw new Error("share plan: repository");
119
129
  if (typeof version !== "string" || version === "" || released !== void 0 && (typeof released !== "string" || released === "")) throw new Error("share plan: version");
120
130
  if (visibility !== "private" && visibility !== "public" || typeof createsRepository !== "boolean") throw new Error("share plan: visibility");
131
+ if (license !== void 0 && (typeof license !== "string" || !/^[A-Za-z0-9.+-]+$/u.test(license))) throw new Error("share plan: license");
132
+ if (registry !== void 0 && typeof registry !== "boolean") throw new Error("share plan: registry");
133
+ if (registry === true && visibility !== "public") throw new Error("share plan: only a public share can be listed in the registry");
121
134
  return {
122
135
  owner,
123
136
  repo,
124
137
  version,
125
138
  visibility,
126
139
  createsRepository,
127
- ...released === void 0 ? {} : { released }
140
+ ...released === void 0 ? {} : { released },
141
+ ...license === void 0 ? {} : { license },
142
+ ...registry === true ? { registry } : {}
128
143
  };
129
144
  }
130
145
  /** The same plan: what the person confirmed is what would be published now. */
131
146
  function samePlan(a, b) {
132
- return a.owner === b.owner && a.repo === b.repo && a.version === b.version && a.visibility === b.visibility && a.createsRepository === b.createsRepository && a.released === b.released;
147
+ return a.owner === b.owner && a.repo === b.repo && a.version === b.version && a.visibility === b.visibility && a.createsRepository === b.createsRepository && a.released === b.released && a.license === b.license && a.registry === true === (b.registry === true);
133
148
  }
134
149
  const FRAME_FEEDBACK_PATH = `${FRAME_API_PREFIX}/feedback`;
135
150
  const FRAME_FEEDBACK_SEEN_PATH = `${FRAME_API_PREFIX}/feedback/seen`;
@@ -139,15 +154,15 @@ const FRAME_FEEDBACK_SHOT_PATH = `${FRAME_API_PREFIX}/feedback/shot`;
139
154
  function parseFeedbackNotes(value) {
140
155
  if (!Array.isArray(value)) throw new Error("feedback: not a list");
141
156
  return value.map((entry) => {
142
- if (!isRecord$1(entry) || typeof entry.id !== "string" || typeof entry.at !== "string" || typeof entry.text !== "string" || typeof entry.page !== "string" || typeof entry.seen !== "boolean") throw new Error("feedback: note");
157
+ if (!isRecord$2(entry) || typeof entry.id !== "string" || typeof entry.at !== "string" || typeof entry.text !== "string" || typeof entry.page !== "string" || typeof entry.seen !== "boolean") throw new Error("feedback: note");
143
158
  const element = entry.element;
144
- const pinned = isRecord$1(element) && typeof element.selector === "string" && typeof element.label === "string" ? { element: {
159
+ const pinned = isRecord$2(element) && typeof element.selector === "string" && typeof element.label === "string" ? { element: {
145
160
  selector: element.selector,
146
161
  label: element.label
147
162
  } } : {};
148
163
  const shot = entry.screenshot;
149
164
  let screenshot = {};
150
- if (isRecord$1(shot) && (shot["mediaType"] === "image/webp" || shot["mediaType"] === "image/png") && typeof shot["width"] === "number" && typeof shot["height"] === "number") screenshot = { screenshot: {
165
+ if (isRecord$2(shot) && (shot["mediaType"] === "image/webp" || shot["mediaType"] === "image/png") && typeof shot["width"] === "number" && typeof shot["height"] === "number") screenshot = { screenshot: {
151
166
  mediaType: shot["mediaType"],
152
167
  width: shot["width"],
153
168
  height: shot["height"]
@@ -361,11 +376,68 @@ async function checkedShares(records, check) {
361
376
  const entries = await Promise.all(Object.entries(records).map(async ([name, shared]) => [name, await check(shared.url) === false ? {
362
377
  url: shared.url,
363
378
  version: shared.version,
364
- gone: true
379
+ gone: true,
380
+ ...shared.registry === true ? { registry: true } : {}
365
381
  } : shared]));
366
382
  return Object.fromEntries(entries);
367
383
  }
368
- async function readAppPlugins(root, git, sharedFile, check) {
384
+ /** A path inside `root` as a relative path with forward slashes, or undefined when it is outside. */
385
+ function insideApp(root, file) {
386
+ const rel = relative(root, file);
387
+ if (rel === "" || rel.startsWith("..") || isAbsolute(rel)) return void 0;
388
+ return rel.split("\\").join("/");
389
+ }
390
+ /** The files a plugin's code starts in, first match wins: the entry beside its package.json, then `src/`, then what package.json names, then the README. */
391
+ function mainFileOf(folder) {
392
+ const entries = [...ENTRIES, ...ENTRIES.map((file) => join("src", file))];
393
+ const named = [];
394
+ try {
395
+ const manifest = JSON.parse(readFileSync(join(folder, "package.json"), "utf8"));
396
+ if (typeof manifest.main === "string") named.push(manifest.main);
397
+ const dot = typeof manifest.exports === "object" && manifest.exports !== null ? manifest.exports["."] : manifest.exports;
398
+ if (typeof dot === "string") named.push(dot);
399
+ } catch {}
400
+ return [
401
+ ...entries,
402
+ ...named,
403
+ "README.md"
404
+ ].find((file) => existsSync(join(folder, file)));
405
+ }
406
+ /** The plugin's own folder in `plugins/` with the file its code starts in, else undefined. */
407
+ function ownLocation(root, name) {
408
+ const folder = join(root, "plugins", name);
409
+ if (!existsSync(folder)) return void 0;
410
+ const entry = mainFileOf(folder);
411
+ return {
412
+ folder,
413
+ ...entry === void 0 ? {} : { main: `plugins/${name}/${entry.replace(/^\.\//u, "").split("\\").join("/")}` }
414
+ };
415
+ }
416
+ /** Where a plugin of `blend.yaml` or the frame has its code: a folder of the app's `plugins/`, else the package the app installed (read-only). */
417
+ async function pluginLocation(root, name) {
418
+ const own = ownLocation(root, name);
419
+ if (own !== void 0) return own;
420
+ const found = await modulePackage(root, name);
421
+ if (found?.dir === void 0) return void 0;
422
+ const main = found.main === void 0 ? void 0 : insideApp(root, found.main);
423
+ return {
424
+ folder: found.dir,
425
+ ...main === void 0 ? {} : { main }
426
+ };
427
+ }
428
+ /** The newest packed copy of each plugin kept in the app's plugin store, by name. An unreadable store lists nothing. */
429
+ function savedCopies(storeRoot) {
430
+ const copies = /* @__PURE__ */ new Map();
431
+ if (storeRoot === void 0) return copies;
432
+ try {
433
+ for (const stored of new PluginStore(storeRoot).list()) if (!copies.has(stored.name)) copies.set(stored.name, {
434
+ version: stored.version,
435
+ path: stored.path
436
+ });
437
+ } catch {}
438
+ return copies;
439
+ }
440
+ async function readAppPlugins(root, git, sharedFile, check, storeRoot) {
369
441
  const text = await readFile(join(root, "blend.yaml"), "utf8");
370
442
  const off = new Set(extensionsOff(text));
371
443
  const versions = await libraryVersions(root);
@@ -373,9 +445,12 @@ async function readAppPlugins(root, git, sharedFile, check) {
373
445
  const shareRecords = check === void 0 ? recorded : await checkedShares(recorded, check);
374
446
  const blendRows = parseBlendRows(text);
375
447
  const own = await madePlugins(root);
448
+ const copies = savedCopies(storeRoot);
376
449
  const made = await Promise.all(own.map(async (name) => {
377
450
  const [description, first] = await Promise.all([packageDescription(join(root, "plugins", name)), firstCommit(git, root, `plugins/${name}`)]);
378
451
  const shared = shareRecords[name];
452
+ const saved = copies.get(name);
453
+ const where = ownLocation(root, name);
379
454
  const row = blendRows.find((entry) => entry.name === name);
380
455
  return {
381
456
  name,
@@ -385,6 +460,11 @@ async function readAppPlugins(root, git, sharedFile, check) {
385
460
  at: first.at
386
461
  },
387
462
  ...shared === void 0 ? {} : { shared },
463
+ ...saved === void 0 ? {} : { saved },
464
+ ...where === void 0 ? {} : {
465
+ folder: where.folder,
466
+ ...where.main === void 0 ? {} : { main: where.main }
467
+ },
388
468
  description,
389
469
  on: row === void 0 ? !off.has(name) : !row.disabled
390
470
  };
@@ -392,10 +472,15 @@ async function readAppPlugins(root, git, sharedFile, check) {
392
472
  const rows = await Promise.all(blendRows.filter((row) => !own.includes(row.name)).map(async (row) => {
393
473
  const description = row.comment !== "" ? firstSentence(row.comment) : await packageDescription(join(root, "plugins", row.name));
394
474
  const version = versions.get(row.name);
475
+ const where = await pluginLocation(root, row.name);
395
476
  return {
396
477
  name: row.name,
397
478
  kind: "row",
398
479
  ...version === void 0 ? {} : { version },
480
+ ...where === void 0 ? {} : {
481
+ folder: where.folder,
482
+ ...where.main === void 0 ? {} : { main: where.main }
483
+ },
399
484
  description,
400
485
  on: !row.disabled
401
486
  };
@@ -444,6 +529,8 @@ async function modulePackage(root, name) {
444
529
  const parsed = JSON.parse(await readFile(join(dir, "package.json"), "utf8"));
445
530
  if (parsed.name !== name) continue;
446
531
  return {
532
+ dir,
533
+ main: file,
447
534
  ...typeof parsed.version === "string" ? { version: parsed.version } : {},
448
535
  ...typeof parsed.description === "string" ? { description: parsed.description } : {}
449
536
  };
@@ -453,22 +540,26 @@ async function modulePackage(root, name) {
453
540
  async function readFramePlugins(root, rows) {
454
541
  return Promise.all(rows.filter((row) => isFramePlugin(row.name, row.id)).map(async (row) => {
455
542
  const manifest = await modulePackage(root, row.name);
543
+ const main = manifest?.main === void 0 ? void 0 : insideApp(root, manifest.main);
456
544
  return {
457
545
  id: row.id,
458
546
  name: row.name,
459
547
  ...manifest?.version === void 0 ? {} : { version: manifest.version },
460
548
  description: manifest?.description ?? "",
461
- state: frameRowState(row)
549
+ state: frameRowState(row),
550
+ ...manifest?.dir === void 0 ? {} : { folder: manifest.dir },
551
+ ...main === void 0 ? {} : { main }
462
552
  };
463
553
  }));
464
554
  }
465
555
  /** The package.json a local plugin is shared with: the fields the builder's package_plugin writes (plugins/builder/index.ts), plus the Loader
466
556
  * patch the plugin-hub's share requires so the package can also be installed as a row. */
467
- function pluginPackageManifest(name, description, version = "0.1.0") {
557
+ function pluginPackageManifest(name, description, version = "0.1.0", license) {
468
558
  return {
469
559
  name,
470
560
  version,
471
561
  description,
562
+ ...license === void 0 ? {} : { license },
472
563
  type: "module",
473
564
  exports: {
474
565
  ".": "./index.ts",
@@ -502,10 +593,11 @@ async function readSharedRecords(file) {
502
593
  const records = {};
503
594
  for (const [name, value] of Object.entries(parsed)) {
504
595
  if (value === null || typeof value !== "object") continue;
505
- const { url, version } = value;
596
+ const { url, version, registry } = value;
506
597
  if (typeof url === "string" && typeof version === "string") records[name] = {
507
598
  url,
508
- version
599
+ version,
600
+ ...registry === true ? { registry: true } : {}
509
601
  };
510
602
  }
511
603
  return records;
@@ -525,7 +617,7 @@ async function recordShare(file, name, shared) {
525
617
  /** Where the frame packages the plugins it shares: under the app's home, never in the app's folder, so a share leaves no file to save. */
526
618
  const pluginPackagesOf = (home) => join(home, "plugin-packages");
527
619
  /** Copy one local plugin into its package folder under `packages`, the way the builder's package_plugin does; answers the folder. */
528
- async function packageAppPlugin(root, name, packages) {
620
+ async function packageAppPlugin(root, name, packages, license) {
529
621
  if (!(await madePlugins(root)).includes(name)) throw new Error(`plugins/ has no local plugin "${name}"`);
530
622
  const source = join(root, "plugins", name);
531
623
  const target = join(packages, name);
@@ -544,7 +636,7 @@ async function packageAppPlugin(root, name, packages) {
544
636
  filter: (path) => !/(^|[\\/])(node_modules|\.git)([\\/]|$)/u.test(path.slice(source.length))
545
637
  });
546
638
  const description = await packageDescription(source);
547
- writeFileSync(join(target, "package.json"), `${JSON.stringify(pluginPackageManifest(name, description, version), null, 2)}\n`);
639
+ writeFileSync(join(target, "package.json"), `${JSON.stringify(pluginPackageManifest(name, description, version, license), null, 2)}\n`);
548
640
  writeFileSync(join(target, "cordis.patch.yml"), `- insert:\n - id: ${name}\n name: ./index.ts\n`);
549
641
  if (!existsSync(join(target, "README.md"))) writeFileSync(join(target, "README.md"), `# ${name}\n\n${description}\n\nA Cordis plugin. In an ACRYLBLENDS app: \`acrylblends add <this folder>\`.\n`);
550
642
  return target;
@@ -559,23 +651,67 @@ async function bumpPackageVersion(dir) {
559
651
  await writeFile(join(dir, "package.json"), `${JSON.stringify(manifest, null, 2)}\n`);
560
652
  return next;
561
653
  }
654
+ /**
655
+ * Keep a packed copy of one local plugin on this machine: the plugin is packaged under the app's home as a share does, then put in the app's plugin
656
+ * store with its checksum. A version is stored once: when this version is already saved with other content, the version is raised (patch) and saved
657
+ * again, so a changed plugin never overwrites an earlier copy. Nothing leaves the machine.
658
+ */
659
+ async function saveAppPlugin(root, home, name) {
660
+ const dir = await packageAppPlugin(root, name, pluginPackagesOf(home));
661
+ const store = new PluginStore(storeRootOf(home));
662
+ try {
663
+ const { stored, added } = savePlugin(dir, store);
664
+ return {
665
+ version: stored.version,
666
+ path: stored.path,
667
+ added,
668
+ bumped: false
669
+ };
670
+ } catch (cause) {
671
+ if (!(cause instanceof StoreConflictError)) throw cause;
672
+ }
673
+ await bumpPackageVersion(dir);
674
+ const { stored, added } = savePlugin(dir, store);
675
+ return {
676
+ version: stored.version,
677
+ path: stored.path,
678
+ added,
679
+ bumped: true
680
+ };
681
+ }
562
682
  const githubSharePorts = () => ({
563
683
  host: githubCli(),
564
684
  git: gitCli()
565
685
  });
566
686
  /**
687
+ * The hub labels every release with the topics catalogs find a plugin by, and `cordis-plugin` is the one the registry's sync lists a public repository
688
+ * by. A share that was not asked to go to the registry must not put the repository there, so its host takes no topics; a registry share passes them on.
689
+ */
690
+ function listedOnlyWhenAsked(host, listed) {
691
+ return {
692
+ ...host,
693
+ addTopics: (owner, repo, topics) => {
694
+ if (listed) host.addTopics(owner, repo, topics);
695
+ }
696
+ };
697
+ }
698
+ /**
567
699
  * What sharing one local plugin would do, read without sending anything: it packages the plugin under the app's home and asks the host who is
568
700
  * signed in, whether the repository exists and whether this version is released there (then the plan releases the next patch).
569
- * @param options - the repository owner (the signed-in account when absent).
701
+ * @param options - the repository owner (the signed-in account when absent), the visibility the person asked for (private when absent: a share is
702
+ * public only when the person chose it, because anyone can then read and pull it), the license of a public share (MIT when absent; the plan names it)
703
+ * and whether the public registry lists it (`registry`: the share sets the `cordis-plugin` topic, which the registry's hourly sync finds).
570
704
  */
571
705
  async function planAppPluginShare(root, home, name, options, ports) {
572
- const dir = await packageAppPlugin(root, name, pluginPackagesOf(home));
706
+ const registry = options.registry === true;
707
+ const visibility = registry ? "public" : options.visibility ?? "private";
708
+ const license = visibility === "public" ? options.license ?? "MIT" : void 0;
709
+ const dir = await packageAppPlugin(root, name, pluginPackagesOf(home), license);
573
710
  const manifest = JSON.parse(await readFile(join(dir, "package.json"), "utf8"));
574
711
  const current = typeof manifest.version === "string" && parseVersion(manifest.version) !== void 0 ? manifest.version : void 0;
575
712
  if (current === void 0) throw new Error(`${name}: its package has no semantic version`);
576
713
  const owner = options.owner ?? ports.host.login();
577
714
  const repo = name;
578
- const visibility = manifest.acryl?.visibility === "public" ? "public" : "private";
579
715
  const existing = ports.host.repository(owner, repo);
580
716
  const released = existing !== void 0 && ports.host.releaseExists(owner, repo, `v${current}`);
581
717
  return {
@@ -584,7 +720,9 @@ async function planAppPluginShare(root, home, name, options, ports) {
584
720
  version: released ? bumpVersion(current, "patch") : current,
585
721
  visibility,
586
722
  createsRepository: existing === void 0,
587
- ...released ? { released: current } : {}
723
+ ...released ? { released: current } : {},
724
+ ...license === void 0 ? {} : { license },
725
+ ...registry ? { registry } : {}
588
726
  };
589
727
  }
590
728
  /**
@@ -596,7 +734,12 @@ async function planAppPluginShare(root, home, name, options, ports) {
596
734
  * @param options - the repository owner the frame is configured with (the signed-in account when absent).
597
735
  */
598
736
  async function shareAppPlugin(root, home, name, confirmed, options, ports) {
599
- const plan = await planAppPluginShare(root, home, name, options, ports);
737
+ const plan = await planAppPluginShare(root, home, name, {
738
+ ...options,
739
+ visibility: confirmed.visibility,
740
+ ...confirmed.license === void 0 ? {} : { license: confirmed.license },
741
+ ...confirmed.registry === true ? { registry: true } : {}
742
+ }, ports);
600
743
  if (!samePlan(plan, confirmed)) throw new Error(`The share changed since you confirmed it (${plan.owner}/${plan.repo} v${plan.version}); nothing was sent. Look at it again.`);
601
744
  const dir = join(pluginPackagesOf(home), name);
602
745
  if (plan.released !== void 0 && await bumpPackageVersion(dir) !== plan.version) throw new Error(`${name}: the next version is not v${plan.version}; nothing was sent`);
@@ -606,19 +749,22 @@ async function shareAppPlugin(root, home, name, confirmed, options, ports) {
606
749
  visibility: plan.visibility
607
750
  }, {
608
751
  ...ports,
752
+ host: listedOnlyWhenAsked(ports.host, plan.registry === true),
609
753
  store: new PluginStore(storeRootOf(home))
610
754
  });
611
755
  if (result.status === "refused") throw new Error(result.reason);
612
756
  await recordShare(join(home, "shared-plugins.json"), name, {
613
757
  url: result.url,
614
- version: result.version
758
+ version: result.version,
759
+ ...plan.registry === true ? { registry: true } : {}
615
760
  });
616
761
  return {
617
762
  url: result.url,
618
763
  version: result.version,
619
764
  owner: result.owner,
620
765
  repo: result.repo,
621
- tag: result.tag
766
+ tag: result.tag,
767
+ ...plan.registry === true ? { registry: true } : {}
622
768
  };
623
769
  }
624
770
  //#endregion
@@ -667,6 +813,581 @@ function appFallbackTarget(appBase, url, headers) {
667
813
  return fromAppPage(appBase, url, headers) ? appUrlUnderBase(appBase, url) : void 0;
668
814
  }
669
815
  //#endregion
816
+ //#region src/graph-contract.ts
817
+ /**
818
+ * The plugin graph's wire types: what the frame's Host answers and what the browser draws (Settings > Plugins > Graph). Ported from cordis-plugin-graph
819
+ * (MIT, github.com/cordisplugins/cordis-plugin-graph, commit e9bf6b5, `src/inspect.ts`), with two additions the original did not have: a node says where its
820
+ * code is (`source`), and the Host keeps a numbered list of fiber lifecycle events (`GraphEvent`) so the browser hears a change instead of asking again.
821
+ * No Node or browser import: both sides read this file.
822
+ */
823
+ /** The whole graph of the Host's Cordis context, now. */
824
+ const FRAME_GRAPH_PATH = `${FRAME_API_PREFIX}/graph`;
825
+ /** The fiber events after `?after=<seq>`: answered at once when there are some, else when the next one happens (or after about 20 s with none). */
826
+ const FRAME_GRAPH_EVENTS_PATH = `${FRAME_API_PREFIX}/graph/events`;
827
+ //#endregion
828
+ //#region src/plain.ts
829
+ /** A failure whose message is already for the person; a route answers it as it is. */
830
+ var PlainError = class extends Error {
831
+ plain;
832
+ constructor(plain) {
833
+ super(plain.say);
834
+ this.plain = plain;
835
+ this.name = "PlainError";
836
+ }
837
+ };
838
+ const KEEP_HERE = "Keeping the plugin on this computer still works.";
839
+ const GITHUB_MISSING = {
840
+ status: "missing",
841
+ say: `Sharing needs a free helper program from GitHub, and it is not installed on this computer. Install it from cli.github.com, then sign in once. ${KEEP_HERE}`,
842
+ link: "https://cli.github.com"
843
+ };
844
+ const GITHUB_SIGNED_OUT = {
845
+ status: "signed-out",
846
+ say: `To share, connect your GitHub account once. ${KEEP_HERE}`,
847
+ command: "gh auth login"
848
+ };
849
+ /** What a failed tool call says about the person's setup: the helper is not installed, or it is not signed in. */
850
+ function githubProblemOf(message) {
851
+ if (/is not available here/iu.test(message)) return "missing";
852
+ if (/auth login|not logged in|credential|HTTP 401|authentication/iu.test(message)) return "signed-out";
853
+ }
854
+ /** Read whether sharing to GitHub can work: ask who is signed in. `login` is the host's own check (it throws a tool message when it cannot). */
855
+ function githubReadiness(login) {
856
+ try {
857
+ const account = login().trim();
858
+ return account === "" ? GITHUB_SIGNED_OUT : {
859
+ status: "ready",
860
+ account
861
+ };
862
+ } catch (cause) {
863
+ const problem = githubProblemOf(cause instanceof Error ? cause.message : String(cause));
864
+ if (problem === "missing") return GITHUB_MISSING;
865
+ if (problem === "signed-out") return GITHUB_SIGNED_OUT;
866
+ return {
867
+ status: "unavailable",
868
+ say: "GitHub did not answer. Check your internet connection and try again."
869
+ };
870
+ }
871
+ }
872
+ /** A share that could not be planned or sent, in words a person can act on. */
873
+ function plainShareProblem(cause) {
874
+ const message = cause instanceof Error ? cause.message : String(cause);
875
+ const setup = githubProblemOf(message);
876
+ if (setup === "missing") return /\bgit is not available/iu.test(message) ? {
877
+ say: `Sharing needs a free program called git, and it is not installed on this computer. Install it from git-scm.com and try again. ${KEEP_HERE}`,
878
+ details: message
879
+ } : {
880
+ say: GITHUB_MISSING.status === "missing" ? GITHUB_MISSING.say : "",
881
+ details: message
882
+ };
883
+ if (setup === "signed-out") return {
884
+ say: "GitHub is not connected. Press Connect GitHub, then try again. Nothing was sent.",
885
+ details: message
886
+ };
887
+ if (/changed since you confirmed/iu.test(message)) return {
888
+ say: "Something changed while you were deciding, so nothing was sent. Please try again.",
889
+ details: message
890
+ };
891
+ if (/secret|password|token|private key|credential/iu.test(message)) return {
892
+ say: "This plugin contains something that looks like a password or a key, so it was not shared. Remove it from the plugin and try again.",
893
+ details: message
894
+ };
895
+ if (/already (released|exists)|released once/iu.test(message)) return {
896
+ say: "This version is already shared. Change the plugin, then share it again to send the next version.",
897
+ details: message
898
+ };
899
+ if (/could not resolve host|network|timed out|ENOTFOUND|ECONN/iu.test(message)) return {
900
+ say: "GitHub could not be reached. Check your internet connection and try again. Nothing was sent.",
901
+ details: message
902
+ };
903
+ return {
904
+ say: "The plugin could not be shared. Nothing was sent.",
905
+ details: message
906
+ };
907
+ }
908
+ /** Why a plugin could not be added to the app, by the kind of refusal the app's pull gives (`plugins/plugin-share/pull-check.ts`). */
909
+ function plainPullRefusal(refusal, reason, next) {
910
+ const details = [reason, next].filter((part) => part !== "").join(" - ");
911
+ return {
912
+ say: (() => {
913
+ switch (refusal) {
914
+ case "source": return "That address is not one this app understands.";
915
+ case "fetch": return "The plugin could not be downloaded. Check your internet connection and that it is still public, then try again.";
916
+ case "name": return "This plugin's name does not fit in this app, so it was not added.";
917
+ case "digest": return "The downloaded file is not the one its author published, so nothing was added.";
918
+ case "portability": return "This plugin only works on some kinds of computer, so it was not added.";
919
+ case "dependencies": return "This plugin needs extra software installed first, so it was not added.";
920
+ case "entry": return "This plugin has no starting file this app can use, so it was not added.";
921
+ case "inject":
922
+ case "missing-service": return "This plugin needs parts that this app does not have, so it cannot work here. Nothing was added.";
923
+ case "folder-exists": return "You already have a different plugin with this name. Remove it first if you want this one. Nothing was changed.";
924
+ case "install": return "The plugin did not start, so nothing was changed.";
925
+ default: return "The plugin could not be added. Nothing was changed.";
926
+ }
927
+ })(),
928
+ ...details === "" ? {} : { details }
929
+ };
930
+ }
931
+ //#endregion
932
+ //#region src/graph-inspect.ts
933
+ const MAX_FIBERS = 4096;
934
+ const MAX_LABEL = 400;
935
+ const PHASE = {
936
+ 0: "pending",
937
+ 1: "loading",
938
+ 2: "active",
939
+ 3: "failed",
940
+ 4: "disposed",
941
+ 5: "unloading"
942
+ };
943
+ const clamp = (value) => value.length > MAX_LABEL ? `${value.slice(0, MAX_LABEL)}…` : value;
944
+ const phaseOf = (fiber) => PHASE[fiber.state] ?? "pending";
945
+ /** Every live fiber reachable from the context root, root first, uid-ascending. */
946
+ function collectFibers(ctx) {
947
+ const found = /* @__PURE__ */ new Set([ctx.root.fiber]);
948
+ for (const runtime of ctx.root.registry.values()) for (const fiber of runtime.fibers) if (fiber.uid !== null) found.add(fiber);
949
+ const result = [...found].sort((a, b) => (a.uid ?? 0) - (b.uid ?? 0));
950
+ if (result.length > MAX_FIBERS) throw new Error("the context has more fibers than the graph shows");
951
+ return result;
952
+ }
953
+ /** Live service implementations in the root reflect store, keyed off `impl.fiber.uid`, so a wrapped fiber never mis-attributes a provider. */
954
+ function liveServices(ctx) {
955
+ const store = ctx.root.reflect.store;
956
+ return Reflect.ownKeys(store).map((key) => store[key]).filter((impl) => impl != null && typeof impl.name === "string" && impl.fiber != null && impl.fiber.uid != null);
957
+ }
958
+ /** The current Cordis graph of `ctx`: every fiber, the disabled Loader rows, and the three kinds of relation. */
959
+ function inspectCordisContext(ctx, plane, sourceOf = () => void 0) {
960
+ const fibers = collectFibers(ctx);
961
+ const providesByUid = /* @__PURE__ */ new Map();
962
+ for (const impl of liveServices(ctx)) {
963
+ const uid = impl.fiber.uid ?? 0;
964
+ const list = providesByUid.get(uid) ?? [];
965
+ list.push(impl.name);
966
+ providesByUid.set(uid, list);
967
+ }
968
+ const loader = ctx.get("loader");
969
+ const uidByEntryId = /* @__PURE__ */ new Map();
970
+ const nodes = [];
971
+ const edges = [];
972
+ const known = /* @__PURE__ */ new Set();
973
+ for (const fiber of fibers) {
974
+ const uid = fiber.uid ?? 0;
975
+ known.add(uid);
976
+ const parent = fiber.parent.fiber;
977
+ const parentUid = parent === fiber ? null : parent.uid ?? null;
978
+ const ownsEntry = fiber.entry !== void 0 && (parent === fiber || parent.entry !== fiber.entry);
979
+ const entryId = ownsEntry ? loader?.locate?.(fiber) ?? null : null;
980
+ if (entryId !== null) uidByEntryId.set(entryId, uid);
981
+ const moduleName = ownsEntry ? fiber.entry?.options.name ?? null : null;
982
+ const source = uid === 0 ? void 0 : sourceOf(moduleName, fiber.name);
983
+ nodes.push({
984
+ uid,
985
+ name: clamp(fiber.name),
986
+ phase: phaseOf(fiber),
987
+ enabled: true,
988
+ moduleName,
989
+ loaderEntryId: entryId,
990
+ provides: [...providesByUid.get(uid) ?? []].sort(),
991
+ effects: fiber.getEffects().map((meta) => clamp(meta.label)),
992
+ ...source === void 0 ? {} : { source }
993
+ });
994
+ if (parentUid !== null && known.has(parentUid)) edges.push({
995
+ kind: "nesting",
996
+ from: uid,
997
+ to: parentUid
998
+ });
999
+ for (const service of Object.keys(fiber.inject).sort()) {
1000
+ const providerUid = (fiber.store?.[service])?.fiber?.uid ?? null;
1001
+ const resolved = providerUid !== null && known.has(providerUid);
1002
+ edges.push({
1003
+ kind: "inject",
1004
+ from: uid,
1005
+ to: resolved ? providerUid : uid,
1006
+ service,
1007
+ resolved
1008
+ });
1009
+ if (resolved && providerUid !== uid) edges.push({
1010
+ kind: "provider",
1011
+ from: providerUid,
1012
+ to: uid,
1013
+ service
1014
+ });
1015
+ }
1016
+ }
1017
+ let synthetic = -1;
1018
+ if (typeof loader?.entries === "function") for (const entry of loader.entries()) {
1019
+ if (entry?.options?.group) continue;
1020
+ const id = typeof entry.id === "string" ? entry.id : null;
1021
+ if (id !== null && uidByEntryId.has(id)) continue;
1022
+ const fiberUid = entry.fiber?.uid ?? null;
1023
+ if (fiberUid !== null && known.has(fiberUid)) continue;
1024
+ const disabled = entry.disabled === true;
1025
+ const moduleName = entry.options?.name ?? null;
1026
+ const source = moduleName === null ? void 0 : sourceOf(moduleName, moduleName);
1027
+ nodes.push({
1028
+ uid: fiberUid ?? synthetic--,
1029
+ name: clamp(moduleName ?? id ?? "unknown"),
1030
+ phase: disabled ? "disabled" : entry.fiber ? phaseOf(entry.fiber) : "pending",
1031
+ enabled: !disabled,
1032
+ moduleName,
1033
+ loaderEntryId: id,
1034
+ provides: [],
1035
+ effects: [],
1036
+ ...source === void 0 ? {} : { source }
1037
+ });
1038
+ }
1039
+ return {
1040
+ capturedAt: (/* @__PURE__ */ new Date()).toISOString(),
1041
+ plane,
1042
+ nodes,
1043
+ edges
1044
+ };
1045
+ }
1046
+ //#endregion
1047
+ //#region src/plugin-graph.ts
1048
+ /**
1049
+ * The plugin graph, Host side: the numbered list of fiber changes the browser listens to, where each plugin's code is, and the port the frame's routes use.
1050
+ * The reading of the context itself is `./graph-inspect.ts` (ported from cordis-plugin-graph, MIT); the recorder and the source finder are new: that plugin
1051
+ * kept a ring of tool calls and had the browser ask for the whole graph every two seconds, while here a fiber's own `internal/status` and `internal/plugin`
1052
+ * events are recorded, and the browser's request waits until one happens.
1053
+ */
1054
+ const MAX_EVENTS = 200;
1055
+ /** How long a request for events waits for one before it answers with none; the browser asks again at once. */
1056
+ const EVENTS_WAIT_MS = 2e4;
1057
+ /** The recent fiber changes, numbered; a request for those after a number waits for the next change when there are none. */
1058
+ var GraphRecorder = class {
1059
+ seq = 0;
1060
+ events = [];
1061
+ waiting = /* @__PURE__ */ new Set();
1062
+ /** The newest event number; 0 before the first. */
1063
+ get head() {
1064
+ return this.seq;
1065
+ }
1066
+ record(event, at = Date.now()) {
1067
+ this.seq += 1;
1068
+ this.events.push({
1069
+ ...event,
1070
+ seq: this.seq,
1071
+ at
1072
+ });
1073
+ if (this.events.length > MAX_EVENTS) this.events.shift();
1074
+ for (const wake of [...this.waiting]) wake();
1075
+ }
1076
+ /** Every recorded event after `after`, oldest first. */
1077
+ since(after) {
1078
+ return {
1079
+ seq: this.seq,
1080
+ events: this.events.filter((event) => event.seq > after)
1081
+ };
1082
+ }
1083
+ /** The events after `after`, as soon as there are some; none when `ms` passes first or `signal` aborts (the browser left). */
1084
+ async wait(after, ms, signal) {
1085
+ if (this.seq > after || ms <= 0 || signal?.aborted === true) return this.since(after);
1086
+ await new Promise((done) => {
1087
+ const finish = () => {
1088
+ clearTimeout(timer);
1089
+ this.waiting.delete(finish);
1090
+ signal?.removeEventListener("abort", finish);
1091
+ done();
1092
+ };
1093
+ const timer = setTimeout(finish, ms);
1094
+ this.waiting.add(finish);
1095
+ signal?.addEventListener("abort", finish, { once: true });
1096
+ });
1097
+ return this.since(after);
1098
+ }
1099
+ /** Wake every waiting request now (the Host is stopping); each answers with what it has. */
1100
+ release() {
1101
+ for (const wake of [...this.waiting]) wake();
1102
+ }
1103
+ };
1104
+ /** Record every fiber of `ctx`'s tree changing: created, removed, or moved to another phase. Returns the stop. */
1105
+ function recordFibers(ctx, recorder) {
1106
+ const root = ctx.root;
1107
+ const offPlugin = root.on("internal/plugin", (fiber) => {
1108
+ try {
1109
+ recorder.record({
1110
+ uid: fiber.uid ?? 0,
1111
+ name: clamp(fiber.name),
1112
+ kind: fiber.uid === null ? "removed" : "created"
1113
+ });
1114
+ } catch {}
1115
+ });
1116
+ const offStatus = root.on("internal/status", (fiber, before) => {
1117
+ try {
1118
+ recorder.record({
1119
+ uid: fiber.uid ?? 0,
1120
+ name: clamp(fiber.name),
1121
+ kind: "status",
1122
+ from: PHASE[before] ?? "pending",
1123
+ to: PHASE[fiber.state] ?? "pending"
1124
+ });
1125
+ } catch {}
1126
+ });
1127
+ return () => {
1128
+ offPlugin();
1129
+ offStatus();
1130
+ };
1131
+ }
1132
+ const MAIN_FILES = [
1133
+ "index.ts",
1134
+ "index.mts",
1135
+ "index.js",
1136
+ "index.mjs",
1137
+ "src/index.ts",
1138
+ "src/index.js"
1139
+ ];
1140
+ const FILE_ENDINGS = [
1141
+ "",
1142
+ ".ts",
1143
+ ".mts",
1144
+ ".tsx",
1145
+ ".js",
1146
+ ".mjs",
1147
+ ".cjs"
1148
+ ];
1149
+ const isFile = (path) => {
1150
+ try {
1151
+ return statSync(path).isFile();
1152
+ } catch {
1153
+ return false;
1154
+ }
1155
+ };
1156
+ const isDirectory = (path) => {
1157
+ try {
1158
+ return statSync(path).isDirectory();
1159
+ } catch {
1160
+ return false;
1161
+ }
1162
+ };
1163
+ /** The main file of a plugin folder: the manifest's `main` when it names one, else the first index file. */
1164
+ function mainOfFolder(folder) {
1165
+ try {
1166
+ const manifest = JSON.parse(readFileSync(join(folder, "plugin.json"), "utf8"));
1167
+ if (typeof manifest.main === "string" && isFile(join(folder, manifest.main))) return join(folder, manifest.main);
1168
+ } catch {}
1169
+ return MAIN_FILES.map((name) => join(folder, name)).find(isFile);
1170
+ }
1171
+ /** The file a path names: the file itself, the file with an ending, or the main file of the folder. */
1172
+ function fileOf(path) {
1173
+ if (isDirectory(path)) return mainOfFolder(path);
1174
+ return FILE_ENDINGS.map((ending) => path + ending).find(isFile);
1175
+ }
1176
+ /** The folder of the package a file belongs to: the nearest parent with a package.json, else the file's own folder. */
1177
+ function packageFolderOf(file) {
1178
+ let dir = dirname(file);
1179
+ for (;;) {
1180
+ if (existsSync(join(dir, "package.json"))) return dir;
1181
+ const parent = dirname(dir);
1182
+ if (parent === dir) return dirname(file);
1183
+ dir = parent;
1184
+ }
1185
+ }
1186
+ /**
1187
+ * Find where a Loader entry's code is. In the order the app itself finds it: a folder of the app's `plugins/` named like the row, then a path from the app's
1188
+ * folder (`./src/frame.ts`), then a package the app or the frame (for the DSH packages, which the frame's own install carries) can resolve.
1189
+ */
1190
+ function sourceFinder(appRoot) {
1191
+ const root = (() => {
1192
+ try {
1193
+ return realpathSync(appRoot);
1194
+ } catch {
1195
+ return resolve(appRoot);
1196
+ }
1197
+ })();
1198
+ const fromApp = createRequire(join(root, "package.json"));
1199
+ const fromFrame = createRequire(import.meta.url);
1200
+ const cache = /* @__PURE__ */ new Map();
1201
+ const describe = (file, folder) => {
1202
+ const real = (() => {
1203
+ try {
1204
+ return realpathSync(file);
1205
+ } catch {
1206
+ return file;
1207
+ }
1208
+ })();
1209
+ const realFolder = (() => {
1210
+ try {
1211
+ return realpathSync(folder);
1212
+ } catch {
1213
+ return folder;
1214
+ }
1215
+ })();
1216
+ const inside = relative(root, real);
1217
+ return {
1218
+ file: real,
1219
+ folder: realFolder,
1220
+ ...inside !== "" && !inside.startsWith("..") && !isAbsolute(inside) && !inside.split(sep).includes("node_modules") ? { inApp: inside.split(sep).join("/") } : {}
1221
+ };
1222
+ };
1223
+ const find = (moduleName) => {
1224
+ if (moduleName.startsWith("file:")) moduleName = moduleName.slice(5);
1225
+ if (isAbsolute(moduleName) || moduleName.startsWith("./") || moduleName.startsWith("../")) {
1226
+ const file = fileOf(isAbsolute(moduleName) ? moduleName : resolve(root, moduleName));
1227
+ if (file === void 0) return void 0;
1228
+ const base = isAbsolute(moduleName) ? moduleName : resolve(root, moduleName);
1229
+ return describe(file, isDirectory(base) ? base : dirname(file));
1230
+ }
1231
+ const local = join(root, "plugins", moduleName);
1232
+ if (isDirectory(local)) {
1233
+ const file = mainOfFolder(local);
1234
+ if (file !== void 0) return describe(file, local);
1235
+ }
1236
+ for (const requireFrom of [fromApp, fromFrame]) try {
1237
+ const file = requireFrom.resolve(moduleName);
1238
+ return describe(file, packageFolderOf(file));
1239
+ } catch {}
1240
+ };
1241
+ return (moduleName, name) => {
1242
+ for (const candidate of [moduleName, name]) {
1243
+ if (candidate === null || candidate === "" || candidate === "root") continue;
1244
+ if (!cache.has(candidate)) cache.set(candidate, find(candidate));
1245
+ const found = cache.get(candidate);
1246
+ if (found !== void 0) return found;
1247
+ }
1248
+ };
1249
+ }
1250
+ /** The graph of the Host's context, with its recorder started. `stop` ends the recording and answers every waiting request. */
1251
+ function createGraphPort(ctx, appRoot) {
1252
+ const recorder = new GraphRecorder();
1253
+ const stopRecording = recordFibers(ctx, recorder);
1254
+ const sourceOf = sourceFinder(appRoot);
1255
+ return {
1256
+ port: {
1257
+ read: () => {
1258
+ const seq = recorder.head;
1259
+ return {
1260
+ snapshot: inspectCordisContext(ctx, "host", sourceOf),
1261
+ seq
1262
+ };
1263
+ },
1264
+ events: (after, signal) => recorder.wait(after, EVENTS_WAIT_MS, signal)
1265
+ },
1266
+ stop: () => {
1267
+ stopRecording();
1268
+ recorder.release();
1269
+ }
1270
+ };
1271
+ }
1272
+ //#endregion
1273
+ //#region src/registry.ts
1274
+ const REGISTRY_INDEX_URL = "https://cordisplugins.github.io/registry/index.json";
1275
+ /** What the person is told when the registry cannot be read. */
1276
+ const OFFLINE = "The registry could not be reached. Check your internet connection and try again.";
1277
+ const BUSY = "The registry is busy right now. Try again in a few minutes.";
1278
+ const CHANGED = "The registry answered in a way this app does not understand. Try again later.";
1279
+ const SOURCE = /\bgithub:([A-Za-z0-9][A-Za-z0-9-]*)\/([A-Za-z0-9][A-Za-z0-9._-]*)@([0-9][0-9A-Za-z.+-]*)/u;
1280
+ /** A plugin's folder name: the name without its scope, lower case (`@owner/notes` is `notes`). */
1281
+ const bareName = (name) => (name.includes("/") ? name.slice(name.lastIndexOf("/") + 1) : name).toLowerCase();
1282
+ /** `owner/repo` of a `github:` source, lower case; undefined for any other source. */
1283
+ function repoOfSource(source) {
1284
+ const match = SOURCE.exec(source);
1285
+ return match === null ? void 0 : `${match[1] ?? ""}/${match[2] ?? ""}`.toLowerCase();
1286
+ }
1287
+ function isRecord$1(value) {
1288
+ return value !== null && typeof value === "object" && !Array.isArray(value);
1289
+ }
1290
+ /**
1291
+ * The entries a Blends app can pull: the ones the index gives a version and a pull line (a plugin whose code is only a folder of another
1292
+ * repository has none). @throws when the index is not formatVersion 1.
1293
+ */
1294
+ function registryEntries(index, marks) {
1295
+ if (!isRecord$1(index) || index.formatVersion !== 1 || !Array.isArray(index.entries)) throw new Error("registry: not a version 1 index");
1296
+ const entries = [];
1297
+ for (const entry of index.entries) {
1298
+ if (!isRecord$1(entry)) continue;
1299
+ const { name, description, repo, version, published, compatibility, acrylPull } = entry;
1300
+ if (typeof name !== "string" || typeof repo !== "string" || typeof version !== "string" || typeof acrylPull !== "string") continue;
1301
+ const source = SOURCE.exec(acrylPull)?.[0];
1302
+ const where = /^https:\/\/github\.com\/([^/]+)\/([^/#?]+)/u.exec(repo);
1303
+ if (source === void 0 || where === null) continue;
1304
+ const owner = where[1] ?? "";
1305
+ const repository = repoOfSource(source);
1306
+ entries.push({
1307
+ name,
1308
+ description: typeof description === "string" ? description : "",
1309
+ owner,
1310
+ url: `https://github.com/${owner}/${where[2] ?? ""}`,
1311
+ version,
1312
+ ...typeof published === "string" && /^\d{4}-\d{2}-\d{2}$/u.test(published) ? { published } : {},
1313
+ compatibility: typeof compatibility === "string" ? compatibility : "DSH stock",
1314
+ source,
1315
+ installed: marks.names.has(bareName(name)) || repository !== void 0 && marks.repos.has(repository),
1316
+ mine: marks.accounts.has(owner.toLowerCase())
1317
+ });
1318
+ }
1319
+ return entries.sort((a, b) => Number(b.mine) - Number(a.mine) || (b.published ?? "").localeCompare(a.published ?? "") || a.name.localeCompare(b.name));
1320
+ }
1321
+ /** The raw index, read once in a while: a fresh copy within `ttlMs`, else a new read, else the copy read before with the time it was read. */
1322
+ function createRegistryReader(fetcher, options = {}) {
1323
+ const ttl = options.ttlMs ?? 3e5;
1324
+ const timeout = options.timeoutMs ?? 1e4;
1325
+ const now = options.now ?? Date.now;
1326
+ let kept;
1327
+ return async () => {
1328
+ if (kept !== void 0 && now() - kept.at < ttl) return {
1329
+ index: kept.index,
1330
+ readAt: new Date(kept.at).toISOString()
1331
+ };
1332
+ const abort = new AbortController();
1333
+ const timer = setTimeout(() => {
1334
+ abort.abort();
1335
+ }, timeout);
1336
+ let failure = OFFLINE;
1337
+ try {
1338
+ const response = await fetcher(REGISTRY_INDEX_URL, {
1339
+ signal: abort.signal,
1340
+ headers: { Accept: "application/json" }
1341
+ });
1342
+ if (response.ok) {
1343
+ const index = await response.json();
1344
+ kept = {
1345
+ index,
1346
+ at: now()
1347
+ };
1348
+ return {
1349
+ index,
1350
+ readAt: new Date(kept.at).toISOString()
1351
+ };
1352
+ }
1353
+ failure = response.status === 403 || response.status === 429 ? BUSY : response.status >= 500 ? OFFLINE : CHANGED;
1354
+ } catch (cause) {
1355
+ failure = cause instanceof SyntaxError ? CHANGED : OFFLINE;
1356
+ } finally {
1357
+ clearTimeout(timer);
1358
+ }
1359
+ return kept === void 0 ? { message: failure } : {
1360
+ index: kept.index,
1361
+ readAt: new Date(kept.at).toISOString()
1362
+ };
1363
+ };
1364
+ }
1365
+ /** The registry as the frame shows it, from one read of the index. */
1366
+ async function readRegistryView(read, marks) {
1367
+ const got = await read();
1368
+ if ("message" in got) return {
1369
+ status: "unavailable",
1370
+ message: got.message
1371
+ };
1372
+ try {
1373
+ return {
1374
+ status: "ready",
1375
+ entries: registryEntries(got.index, await marks()),
1376
+ readAt: got.readAt
1377
+ };
1378
+ } catch {
1379
+ return {
1380
+ status: "unavailable",
1381
+ message: CHANGED
1382
+ };
1383
+ }
1384
+ }
1385
+ /** The running app's `pluginShare`, read at each call (the app's rows come and go with a reload); undefined when the app has none. */
1386
+ function pluginShareOf(service) {
1387
+ const share = service();
1388
+ return typeof share?.pull === "function" && typeof share.list === "function" ? share : void 0;
1389
+ }
1390
+ //#endregion
670
1391
  //#region src/auto-save.ts
671
1392
  /**
672
1393
  * The frame's auto-save: when the chat's agent finishes a turn that changed the app's files, the Host makes a save point (a version) by itself and
@@ -1293,11 +2014,19 @@ function ghApiWrites(args) {
1293
2014
  }
1294
2015
  /** A rehearsal that sends nothing: `git push --dry-run` (or `-n`), `npm publish --dry-run`. */
1295
2016
  const rehearses = (args, short) => args.some((word) => word === "--dry-run" || short !== void 0 && word === short);
2017
+ /** The app's share command told to send (`--confirm`), through a package manager's `run share` or `node plugins/save/share-cli.ts`. Without `--confirm` it only shows the plan. */
2018
+ function sharesConfirmed(name, args) {
2019
+ if (!args.some((word) => word === "--confirm" || word.startsWith("--confirm="))) return false;
2020
+ if (args.some((word) => /(?:^|[\\/])share-cli\.[cm]?[jt]s$/u.test(word))) return true;
2021
+ const plain = args.filter((word) => !word.startsWith("-"));
2022
+ return PACKAGE_MANAGERS.has(name) && (plain[0] === "share" || plain[0] === "run" && plain[1] === "share");
2023
+ }
1296
2024
  /** What one simple command sends out, as the person would name it; undefined when it sends nothing. */
1297
2025
  function outwardOf(words) {
1298
2026
  const [first, ...args] = fromProgram(words);
1299
2027
  if (first === void 0) return void 0;
1300
2028
  const name = program(first);
2029
+ if (sharesConfirmed(name, args)) return "share the app";
1301
2030
  if (name === "git") return gitSubcommand(args) === "push" && !rehearses(args, "-n") ? "git push" : void 0;
1302
2031
  if (name === "gh") {
1303
2032
  const [group, verb] = args.filter((word) => !word.startsWith("-"));
@@ -2279,6 +3008,157 @@ async function upstreamHead(git, root) {
2279
3008
  }
2280
3009
  }
2281
3010
  //#endregion
3011
+ //#region src/github-connect.ts
3012
+ /**
3013
+ * Connect GitHub from the app, for a person who has never opened a terminal: GitHub's own browser sign-in (`gh auth login --web`), started by a button.
3014
+ *
3015
+ * gh prints a one-time code and the address github.com/login/device, then waits until the person enters the code there and says yes. This module runs
3016
+ * that one gh process, reads the code from what it prints, and reports where the sign-in is. No password or token passes through the app: the person
3017
+ * signs in on github.com, and gh keeps its credential where it always does. When the sign-in succeeded, `gh auth setup-git` lets git push over HTTPS
3018
+ * with the same account, which a share needs.
3019
+ *
3020
+ * One sign-in at a time. The owner (the frame's Host) disposes it with the plugin, which ends a sign-in still waiting.
3021
+ */
3022
+ const DEVICE_URL = "https://github.com/login/device";
3023
+ const CODE = /\b([A-Z0-9]{4}-[A-Z0-9]{4})\b/u;
3024
+ const URL_IN_TEXT = /https:\/\/github\.com\/login\/device\b/u;
3025
+ /** How long a code stays usable on GitHub's side (15 minutes); after that this gives up and the person starts again. */
3026
+ const GIVE_UP_MS = 9e5;
3027
+ const GITHUB_CONNECT_MISSING = "Connecting needs a free helper program from GitHub, and it is not installed on this computer. Install it from cli.github.com, then try again.";
3028
+ /** The gh this computer has, without a terminal: no prompts, no browser opened by gh itself (the page offers the link). */
3029
+ function githubConnectPorts() {
3030
+ const env = {
3031
+ ...process.env,
3032
+ GH_BROWSER: "true",
3033
+ GH_PROMPT_DISABLED: "1",
3034
+ GIT_TERMINAL_PROMPT: "0"
3035
+ };
3036
+ return {
3037
+ startLogin: () => {
3038
+ if (spawnSync("gh", ["--version"], {
3039
+ env,
3040
+ encoding: "utf8"
3041
+ }).error !== void 0) return void 0;
3042
+ return spawn("gh", [
3043
+ "auth",
3044
+ "login",
3045
+ "--hostname",
3046
+ "github.com",
3047
+ "--git-protocol",
3048
+ "https",
3049
+ "--web",
3050
+ "--skip-ssh-key"
3051
+ ], {
3052
+ env,
3053
+ stdio: [
3054
+ "pipe",
3055
+ "pipe",
3056
+ "pipe"
3057
+ ]
3058
+ });
3059
+ },
3060
+ run: (args) => {
3061
+ const result = spawnSync("gh", [...args], {
3062
+ env,
3063
+ encoding: "utf8"
3064
+ });
3065
+ return result.error !== void 0 ? 1 : result.status ?? 1;
3066
+ }
3067
+ };
3068
+ }
3069
+ var GithubConnect = class {
3070
+ ports;
3071
+ giveUpMs;
3072
+ current = { status: "idle" };
3073
+ child;
3074
+ timer;
3075
+ disposed = false;
3076
+ constructor(ports, giveUpMs = GIVE_UP_MS) {
3077
+ this.ports = ports;
3078
+ this.giveUpMs = giveUpMs;
3079
+ }
3080
+ state() {
3081
+ return this.current;
3082
+ }
3083
+ /**
3084
+ * Start a sign-in, or return the one already waiting. Resolves when the code is known (or the start failed), which is well before the person
3085
+ * finishes on github.com; ask `state()` for the rest.
3086
+ */
3087
+ async start() {
3088
+ if (this.disposed) return this.current;
3089
+ if (this.child !== void 0) return this.waitForCode();
3090
+ const child = this.ports.startLogin();
3091
+ if (child === void 0) {
3092
+ this.current = {
3093
+ status: "failed",
3094
+ say: GITHUB_CONNECT_MISSING
3095
+ };
3096
+ return this.current;
3097
+ }
3098
+ this.child = child;
3099
+ this.current = { status: "starting" };
3100
+ let said = "";
3101
+ const read = (chunk) => {
3102
+ said += String(chunk);
3103
+ if (this.current.status !== "starting") return;
3104
+ const code = CODE.exec(said)?.[1];
3105
+ if (code !== void 0) this.current = {
3106
+ status: "code",
3107
+ code,
3108
+ url: URL_IN_TEXT.exec(said)?.[0] ?? DEVICE_URL
3109
+ };
3110
+ };
3111
+ child.stdout?.on("data", read);
3112
+ child.stderr?.on("data", read);
3113
+ child.stdin?.on("error", () => {});
3114
+ child.stdin?.write("\n");
3115
+ child.on("error", (cause) => this.finish({
3116
+ status: "failed",
3117
+ say: GITHUB_CONNECT_MISSING,
3118
+ details: cause.message
3119
+ }));
3120
+ child.on("exit", (status) => {
3121
+ if (status === 0) {
3122
+ this.ports.run(["auth", "setup-git"]);
3123
+ this.finish({ status: "connected" });
3124
+ } else if (this.current.status !== "failed") this.finish({
3125
+ status: "failed",
3126
+ say: "GitHub did not finish connecting. Press Connect GitHub to try again.",
3127
+ details: said.trim().split("\n").at(-1) ?? ""
3128
+ });
3129
+ });
3130
+ this.timer = setTimeout(() => {
3131
+ this.finish({
3132
+ status: "failed",
3133
+ say: "The code ran out before GitHub was connected. Press Connect GitHub to get a new one."
3134
+ });
3135
+ }, this.giveUpMs);
3136
+ return this.waitForCode();
3137
+ }
3138
+ /** End a waiting sign-in (the person closed the chooser, or the plugin unloads). Nothing on GitHub changes. */
3139
+ cancel() {
3140
+ if (this.child === void 0) return;
3141
+ this.finish({ status: "idle" });
3142
+ }
3143
+ dispose() {
3144
+ this.disposed = true;
3145
+ this.cancel();
3146
+ }
3147
+ finish(next) {
3148
+ if (this.timer !== void 0) clearTimeout(this.timer);
3149
+ this.timer = void 0;
3150
+ const child = this.child;
3151
+ this.child = void 0;
3152
+ if (child !== void 0 && child.exitCode === null && child.signalCode === null) child.kill();
3153
+ this.current = next;
3154
+ }
3155
+ /** The code usually arrives within a second; give up waiting for it after a few, and let the page ask again. */
3156
+ async waitForCode() {
3157
+ for (let waited = 0; waited < 5e3 && this.current.status === "starting"; waited += 50) await new Promise((resolve) => setTimeout(resolve, 50));
3158
+ return this.current;
3159
+ }
3160
+ };
3161
+ //#endregion
2282
3162
  //#region src/app-snapshot.ts
2283
3163
  /**
2284
3164
  * The app's snapshot verbs as the frame's service `appSnapshot`: every version the frame saves (Save point, the auto-save) is captured first, so
@@ -2456,6 +3336,15 @@ async function readAppName(root) {
2456
3336
  } catch {}
2457
3337
  return basename(root);
2458
3338
  }
3339
+ /** The only address a page may ask to add: a released plugin of a GitHub account, by version (never a local file or another URL). */
3340
+ const REGISTRY_SOURCE = /^github:[A-Za-z0-9][A-Za-z0-9-]*\/[A-Za-z0-9][A-Za-z0-9._-]*@[0-9][0-9A-Za-z.+-]*$/u;
3341
+ /** What a failed route answers: the plain sentence, and for a developer the tool's own text (the page shows it behind "Details"). */
3342
+ function plainBody(plain) {
3343
+ return {
3344
+ ...error(plain.say),
3345
+ ...plain.details === void 0 ? {} : { details: plain.details }
3346
+ };
3347
+ }
2459
3348
  function parseSwitch(body) {
2460
3349
  if (body === null || typeof body !== "object") return void 0;
2461
3350
  const { kind, name, on } = body;
@@ -2518,7 +3407,7 @@ function parseBranchName(body) {
2518
3407
  const problem = branchNameProblem(name);
2519
3408
  return problem === void 0 ? { name } : { problem };
2520
3409
  }
2521
- function frameRoutes({ state, report = () => {}, plugins, feedback, branches, branchChats, chatSaves, shared, realChats, gitSync, snapshot, appReload, selection }) {
3410
+ function frameRoutes({ state, report = () => {}, plugins, graph, feedback, branches, branchChats, chatSaves, shared, realChats, gitSync, snapshot, appReload, selection }) {
2522
3411
  const app = new Acryl();
2523
3412
  if (appReload !== void 0) app.get(FRAME_APP_PATH, ownPage, async (c) => {
2524
3413
  const after = Number(c.req.query("after"));
@@ -2679,6 +3568,21 @@ function frameRoutes({ state, report = () => {}, plugins, feedback, branches, br
2679
3568
  }
2680
3569
  });
2681
3570
  }
3571
+ if (graph !== void 0) {
3572
+ app.get(FRAME_GRAPH_PATH, ownPage, async (c) => {
3573
+ try {
3574
+ return c.json(graph.read());
3575
+ } catch (cause) {
3576
+ report(cause);
3577
+ return c.json(error("the plugin graph could not be read"), 500);
3578
+ }
3579
+ });
3580
+ app.get(FRAME_GRAPH_EVENTS_PATH, ownPage, async (c) => {
3581
+ const after = Number(c.req.query("after") ?? "0");
3582
+ if (!Number.isInteger(after) || after < 0) return c.json(error("name the last event number you have"), 400);
3583
+ return c.json(await graph.events(after, c.req.raw.signal));
3584
+ });
3585
+ }
2682
3586
  if (plugins !== void 0) {
2683
3587
  app.get(FRAME_PLUGINS_PATH, ownPage, async (c) => {
2684
3588
  try {
@@ -2705,10 +3609,26 @@ function frameRoutes({ state, report = () => {}, plugins, feedback, branches, br
2705
3609
  const name = pluginName(body === INVALID_JSON || body === null || typeof body !== "object" ? void 0 : body);
2706
3610
  if (name === void 0) return c.json(error("name one local plugin"), 400);
2707
3611
  try {
2708
- return c.json(await plugins.planShare(name));
3612
+ const asked = body.visibility;
3613
+ const listed = body.registry === true;
3614
+ return c.json(await plugins.planShare(name, listed ? "public" : asked === "public" || asked === "private" ? asked : void 0, listed));
2709
3615
  } catch (cause) {
2710
3616
  report(cause);
2711
- return c.json(error(cause instanceof Error ? cause.message : "the share could not be planned"), 409);
3617
+ return c.json(plainBody(plainShareProblem(cause)), 409);
3618
+ }
3619
+ });
3620
+ app.post(FRAME_PLUGINS_SAVE_PATH, ownPage, jsonBody(), async (c) => {
3621
+ const body = await readJson(c);
3622
+ const name = pluginName(body === INVALID_JSON || body === null || typeof body !== "object" ? void 0 : body);
3623
+ if (name === void 0) return c.json(error("name one local plugin"), 400);
3624
+ try {
3625
+ return c.json(await plugins.save(name));
3626
+ } catch (cause) {
3627
+ report(cause);
3628
+ return c.json(plainBody({
3629
+ say: "The plugin could not be kept on this computer. Nothing was changed.",
3630
+ details: cause instanceof Error ? cause.message : String(cause)
3631
+ }), 409);
2712
3632
  }
2713
3633
  });
2714
3634
  app.post(FRAME_PLUGINS_SHARE_PATH, ownPage, jsonBody(), async (c) => {
@@ -2726,7 +3646,44 @@ function frameRoutes({ state, report = () => {}, plugins, feedback, branches, br
2726
3646
  return c.json(await plugins.share(name, confirmed));
2727
3647
  } catch (cause) {
2728
3648
  report(cause);
2729
- return c.json(error(cause instanceof Error ? cause.message : "the plugin could not be shared"), 409);
3649
+ return c.json(plainBody(plainShareProblem(cause)), 409);
3650
+ }
3651
+ });
3652
+ app.get(FRAME_PLUGINS_GITHUB_PATH, ownPage, async (c) => {
3653
+ try {
3654
+ return c.json(await plugins.github());
3655
+ } catch (cause) {
3656
+ report(cause);
3657
+ return c.json(error("GitHub could not be checked"), 500);
3658
+ }
3659
+ });
3660
+ app.post(FRAME_PLUGINS_GITHUB_CONNECT_PATH, ownPage, async (c) => c.json(await plugins.connect.start()));
3661
+ app.get(FRAME_PLUGINS_GITHUB_CONNECT_PATH, ownPage, (c) => c.json(plugins.connect.state()));
3662
+ app.delete(FRAME_PLUGINS_GITHUB_CONNECT_PATH, ownPage, (c) => {
3663
+ plugins.connect.cancel();
3664
+ return c.json(plugins.connect.state());
3665
+ });
3666
+ app.get(FRAME_PLUGINS_REGISTRY_PATH, ownPage, async (c) => {
3667
+ try {
3668
+ return c.json(await plugins.registry());
3669
+ } catch (cause) {
3670
+ report(cause);
3671
+ return c.json(error("The registry could not be read."), 500);
3672
+ }
3673
+ });
3674
+ app.post(FRAME_PLUGINS_PULL_PATH, ownPage, jsonBody(), async (c) => {
3675
+ const body = await readJson(c);
3676
+ const source = body === INVALID_JSON || body === null || typeof body !== "object" ? void 0 : body.source;
3677
+ if (typeof source !== "string" || !REGISTRY_SOURCE.test(source)) return c.json(error("That address is not one this app can add a plugin from."), 400);
3678
+ try {
3679
+ return c.json(await plugins.pull(source));
3680
+ } catch (cause) {
3681
+ if (cause instanceof PlainError) return c.json(plainBody(cause.plain), 409);
3682
+ report(cause);
3683
+ return c.json(plainBody({
3684
+ say: "The plugin could not be added. Nothing was changed.",
3685
+ details: cause instanceof Error ? cause.message : String(cause)
3686
+ }), 409);
2730
3687
  }
2731
3688
  });
2732
3689
  }
@@ -2848,7 +3805,8 @@ function hostIdentity(instance) {
2848
3805
  }
2849
3806
  function apply(ctx, config = {}) {
2850
3807
  const appPage = typeof config.appPage === "string" && config.appPage.startsWith("/") ? config.appPage : void 0;
2851
- const shareOwner = typeof config.shareOwner === "string" && /^[A-Za-z0-9-]+$/u.test(config.shareOwner) ? config.shareOwner : void 0;
3808
+ const wantedOwner = config.shareOwner ?? process.env.ACRYLBLENDS_SHARE_OWNER;
3809
+ const shareOwner = typeof wantedOwner === "string" && /^[A-Za-z0-9-]+$/u.test(wantedOwner) ? wantedOwner : void 0;
2852
3810
  const shareTo = shareOwner === void 0 ? {} : { owner: shareOwner };
2853
3811
  const root = ctx.appInstance.root;
2854
3812
  if (typeof root !== "string") throw new Error("acryl-blends-frame: the app instance has no app folder (root)");
@@ -2915,6 +3873,7 @@ function apply(ctx, config = {}) {
2915
3873
  ...upstream === void 0 ? {} : { upstreamHead: upstream }
2916
3874
  };
2917
3875
  };
3876
+ const graph = createGraphPort(ctx, root);
2918
3877
  const frameRows = () => {
2919
3878
  const loader = ctx.get("loader");
2920
3879
  if (loader === void 0) return [];
@@ -2925,9 +3884,13 @@ function apply(ctx, config = {}) {
2925
3884
  fiberState: entry.fiber?.state
2926
3885
  }));
2927
3886
  };
3887
+ const githubConnect = new GithubConnect(githubConnectPorts());
3888
+ ctx.effect(() => () => {
3889
+ githubConnect.dispose();
3890
+ }, "acryl-blends-frame: connecting GitHub");
2928
3891
  const plugins = {
2929
3892
  read: async () => {
2930
- const [app, frame] = await Promise.all([readAppPlugins(root, git, join(ctx.appInstance.home, "shared-plugins.json"), ghRepositoryCheck), readFramePlugins(root, frameRows())]);
3893
+ const [app, frame] = await Promise.all([readAppPlugins(root, git, join(ctx.appInstance.home, "shared-plugins.json"), ghRepositoryCheck, storeRootOf(ctx.appInstance.home)), readFramePlugins(root, frameRows())]);
2931
3894
  return {
2932
3895
  plugins: app,
2933
3896
  frame
@@ -2939,8 +3902,47 @@ function apply(ctx, config = {}) {
2939
3902
  const entry = loader === void 0 ? void 0 : [...loader.entries()].find((row) => row.options.id === APP_PLUGINS_ROW);
2940
3903
  if (entry?.fiber !== void 0) await entry.fiber.restart();
2941
3904
  },
2942
- planShare: async (name) => planAppPluginShare(root, ctx.appInstance.home, name, shareTo, githubSharePorts()),
2943
- share: async (name, confirmed) => shareAppPlugin(root, ctx.appInstance.home, name, confirmed, shareTo, githubSharePorts())
3905
+ planShare: async (name, visibility, registry) => planAppPluginShare(root, ctx.appInstance.home, name, {
3906
+ ...shareTo,
3907
+ ...visibility === void 0 ? {} : { visibility },
3908
+ ...registry === true ? { registry } : {}
3909
+ }, githubSharePorts()),
3910
+ share: async (name, confirmed) => shareAppPlugin(root, ctx.appInstance.home, name, confirmed, shareTo, githubSharePorts()),
3911
+ save: async (name) => saveAppPlugin(root, ctx.appInstance.home, name),
3912
+ github: async () => githubReadiness(() => githubSharePorts().host.login()),
3913
+ connect: githubConnect,
3914
+ registry: async () => readRegistryView(registryRead, async () => registryMarks()),
3915
+ pull: async (source) => {
3916
+ const share = pluginShareOf(() => ctx.get("pluginShare"));
3917
+ if (share === void 0) throw new PlainError({ say: "This app cannot add plugins: its plugin sharing part is switched off. Switch it on in Settings > Plugins, then try again." });
3918
+ const answer = await share.pull(source);
3919
+ if (!answer.ok) throw new PlainError(plainPullRefusal(answer.refusal, answer.reason, answer.next));
3920
+ return {
3921
+ name: answer.name,
3922
+ version: answer.version,
3923
+ action: answer.action,
3924
+ state: answer.state
3925
+ };
3926
+ }
3927
+ };
3928
+ const registryRead = createRegistryReader((input, init) => fetch(input, init));
3929
+ let signedIn;
3930
+ const registryMarks = async () => {
3931
+ const listed = pluginShareOf(() => ctx.get("pluginShare"))?.list() ?? [];
3932
+ const names = /* @__PURE__ */ new Set([...frameRows().map((row) => bareName(row.name)), ...listed.map((info) => bareName(info.name))]);
3933
+ const repos = new Set(listed.flatMap((info) => info.pulledFrom === void 0 ? [] : [repoOfSource(info.pulledFrom) ?? ""]).filter((repo) => repo !== ""));
3934
+ if (signedIn === void 0 || Date.now() - signedIn.at > 6e4) {
3935
+ const ready = githubReadiness(() => githubSharePorts().host.login());
3936
+ signedIn = {
3937
+ at: Date.now(),
3938
+ account: ready.status === "ready" ? ready.account : void 0
3939
+ };
3940
+ }
3941
+ return {
3942
+ names,
3943
+ repos,
3944
+ accounts: /* @__PURE__ */ new Set([...shareOwner === void 0 ? [] : [shareOwner.toLowerCase()], ...signedIn.account === void 0 ? [] : [signedIn.account.toLowerCase()]])
3945
+ };
2944
3946
  };
2945
3947
  const store = new SaveStore(join(ctx.appInstance.dshHome, "chat-saves.json"), report);
2946
3948
  const versions = new Versions(git);
@@ -3000,6 +4002,7 @@ function apply(ctx, config = {}) {
3000
4002
  ctx.logger.error(`acryl-blends-frame: request failed: ${cause instanceof Error ? cause.message : String(cause)}`);
3001
4003
  },
3002
4004
  plugins,
4005
+ graph: graph.port,
3003
4006
  feedback: feedbackPort(() => {
3004
4007
  return (ctx.get("loader")?.entries().find((row) => row.options.id === APP_PLUGINS_ROW))?.fiber?.ctx?.get("feedback") ?? ctx.get("feedback");
3005
4008
  }),
@@ -3049,6 +4052,7 @@ function apply(ctx, config = {}) {
3049
4052
  ctx.routerHttp.mount(FRAME_API_PREFIX);
3050
4053
  const stopSnapshot = ctx.reflect.provide("appSnapshot", snapshot);
3051
4054
  return () => {
4055
+ graph.stop();
3052
4056
  stopSnapshot();
3053
4057
  stopListening();
3054
4058
  stopGuard();