@acryldev/launcher-desktop 0.1.0 → 0.1.2

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, 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",
@@ -37,6 +41,8 @@ const SURFACES = [
37
41
  const MAKEABLE_SURFACES = ["web", "desktop"];
38
42
  /** A Blend id as `acryl new --from` takes it: it starts with a letter or digit, so it can never read as an option. */
39
43
  const BLEND_ID = /^[a-z0-9][a-z0-9._-]{0,127}$/u;
44
+ /** A Blend released on GitHub, as `--from` takes it (create-acrylblends `github:owner/repo#ref`): what a community Blend is made from. */
45
+ 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
46
  /** 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
47
  const PLUGIN_NAME = /^[a-z0-9][a-z0-9._-]{0,127}$/u;
42
48
  const ACCOUNT_NAME = /^[A-Za-z0-9][A-Za-z0-9-]{0,38}$/u;
@@ -107,13 +113,16 @@ function fileDoor(fetchImpl = (input, init) => fetch(input, init), read = (path)
107
113
  }
108
114
  //#endregion
109
115
  //#region src/registry.ts
116
+ /** 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
117
  const REGISTRY_INDEX = "https://acrylblends.github.io/registry/index.json";
118
+ /** Blends released by people outside the ACRYL project and found on GitHub by the registry's hourly sync (origin `community`, each with its `source`). */
119
+ const REGISTRY_DISCOVERED = "https://acrylblends.github.io/registry/discovered.json";
111
120
  const TIMEOUT_MS = 1e4;
112
121
  var RegistryUnavailable = class extends Error {};
113
122
  const record$1 = (value) => value !== null && typeof value === "object" && !Array.isArray(value) ? value : void 0;
114
123
  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) {
124
+ /** The `entries` of one registry list; `RegistryUnavailable` in words a person can act on. */
125
+ async function entriesOf(fetchImpl, url) {
117
126
  let body;
118
127
  try {
119
128
  const response = await fetchImpl(url, { signal: AbortSignal.timeout(TIMEOUT_MS) });
@@ -125,10 +134,19 @@ async function readBlends(fetchImpl = (input, init) => fetch(input, init), url =
125
134
  }
126
135
  const entries = record$1(body)?.entries;
127
136
  if (!Array.isArray(entries)) throw new RegistryUnavailable("The registry answered, but its list could not be read.");
137
+ return entries;
138
+ }
139
+ /**
140
+ * 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
141
+ * 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.
142
+ */
143
+ async function readBlends(fetchImpl = (input, init) => fetch(input, init), url = REGISTRY_INDEX, discovered = REGISTRY_DISCOVERED) {
128
144
  const blends = [];
129
- for (const raw of entries) {
145
+ const ids = /* @__PURE__ */ new Set();
146
+ for (const raw of await entriesOf(fetchImpl, url)) {
130
147
  const entry = record$1(raw);
131
148
  if (entry === void 0 || entry.runtime !== "acrylblends" || typeof entry.id !== "string" || entry.id === "") continue;
149
+ ids.add(entry.id);
132
150
  blends.push({
133
151
  id: entry.id,
134
152
  name: text$2(entry.name) || entry.id,
@@ -138,6 +156,23 @@ async function readBlends(fetchImpl = (input, init) => fetch(input, init), url =
138
156
  origin: entry.origin === "official" ? "official" : "community"
139
157
  });
140
158
  }
159
+ const community = discovered === void 0 ? [] : await entriesOf(fetchImpl, discovered).catch(() => []);
160
+ for (const raw of community) {
161
+ const entry = record$1(raw);
162
+ if (entry === void 0 || entry.runtime !== "acrylblends" || typeof entry.id !== "string" || entry.id === "" || ids.has(entry.id)) continue;
163
+ const source = text$2(entry.source);
164
+ if (!BLEND_SOURCE.test(source)) continue;
165
+ ids.add(entry.id);
166
+ blends.push({
167
+ id: entry.id,
168
+ name: text$2(entry.name) || entry.id,
169
+ version: text$2(entry.version),
170
+ category: text$2(entry.category),
171
+ description: text$2(entry.description),
172
+ origin: "community",
173
+ source
174
+ });
175
+ }
141
176
  return blends.sort((a, b) => a.name.localeCompare(b.name));
142
177
  }
143
178
  //#endregion
@@ -500,9 +535,30 @@ var LauncherService = class {
500
535
  #failures = /* @__PURE__ */ new Map();
501
536
  #job;
502
537
  #blends;
538
+ #signIn;
539
+ /** 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). */
540
+ #tools = { state: "ready" };
503
541
  constructor(ports) {
504
542
  this.#ports = ports;
505
543
  }
544
+ /** Start fetching what this computer lacks of Node.js and gh; apps wait for it (`#toolsReady`). Called once, when the launcher starts. */
545
+ prepareTools() {
546
+ const prepare = this.#ports.prepareTools;
547
+ if (prepare === void 0) return Promise.resolve();
548
+ this.#tools = { state: "preparing" };
549
+ return prepare().then(() => {
550
+ this.#tools = { state: "ready" };
551
+ }, (cause) => {
552
+ this.#tools = {
553
+ state: "failed",
554
+ reason: cause instanceof Error ? cause.message : String(cause)
555
+ };
556
+ });
557
+ }
558
+ /** Refuse, in words, to start anything while the tools are still being fetched; a failed fetch lets apps try the computer's own tools. */
559
+ #toolsReady() {
560
+ 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.");
561
+ }
506
562
  state() {
507
563
  if (this.#blends === void 0 || Date.now() - this.#blends.at >= BLENDS_FRESH_MS) this.blends().catch(() => void 0);
508
564
  const apps = readApps(this.#ports.home).map((entry) => this.#view(entry));
@@ -563,6 +619,7 @@ var LauncherService = class {
563
619
  * 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
620
  */
565
621
  start(id, surface) {
622
+ this.#toolsReady();
566
623
  const entry = readApps(this.#ports.home).find((app) => app.id === id);
567
624
  if (entry === void 0) throw new LauncherRefusal(`there is no app "${id}" in the list`);
568
625
  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 +697,7 @@ var LauncherService = class {
640
697
  * install). A running app is stopped first and started again after.
641
698
  */
642
699
  update(id) {
700
+ this.#toolsReady();
643
701
  if (this.#job?.status === "running") throw new LauncherRefusal(`${this.#job.name} is still being worked on: wait for it to finish`);
644
702
  const entry = readApps(this.#ports.home).find((app) => app.id === id);
645
703
  if (entry === void 0) throw new LauncherRefusal(`there is no app "${id}" in the list`);
@@ -706,12 +764,13 @@ var LauncherService = class {
706
764
  * 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
765
  */
708
766
  create(request) {
767
+ this.#toolsReady();
709
768
  if (this.#job?.status === "running") throw new LauncherRefusal(`${this.#job.name} is still being made: wait for it to finish`);
710
769
  const problem = whereProblem(request.where) ?? (APP_NAME.test(request.name) ? void 0 : appNameProblem(request.name, this.#ports));
711
770
  if (problem !== void 0) throw new LauncherRefusal(problem);
712
771
  if (request.starter === void 0 === (request.blend === void 0)) throw new LauncherRefusal("choose a starter or a Blend, not both");
713
772
  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)`);
773
+ 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
774
  if (!MAKEABLE_SURFACES.includes(request.surface)) throw new LauncherRefusal("CLI (TUI) apps are coming: choose Web or Desktop");
716
775
  const folder = join(request.where, request.name);
717
776
  if (this.#ports.exists(folder)) throw new LauncherRefusal(`there is already a folder named ${request.name} in ${request.where}`);
@@ -856,9 +915,15 @@ var LauncherService = class {
856
915
  * The app need not be running. An app made before that command has none, and is told how to get it.
857
916
  */
858
917
  async #shareCommand(request, confirm) {
918
+ this.#toolsReady();
859
919
  const entry = this.#entry(request.id);
860
920
  if (request.owner !== void 0 && !ACCOUNT_NAME.test(request.owner)) throw new LauncherRefusal(`"${request.owner}" is not a GitHub account name`);
861
921
  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.`);
922
+ if (request.visibility !== void 0 && confirm === void 0) try {
923
+ setBlendVisibility(entry.path, request.visibility);
924
+ } catch (cause) {
925
+ throw new LauncherRefusal(`Could not set who may see it: ${cause instanceof Error ? cause.message : String(cause)}`);
926
+ }
862
927
  const args = [
863
928
  SHARE_COMMAND,
864
929
  "--json",
@@ -941,10 +1006,66 @@ var LauncherService = class {
941
1006
  }
942
1007
  #environment() {
943
1008
  const inherited = this.#ports.environment();
944
- return appEnvironment({
1009
+ return appEnvironment(toolsEnv(this.#ports.home, {
945
1010
  ...inherited,
946
- ...modelEnv(this.#ports.home, inherited)
947
- });
1011
+ ...modelEnv(this.#ports.home, inherited),
1012
+ ...githubEnv(this.#ports.home, inherited)
1013
+ }));
1014
+ }
1015
+ /** Who is signed in to GitHub here (the token apps get as GH_TOKEN), never the token. */
1016
+ github() {
1017
+ return {
1018
+ available: githubClientId(this.#ports.environment()) !== void 0,
1019
+ login: readGithub(this.#ports.home)?.login ?? null
1020
+ };
1021
+ }
1022
+ /** Start GitHub's device sign-in: the code for the person; the device code stays here until it is approved, refused or expires. */
1023
+ async githubStart() {
1024
+ const clientId = githubClientId(this.#ports.environment());
1025
+ if (clientId === void 0) throw new LauncherRefusal("this build of Control Center has no GitHub app to sign in with");
1026
+ try {
1027
+ const started = await startGithubSignIn(clientId);
1028
+ this.#signIn = {
1029
+ clientId,
1030
+ deviceCode: started.deviceCode,
1031
+ until: Date.now() + started.expiresIn * 1e3
1032
+ };
1033
+ return {
1034
+ userCode: started.userCode,
1035
+ verificationUri: started.verificationUri,
1036
+ interval: started.interval
1037
+ };
1038
+ } catch (cause) {
1039
+ throw new LauncherRefusal(`GitHub sign-in could not start: ${cause instanceof Error ? cause.message : String(cause)}. Check the network and try again.`);
1040
+ }
1041
+ }
1042
+ /** 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. */
1043
+ async githubPoll() {
1044
+ const signIn = this.#signIn;
1045
+ if (signIn === void 0) return {
1046
+ state: "failed",
1047
+ reason: "no GitHub sign-in is under way: start it again"
1048
+ };
1049
+ if (Date.now() > signIn.until) {
1050
+ this.#signIn = void 0;
1051
+ return {
1052
+ state: "failed",
1053
+ reason: "the code expired: start the sign-in again"
1054
+ };
1055
+ }
1056
+ try {
1057
+ const answer = await pollGithubSignIn(this.#ports.home, signIn.clientId, signIn.deviceCode);
1058
+ if (answer.state !== "pending") this.#signIn = void 0;
1059
+ return answer;
1060
+ } catch {
1061
+ return { state: "pending" };
1062
+ }
1063
+ }
1064
+ /** Forget the GitHub connection on this machine. Apps started from now on no longer get the token. */
1065
+ githubDisconnect() {
1066
+ this.#signIn = void 0;
1067
+ clearGithub(this.#ports.home);
1068
+ return this.github();
948
1069
  }
949
1070
  /**
950
1071
  * 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 +1250,22 @@ function parsePublish(value) {
1129
1250
  }
1130
1251
  function parseSharePlan(value) {
1131
1252
  const body = record(value);
1132
- if (body === void 0 || !onlyKeys(body, ["id", "owner"])) return void 0;
1253
+ if (body === void 0 || !onlyKeys(body, [
1254
+ "id",
1255
+ "owner",
1256
+ "visibility"
1257
+ ])) return void 0;
1133
1258
  const id = text(body.id);
1134
1259
  const owner = optional(body.owner);
1260
+ if (body.visibility !== void 0 && body.visibility !== "private" && body.visibility !== "public") return void 0;
1261
+ const visibility = body.visibility;
1135
1262
  return id === void 0 || owner === null ? void 0 : {
1136
1263
  id,
1137
- ...owner === void 0 ? {} : { owner }
1264
+ ...owner === void 0 ? {} : { owner },
1265
+ ...visibility === void 0 ? {} : { visibility }
1138
1266
  };
1139
1267
  }
1268
+ const nothing = (value) => record(value) !== void 0 && Object.keys(value).length === 0 ? {} : void 0;
1140
1269
  function parseShare(value) {
1141
1270
  const body = record(value);
1142
1271
  if (body === void 0) return void 0;
@@ -1217,6 +1346,10 @@ function launcherRoutes(service, report = () => {}) {
1217
1346
  ask(LAUNCHER_PUBLISH_PATH, parsePublish, (request) => service.publish(request), "publish a plugin");
1218
1347
  ask(LAUNCHER_SHARE_PLAN_PATH, parseSharePlan, (request) => service.sharePlan(request), "plan a share");
1219
1348
  ask(LAUNCHER_SHARE_PATH, parseShare, (request) => service.share(request), "share an app");
1349
+ ask(LAUNCHER_GITHUB_PATH, nothing, () => Promise.resolve(service.github()), "read the GitHub connection");
1350
+ ask(LAUNCHER_GITHUB_START_PATH, nothing, () => service.githubStart(), "start the GitHub sign-in");
1351
+ ask(LAUNCHER_GITHUB_POLL_PATH, nothing, () => service.githubPoll(), "check the GitHub sign-in");
1352
+ ask(LAUNCHER_GITHUB_DISCONNECT_PATH, nothing, () => Promise.resolve(service.githubDisconnect()), "disconnect GitHub");
1220
1353
  /** A change: same-origin JSON in, the new state out. A refusal is 409 with its reason; anything else is reported and 500. */
1221
1354
  const change = (path, parse, run, operation) => {
1222
1355
  app.post(path, ownPage, jsonContent, jsonBody(), async (c) => {
@@ -1285,8 +1418,10 @@ function apply(ctx) {
1285
1418
  mkdirSync(path, { recursive: true });
1286
1419
  },
1287
1420
  blends: () => readBlends(),
1288
- door: fileDoor()
1421
+ door: fileDoor(),
1422
+ prepareTools: () => prepareTools(home, process.env)
1289
1423
  });
1424
+ service.prepareTools();
1290
1425
  const report = (operation, cause) => {
1291
1426
  ctx.logger.error(`@acryldev/launcher-desktop: failed to ${operation}: ${cause instanceof Error ? cause.message : String(cause)}`);
1292
1427
  };
@@ -1300,6 +1435,6 @@ function apply(ctx) {
1300
1435
  ctx.routerHttp.mount(LAUNCHER_API_PREFIX);
1301
1436
  }
1302
1437
  //#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 };
1438
+ 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, apply, inject, name };
1304
1439
 
1305
1440
  //# sourceMappingURL=index.js.map