@acryldev/launcher-desktop 0.1.0 → 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.
package/lib/index.js CHANGED
@@ -1,10 +1,10 @@
1
1
  import { existsSync, mkdirSync, readFileSync } from "node:fs";
2
2
  import { basename, dirname, join } from "node:path";
3
+ import { APP_MARKER, APP_NAME, STARTERS, addApp, appNameProblem, blendOf, blendVersionOf, clearGithub, githubClientId, githubEnv, githubOf, inspectApp, maskKey, modelEnv, pollGithubSignIn, prepareTools, readApps, readGithub, readModelKey, removeApp, setBlendVisibility, startGithubSignIn, toolsEnv, whereProblem } from "@acryldev/launcher";
3
4
  import { defineAcrylTool } from "@acryldev/control";
4
5
  import { Acryl } from "@acryldev/blends";
5
6
  import { error } from "@acryldev/loopback-http";
6
7
  import { INVALID_JSON, jsonBody, jsonContent, ownPage, privateApi, readJson } from "@acryldev/loopback-http/router";
7
- import { APP_MARKER, APP_NAME, STARTERS, addApp, appNameProblem, blendOf, blendVersionOf, inspectApp, maskKey, modelEnv, readApps, readModelKey, removeApp, whereProblem } from "@acryldev/launcher";
8
8
  import { spawn, spawnSync } from "node:child_process";
9
9
  //#region src/contract.ts
10
10
  /** The wire contract of the ACRYL screen's routes (the desktop face of the launcher, spec 050 T012). The screen is the client of these routes. */
@@ -28,6 +28,10 @@ const LAUNCHER_PUBLISH_PLAN_PATH = `${LAUNCHER_API_PREFIX}/publish-plan`;
28
28
  const LAUNCHER_PUBLISH_PATH = `${LAUNCHER_API_PREFIX}/publish`;
29
29
  const LAUNCHER_SHARE_PLAN_PATH = `${LAUNCHER_API_PREFIX}/share-plan`;
30
30
  const LAUNCHER_SHARE_PATH = `${LAUNCHER_API_PREFIX}/share`;
31
+ const LAUNCHER_GITHUB_PATH = `${LAUNCHER_API_PREFIX}/github`;
32
+ const LAUNCHER_GITHUB_START_PATH = `${LAUNCHER_API_PREFIX}/github-start`;
33
+ const LAUNCHER_GITHUB_POLL_PATH = `${LAUNCHER_API_PREFIX}/github-poll`;
34
+ const LAUNCHER_GITHUB_DISCONNECT_PATH = `${LAUNCHER_API_PREFIX}/github-disconnect`;
31
35
  const SURFACES = [
32
36
  "web",
33
37
  "desktop",
@@ -35,8 +39,19 @@ const SURFACES = [
35
39
  ];
36
40
  /** Surfaces a person can choose for a new app today. */
37
41
  const MAKEABLE_SURFACES = ["web", "desktop"];
42
+ /** WebBoxes.ai's New WebBox form, opened with the app's repository filled in (the person signs in and presses Create there). */
43
+ function webboxesDeployUrl(github, name) {
44
+ const url = new URL(WEBBOXES_NEW_BOX);
45
+ url.searchParams.set("github", github);
46
+ url.searchParams.set("name", name.toLowerCase().replace(/[^a-z0-9-]+/gu, "-").replace(/^-+|-+$/gu, "").slice(0, 40));
47
+ return url.href;
48
+ }
38
49
  /** A Blend id as `acryl new --from` takes it: it starts with a letter or digit, so it can never read as an option. */
50
+ /** The New WebBox page of webboxes.ai, which takes `github` and `name` to fill its form. */
51
+ const WEBBOXES_NEW_BOX = "https://webboxes.ai/dashboard/webboxes/new";
39
52
  const BLEND_ID = /^[a-z0-9][a-z0-9._-]{0,127}$/u;
53
+ /** A Blend released on GitHub, as `--from` takes it (create-acrylblends `github:owner/repo#ref`): what a community Blend is made from. */
54
+ const BLEND_SOURCE = /^github:[A-Za-z0-9](?:[A-Za-z0-9-]{0,38})\/[A-Za-z0-9._-]{1,100}(?:#[A-Za-z0-9._/-]{1,100})?$/u;
40
55
  /** A plugin name, a GitHub account and a license id as the door takes them: nothing that could read as an option or a path. */
41
56
  const PLUGIN_NAME = /^[a-z0-9][a-z0-9._-]{0,127}$/u;
42
57
  const ACCOUNT_NAME = /^[A-Za-z0-9][A-Za-z0-9-]{0,38}$/u;
@@ -107,13 +122,16 @@ function fileDoor(fetchImpl = (input, init) => fetch(input, init), read = (path)
107
122
  }
108
123
  //#endregion
109
124
  //#region src/registry.ts
125
+ /** The public Blend registry as the screen's store lists it: only reads (the same index `acryl new --from` and the terminal's "Install a Blend" use). */
110
126
  const REGISTRY_INDEX = "https://acrylblends.github.io/registry/index.json";
127
+ /** Blends released by people outside the ACRYL project and found on GitHub by the registry's hourly sync (origin `community`, each with its `source`). */
128
+ const REGISTRY_DISCOVERED = "https://acrylblends.github.io/registry/discovered.json";
111
129
  const TIMEOUT_MS = 1e4;
112
130
  var RegistryUnavailable = class extends Error {};
113
131
  const record$1 = (value) => value !== null && typeof value === "object" && !Array.isArray(value) ? value : void 0;
114
132
  const text$2 = (value) => typeof value === "string" ? value : "";
115
- /** The Blends an ACRYL app can be made from (registry entries whose runtime is `acrylblends`), by name. Throws `RegistryUnavailable` in words a person can act on. */
116
- async function readBlends(fetchImpl = (input, init) => fetch(input, init), url = REGISTRY_INDEX) {
133
+ /** The `entries` of one registry list; `RegistryUnavailable` in words a person can act on. */
134
+ async function entriesOf(fetchImpl, url) {
117
135
  let body;
118
136
  try {
119
137
  const response = await fetchImpl(url, { signal: AbortSignal.timeout(TIMEOUT_MS) });
@@ -125,10 +143,19 @@ async function readBlends(fetchImpl = (input, init) => fetch(input, init), url =
125
143
  }
126
144
  const entries = record$1(body)?.entries;
127
145
  if (!Array.isArray(entries)) throw new RegistryUnavailable("The registry answered, but its list could not be read.");
146
+ return entries;
147
+ }
148
+ /**
149
+ * The Blends an ACRYL app can be made from (registry entries whose runtime is `acrylblends`), by name: the public registry's, and the community ones
150
+ * the registry found on GitHub (made from their `source`). The community list is optional: when it cannot be read, the store still lists the rest.
151
+ */
152
+ async function readBlends(fetchImpl = (input, init) => fetch(input, init), url = REGISTRY_INDEX, discovered = REGISTRY_DISCOVERED) {
128
153
  const blends = [];
129
- for (const raw of entries) {
154
+ const ids = /* @__PURE__ */ new Set();
155
+ for (const raw of await entriesOf(fetchImpl, url)) {
130
156
  const entry = record$1(raw);
131
157
  if (entry === void 0 || entry.runtime !== "acrylblends" || typeof entry.id !== "string" || entry.id === "") continue;
158
+ ids.add(entry.id);
132
159
  blends.push({
133
160
  id: entry.id,
134
161
  name: text$2(entry.name) || entry.id,
@@ -138,6 +165,23 @@ async function readBlends(fetchImpl = (input, init) => fetch(input, init), url =
138
165
  origin: entry.origin === "official" ? "official" : "community"
139
166
  });
140
167
  }
168
+ const community = discovered === void 0 ? [] : await entriesOf(fetchImpl, discovered).catch(() => []);
169
+ for (const raw of community) {
170
+ const entry = record$1(raw);
171
+ if (entry === void 0 || entry.runtime !== "acrylblends" || typeof entry.id !== "string" || entry.id === "" || ids.has(entry.id)) continue;
172
+ const source = text$2(entry.source);
173
+ if (!BLEND_SOURCE.test(source)) continue;
174
+ ids.add(entry.id);
175
+ blends.push({
176
+ id: entry.id,
177
+ name: text$2(entry.name) || entry.id,
178
+ version: text$2(entry.version),
179
+ category: text$2(entry.category),
180
+ description: text$2(entry.description),
181
+ origin: "community",
182
+ source
183
+ });
184
+ }
141
185
  return blends.sort((a, b) => a.name.localeCompare(b.name));
142
186
  }
143
187
  //#endregion
@@ -500,9 +544,30 @@ var LauncherService = class {
500
544
  #failures = /* @__PURE__ */ new Map();
501
545
  #job;
502
546
  #blends;
547
+ #signIn;
548
+ /** The tools apps need: being fetched (the first start on a computer without them), ready, or not had (apps then try the computer's own). */
549
+ #tools = { state: "ready" };
503
550
  constructor(ports) {
504
551
  this.#ports = ports;
505
552
  }
553
+ /** Start fetching what this computer lacks of Node.js and gh; apps wait for it (`#toolsReady`). Called once, when the launcher starts. */
554
+ prepareTools() {
555
+ const prepare = this.#ports.prepareTools;
556
+ if (prepare === void 0) return Promise.resolve();
557
+ this.#tools = { state: "preparing" };
558
+ return prepare().then(() => {
559
+ this.#tools = { state: "ready" };
560
+ }, (cause) => {
561
+ this.#tools = {
562
+ state: "failed",
563
+ reason: cause instanceof Error ? cause.message : String(cause)
564
+ };
565
+ });
566
+ }
567
+ /** Refuse, in words, to start anything while the tools are still being fetched; a failed fetch lets apps try the computer's own tools. */
568
+ #toolsReady() {
569
+ if (this.#tools.state === "preparing") throw new LauncherRefusal("Getting Node.js and GitHub's tool ready for your apps (only on the first start on this computer, about a minute). Try again in a moment.");
570
+ }
506
571
  state() {
507
572
  if (this.#blends === void 0 || Date.now() - this.#blends.at >= BLENDS_FRESH_MS) this.blends().catch(() => void 0);
508
573
  const apps = readApps(this.#ports.home).map((entry) => this.#view(entry));
@@ -532,6 +597,7 @@ var LauncherService = class {
532
597
  const blend = entry.blend === "" ? blendOf(entry.path) : entry.blend;
533
598
  const version = missing ? "" : blendVersionOf(entry.path);
534
599
  const latest = this.#blends?.list.find((listed) => listed.id === blend)?.version;
600
+ const github = missing ? void 0 : githubOf(entry.path);
535
601
  return {
536
602
  id: entry.id,
537
603
  name: basename(entry.path),
@@ -544,7 +610,8 @@ var LauncherService = class {
544
610
  ...version !== "" && latest !== void 0 && newerVersion(latest, version) ? { update: latest } : {},
545
611
  ...started?.address === void 0 ? {} : { address: started.address },
546
612
  ...started === void 0 || started.address !== void 0 || started.output === "" ? {} : { output: started.output.trimEnd() },
547
- ...failure === void 0 || state !== "stopped" ? {} : { failure }
613
+ ...failure === void 0 || state !== "stopped" ? {} : { failure },
614
+ ...github === void 0 ? {} : { github }
548
615
  };
549
616
  }
550
617
  add(path) {
@@ -563,6 +630,7 @@ var LauncherService = class {
563
630
  * browser), a Desktop app with `npm run desktop`, which starts the same app and opens it in its own window (Electron is fetched the first time).
564
631
  */
565
632
  start(id, surface) {
633
+ this.#toolsReady();
566
634
  const entry = readApps(this.#ports.home).find((app) => app.id === id);
567
635
  if (entry === void 0) throw new LauncherRefusal(`there is no app "${id}" in the list`);
568
636
  if (inspectApp(entry).state === "missing") throw new LauncherRefusal(`the folder ${entry.path} is gone: remove it from the list, or put it back`);
@@ -640,6 +708,7 @@ var LauncherService = class {
640
708
  * install). A running app is stopped first and started again after.
641
709
  */
642
710
  update(id) {
711
+ this.#toolsReady();
643
712
  if (this.#job?.status === "running") throw new LauncherRefusal(`${this.#job.name} is still being worked on: wait for it to finish`);
644
713
  const entry = readApps(this.#ports.home).find((app) => app.id === id);
645
714
  if (entry === void 0) throw new LauncherRefusal(`there is no app "${id}" in the list`);
@@ -706,12 +775,13 @@ var LauncherService = class {
706
775
  * so the process it began is the app's running process: when its blend.yaml appears the app is listed and that process is adopted as the app's.
707
776
  */
708
777
  create(request) {
778
+ this.#toolsReady();
709
779
  if (this.#job?.status === "running") throw new LauncherRefusal(`${this.#job.name} is still being made: wait for it to finish`);
710
780
  const problem = whereProblem(request.where) ?? (APP_NAME.test(request.name) ? void 0 : appNameProblem(request.name, this.#ports));
711
781
  if (problem !== void 0) throw new LauncherRefusal(problem);
712
782
  if (request.starter === void 0 === (request.blend === void 0)) throw new LauncherRefusal("choose a starter or a Blend, not both");
713
783
  if (request.starter !== void 0 && !STARTERS.some((starter) => starter.value === request.starter)) throw new LauncherRefusal(`there is no starter "${request.starter}"`);
714
- if (request.blend !== void 0 && !BLEND_ID.test(request.blend)) throw new LauncherRefusal(`"${request.blend}" is not a Blend id (for example acrylblends.notes)`);
784
+ if (request.blend !== void 0 && !BLEND_ID.test(request.blend) && !BLEND_SOURCE.test(request.blend)) throw new LauncherRefusal(`"${request.blend}" is not a Blend id (for example acrylblends.notes) or a Blend on GitHub (github:owner/repo#tag)`);
715
785
  if (!MAKEABLE_SURFACES.includes(request.surface)) throw new LauncherRefusal("CLI (TUI) apps are coming: choose Web or Desktop");
716
786
  const folder = join(request.where, request.name);
717
787
  if (this.#ports.exists(folder)) throw new LauncherRefusal(`there is already a folder named ${request.name} in ${request.where}`);
@@ -856,9 +926,15 @@ var LauncherService = class {
856
926
  * The app need not be running. An app made before that command has none, and is told how to get it.
857
927
  */
858
928
  async #shareCommand(request, confirm) {
929
+ this.#toolsReady();
859
930
  const entry = this.#entry(request.id);
860
931
  if (request.owner !== void 0 && !ACCOUNT_NAME.test(request.owner)) throw new LauncherRefusal(`"${request.owner}" is not a GitHub account name`);
861
932
  if (!this.#ports.exists(join(entry.path, SHARE_COMMAND))) throw new LauncherRefusal(`This app was made before apps could share themselves. In ${entry.path} run "npx acrylblends@latest upgrade", then try again.`);
933
+ if (request.visibility !== void 0 && confirm === void 0) try {
934
+ setBlendVisibility(entry.path, request.visibility);
935
+ } catch (cause) {
936
+ throw new LauncherRefusal(`Could not set who may see it: ${cause instanceof Error ? cause.message : String(cause)}`);
937
+ }
862
938
  const args = [
863
939
  SHARE_COMMAND,
864
940
  "--json",
@@ -941,10 +1017,66 @@ var LauncherService = class {
941
1017
  }
942
1018
  #environment() {
943
1019
  const inherited = this.#ports.environment();
944
- return appEnvironment({
1020
+ return appEnvironment(toolsEnv(this.#ports.home, {
945
1021
  ...inherited,
946
- ...modelEnv(this.#ports.home, inherited)
947
- });
1022
+ ...modelEnv(this.#ports.home, inherited),
1023
+ ...githubEnv(this.#ports.home, inherited)
1024
+ }));
1025
+ }
1026
+ /** Who is signed in to GitHub here (the token apps get as GH_TOKEN), never the token. */
1027
+ github() {
1028
+ return {
1029
+ available: githubClientId(this.#ports.environment()) !== void 0,
1030
+ login: readGithub(this.#ports.home)?.login ?? null
1031
+ };
1032
+ }
1033
+ /** Start GitHub's device sign-in: the code for the person; the device code stays here until it is approved, refused or expires. */
1034
+ async githubStart() {
1035
+ const clientId = githubClientId(this.#ports.environment());
1036
+ if (clientId === void 0) throw new LauncherRefusal("this build of Control Center has no GitHub app to sign in with");
1037
+ try {
1038
+ const started = await startGithubSignIn(clientId);
1039
+ this.#signIn = {
1040
+ clientId,
1041
+ deviceCode: started.deviceCode,
1042
+ until: Date.now() + started.expiresIn * 1e3
1043
+ };
1044
+ return {
1045
+ userCode: started.userCode,
1046
+ verificationUri: started.verificationUri,
1047
+ interval: started.interval
1048
+ };
1049
+ } catch (cause) {
1050
+ throw new LauncherRefusal(`GitHub sign-in could not start: ${cause instanceof Error ? cause.message : String(cause)}. Check the network and try again.`);
1051
+ }
1052
+ }
1053
+ /** One poll of the sign-in under way: pending, connected (the token is saved and every app started from now on gets it), or failed. */
1054
+ async githubPoll() {
1055
+ const signIn = this.#signIn;
1056
+ if (signIn === void 0) return {
1057
+ state: "failed",
1058
+ reason: "no GitHub sign-in is under way: start it again"
1059
+ };
1060
+ if (Date.now() > signIn.until) {
1061
+ this.#signIn = void 0;
1062
+ return {
1063
+ state: "failed",
1064
+ reason: "the code expired: start the sign-in again"
1065
+ };
1066
+ }
1067
+ try {
1068
+ const answer = await pollGithubSignIn(this.#ports.home, signIn.clientId, signIn.deviceCode);
1069
+ if (answer.state !== "pending") this.#signIn = void 0;
1070
+ return answer;
1071
+ } catch {
1072
+ return { state: "pending" };
1073
+ }
1074
+ }
1075
+ /** Forget the GitHub connection on this machine. Apps started from now on no longer get the token. */
1076
+ githubDisconnect() {
1077
+ this.#signIn = void 0;
1078
+ clearGithub(this.#ports.home);
1079
+ return this.github();
948
1080
  }
949
1081
  /**
950
1082
  * Follow one process. For an app being started, `id` is known; for one being made it is not until the folder has its blend.yaml, which is when the app
@@ -1129,14 +1261,22 @@ function parsePublish(value) {
1129
1261
  }
1130
1262
  function parseSharePlan(value) {
1131
1263
  const body = record(value);
1132
- if (body === void 0 || !onlyKeys(body, ["id", "owner"])) return void 0;
1264
+ if (body === void 0 || !onlyKeys(body, [
1265
+ "id",
1266
+ "owner",
1267
+ "visibility"
1268
+ ])) return void 0;
1133
1269
  const id = text(body.id);
1134
1270
  const owner = optional(body.owner);
1271
+ if (body.visibility !== void 0 && body.visibility !== "private" && body.visibility !== "public") return void 0;
1272
+ const visibility = body.visibility;
1135
1273
  return id === void 0 || owner === null ? void 0 : {
1136
1274
  id,
1137
- ...owner === void 0 ? {} : { owner }
1275
+ ...owner === void 0 ? {} : { owner },
1276
+ ...visibility === void 0 ? {} : { visibility }
1138
1277
  };
1139
1278
  }
1279
+ const nothing = (value) => record(value) !== void 0 && Object.keys(value).length === 0 ? {} : void 0;
1140
1280
  function parseShare(value) {
1141
1281
  const body = record(value);
1142
1282
  if (body === void 0) return void 0;
@@ -1217,6 +1357,10 @@ function launcherRoutes(service, report = () => {}) {
1217
1357
  ask(LAUNCHER_PUBLISH_PATH, parsePublish, (request) => service.publish(request), "publish a plugin");
1218
1358
  ask(LAUNCHER_SHARE_PLAN_PATH, parseSharePlan, (request) => service.sharePlan(request), "plan a share");
1219
1359
  ask(LAUNCHER_SHARE_PATH, parseShare, (request) => service.share(request), "share an app");
1360
+ ask(LAUNCHER_GITHUB_PATH, nothing, () => Promise.resolve(service.github()), "read the GitHub connection");
1361
+ ask(LAUNCHER_GITHUB_START_PATH, nothing, () => service.githubStart(), "start the GitHub sign-in");
1362
+ ask(LAUNCHER_GITHUB_POLL_PATH, nothing, () => service.githubPoll(), "check the GitHub sign-in");
1363
+ ask(LAUNCHER_GITHUB_DISCONNECT_PATH, nothing, () => Promise.resolve(service.githubDisconnect()), "disconnect GitHub");
1220
1364
  /** A change: same-origin JSON in, the new state out. A refusal is 409 with its reason; anything else is reported and 500. */
1221
1365
  const change = (path, parse, run, operation) => {
1222
1366
  app.post(path, ownPage, jsonContent, jsonBody(), async (c) => {
@@ -1285,8 +1429,10 @@ function apply(ctx) {
1285
1429
  mkdirSync(path, { recursive: true });
1286
1430
  },
1287
1431
  blends: () => readBlends(),
1288
- door: fileDoor()
1432
+ door: fileDoor(),
1433
+ prepareTools: () => prepareTools(home, process.env)
1289
1434
  });
1435
+ service.prepareTools();
1290
1436
  const report = (operation, cause) => {
1291
1437
  ctx.logger.error(`@acryldev/launcher-desktop: failed to ${operation}: ${cause instanceof Error ? cause.message : String(cause)}`);
1292
1438
  };
@@ -1300,6 +1446,6 @@ function apply(ctx) {
1300
1446
  ctx.routerHttp.mount(LAUNCHER_API_PREFIX);
1301
1447
  }
1302
1448
  //#endregion
1303
- export { ACCOUNT_NAME, BLEND_ID, LAUNCHER_ADD_PATH, LAUNCHER_ADE_PATH, LAUNCHER_API_PREFIX, LAUNCHER_ASSISTANT_FOLDER_PATH, LAUNCHER_BLENDS_PATH, LAUNCHER_HEALTH_PATH, LAUNCHER_NEW_PATH, LAUNCHER_PLUGINS_PATH, LAUNCHER_PLUGIN_PULL_PATH, LAUNCHER_PUBLISH_PATH, LAUNCHER_PUBLISH_PLAN_PATH, LAUNCHER_REMOVE_PATH, LAUNCHER_SHARE_PATH, LAUNCHER_SHARE_PLAN_PATH, LAUNCHER_START_PATH, LAUNCHER_STATE_PATH, LAUNCHER_STOP_PATH, LAUNCHER_UPDATE_PATH, LICENSE_ID, LauncherRefusal, LauncherService, MAKEABLE_SURFACES, PLUGIN_NAME, SURFACES, apply, inject, name };
1449
+ export { ACCOUNT_NAME, BLEND_ID, BLEND_SOURCE, LAUNCHER_ADD_PATH, LAUNCHER_ADE_PATH, LAUNCHER_API_PREFIX, LAUNCHER_ASSISTANT_FOLDER_PATH, LAUNCHER_BLENDS_PATH, LAUNCHER_GITHUB_DISCONNECT_PATH, LAUNCHER_GITHUB_PATH, LAUNCHER_GITHUB_POLL_PATH, LAUNCHER_GITHUB_START_PATH, LAUNCHER_HEALTH_PATH, LAUNCHER_NEW_PATH, LAUNCHER_PLUGINS_PATH, LAUNCHER_PLUGIN_PULL_PATH, LAUNCHER_PUBLISH_PATH, LAUNCHER_PUBLISH_PLAN_PATH, LAUNCHER_REMOVE_PATH, LAUNCHER_SHARE_PATH, LAUNCHER_SHARE_PLAN_PATH, LAUNCHER_START_PATH, LAUNCHER_STATE_PATH, LAUNCHER_STOP_PATH, LAUNCHER_UPDATE_PATH, LICENSE_ID, LauncherRefusal, LauncherService, MAKEABLE_SURFACES, PLUGIN_NAME, SURFACES, WEBBOXES_NEW_BOX, apply, inject, name, webboxesDeployUrl };
1304
1450
 
1305
1451
  //# sourceMappingURL=index.js.map