@fungi.computer/oyster 0.13.0 → 0.13.1

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.
@@ -8,21 +8,26 @@
8
8
  // npx @fungi.computer/oyster try [directory] [--port 8787] [--no-open] [--verbose]
9
9
  //
10
10
  // Output goes through Lantern, the shared Fungi terminal kit: a wordmark, one
11
- // spinner per real step, a success box and a next step for every failure. It
11
+ // progress log per real step, a success box and a next step for every failure. It
12
12
  // is quiet by default; install and server output go to files under .oyster/
13
13
  // and --verbose streams them instead. Piped output or CI gets plain lines.
14
- import { spawn, spawnSync } from "node:child_process";
14
+ import { spawn } from "node:child_process";
15
15
  import { randomBytes } from "node:crypto";
16
+ import { addAbortListener } from "node:events";
17
+ import { finished } from "node:stream/promises";
18
+ import { runGit } from "../build/local-build.js";
19
+ import { CleanupError, stopProcessGroup, awaitCleanup, } from "../build/process-group.js";
20
+ import { InstallationObservationError } from "../installation-client.js";
16
21
  import { createWriteStream } from "node:fs";
17
- import { copyFile, mkdir, readdir, readFile, stat, writeFile, } from "node:fs/promises";
22
+ import { copyFile, mkdir, mkdtemp, rename, readdir, rm, readFile, stat, writeFile, } from "node:fs/promises";
18
23
  import { createServer } from "node:net";
19
- import { basename, delimiter, join, resolve } from "node:path";
24
+ import { basename, dirname, delimiter, join, resolve } from "node:path";
20
25
  import process from "node:process";
21
26
  import { parseArgs } from "node:util";
22
27
  import { Cli } from "@fungi.computer/lantern";
23
28
  import * as z from "zod";
24
29
  import { installHelloApp } from "./hello-app.js";
25
- import { installLocalDesktop, isInstalled } from "./local-desktop.js";
30
+ import { installLocalDesktop, localDesktopState, } from "./local-desktop.js";
26
31
  import { startSignInLink } from "./sign-in-link.js";
27
32
  export const tryUsage = "Usage: oyster try [directory] [--port 8787] [--no-open] [--verbose] [--package <npm spec>]";
28
33
  const tryHelp = `${tryUsage}
@@ -49,6 +54,33 @@ const ownerKeyFile = ".oyster-owner";
49
54
  const logFile = join(".oyster", "wrangler.log");
50
55
  const installLogFile = join(".oyster", "install.log");
51
56
  const command = "npx @fungi.computer/oyster try";
57
+ const pendingInstall = join(".oyster", "install.pending");
58
+ const quote = (value) => "'" + value.replaceAll("'", "'\"'\"'") + "'";
59
+ const retryCommand = (directory, port) => `${command} ${quote(directory)} --port ${String(port)}`;
60
+ /** Lantern owns rendering; Oyster owns the measured phase and its lifetime. */
61
+ async function timedTask(ui, label, work) {
62
+ const started = performance.now();
63
+ const elapsed = () => `${((performance.now() - started) / 1000).toFixed(1)}s`;
64
+ try {
65
+ return await ui.task(label, async (update) => {
66
+ const timer = setInterval(() => {
67
+ update(`${label} · ${elapsed()} elapsed`);
68
+ }, 5000);
69
+ try {
70
+ const result = await work();
71
+ update(`${label} · done in ${elapsed()}`);
72
+ return result;
73
+ }
74
+ finally {
75
+ clearInterval(timer);
76
+ }
77
+ });
78
+ }
79
+ catch (cause) {
80
+ ui.step(`${label} · ${cause instanceof Error && cause.name === "AbortError" ? "stopped" : "failed"} after ${elapsed()}`);
81
+ throw cause;
82
+ }
83
+ }
52
84
  /** A failure that knows the exact next step; the command shows both. */
53
85
  class TryError extends Error {
54
86
  title;
@@ -61,8 +93,8 @@ class TryError extends Error {
61
93
  }
62
94
  }
63
95
  /**
64
- * Streaming logs and a redrawing spinner cannot share a terminal, so
65
- * --verbose prints plain lines instead of spinners.
96
+ * Streaming logs and interactive progress cannot share a terminal, so
97
+ * --verbose prints plain lines.
66
98
  */
67
99
  export function createTryCli(args) {
68
100
  return args.includes("--verbose")
@@ -150,15 +182,34 @@ const pnpmWorkspace = `allowBuilds:
150
182
  async function exists(path) {
151
183
  return stat(path).then(() => true, () => false);
152
184
  }
153
- async function scaffold(directory, own, spec, manager) {
154
- await mkdir(directory, { recursive: true });
155
- const examples = join(import.meta.dirname, "../../examples/standalone");
156
- for (const name of ["worker.ts", "wrangler.jsonc"])
157
- await copyFile(join(examples, name), join(directory, name));
158
- await writeFile(join(directory, "package.json"), projectManifest(own, spec));
159
- if (manager === "pnpm")
160
- await writeFile(join(directory, "pnpm-workspace.yaml"), pnpmWorkspace);
161
- await writeFile(join(directory, ".gitignore"), ".oyster/\n.wrangler/\nnode_modules/\n.oyster-owner\n");
185
+ async function scaffold(directory, own, spec, manager, signal) {
186
+ signal.throwIfAborted();
187
+ await mkdir(dirname(directory), { recursive: true });
188
+ const stage = await mkdtemp(join(dirname(directory), ".oyster-try-"));
189
+ try {
190
+ const examples = join(import.meta.dirname, "../../examples/standalone");
191
+ for (const name of ["worker.ts", "wrangler.jsonc"]) {
192
+ signal.throwIfAborted();
193
+ await copyFile(join(examples, name), join(stage, name));
194
+ }
195
+ await writeFile(join(stage, "package.json"), projectManifest(own, spec));
196
+ if (manager === "pnpm")
197
+ await writeFile(join(stage, "pnpm-workspace.yaml"), pnpmWorkspace);
198
+ await writeFile(join(stage, ".gitignore"), ".oyster/\n.wrangler/\nnode_modules/\n.oyster-owner\n");
199
+ const key = Array.from(randomBytes(24), (byte) => byte.toString(16).padStart(2, "0")).join("");
200
+ await writeFile(join(stage, ownerKeyFile), key + "\n", {
201
+ mode: 0o600,
202
+ flag: "wx",
203
+ });
204
+ signal.throwIfAborted();
205
+ await rename(stage, directory);
206
+ return key;
207
+ }
208
+ finally {
209
+ await rm(stage, { recursive: true, force: true }).catch((cause) => {
210
+ throw new CleanupError("Project staging cleanup failed", { cause });
211
+ });
212
+ }
162
213
  }
163
214
  /** Write a child's output to a log file, and also to stderr when verbose. */
164
215
  function captureOutput(child, log, verbose) {
@@ -168,30 +219,57 @@ function captureOutput(child, log, verbose) {
168
219
  stream?.pipe(process.stderr, { end: false });
169
220
  }
170
221
  }
171
- async function runInstall(directory, manager, verbose) {
222
+ async function runInstall(directory, manager, verbose, signal) {
223
+ signal.throwIfAborted();
172
224
  await mkdir(join(directory, ".oyster"), { recursive: true });
225
+ signal.throwIfAborted();
173
226
  const log = createWriteStream(join(directory, installLogFile));
227
+ const logClosed = Promise.allSettled([finished(log)]);
228
+ let child;
229
+ let listener;
230
+ let stopping;
231
+ const beginStop = () => (stopping ??= Promise.allSettled([
232
+ child === undefined ? Promise.resolve() : stopProcessGroup(child),
233
+ ]));
234
+ const stop = () => awaitCleanup(beginStop());
174
235
  try {
175
- await new Promise((done, fail) => {
176
- const child = spawn(manager, ["install"], {
177
- cwd: directory,
178
- stdio: ["ignore", "pipe", "pipe"],
179
- shell: process.platform === "win32",
180
- });
181
- captureOutput(child, log, verbose);
182
- child.on("error", (cause) => {
183
- fail(new Error(`Could not run ${manager} install: ${cause.message}`));
236
+ child = spawn(manager, ["install"], {
237
+ cwd: directory,
238
+ detached: process.platform !== "win32",
239
+ signal,
240
+ stdio: ["ignore", "pipe", "pipe"],
241
+ shell: process.platform === "win32",
242
+ });
243
+ captureOutput(child, log, verbose);
244
+ const closed = new Promise((done, fail) => {
245
+ let failure;
246
+ child?.once("error", (cause) => {
247
+ failure = cause;
184
248
  });
185
- child.on("close", (code) => {
186
- if (code === 0)
249
+ child?.once("close", (code) => {
250
+ if (failure !== undefined)
251
+ fail(failure);
252
+ else if (code === 0)
187
253
  done();
188
254
  else
189
255
  fail(new Error(`${manager} install failed (exit ${String(code)}).`));
190
256
  });
191
257
  });
258
+ listener = addAbortListener(signal, () => {
259
+ void beginStop();
260
+ });
261
+ try {
262
+ await closed;
263
+ }
264
+ finally {
265
+ await stop();
266
+ }
267
+ signal.throwIfAborted();
192
268
  }
193
269
  finally {
270
+ listener?.[Symbol.dispose]();
194
271
  log.end();
272
+ await awaitCleanup(logClosed);
195
273
  }
196
274
  }
197
275
  function portFree(port) {
@@ -207,37 +285,34 @@ function portFree(port) {
207
285
  });
208
286
  });
209
287
  }
210
- async function waitUntilReady(url, child, timeoutMs) {
288
+ async function waitUntilReady(url, child, timeoutMs, signal) {
211
289
  const deadline = Date.now() + timeoutMs;
212
- while (Date.now() < deadline) {
213
- if (child.exitCode !== null)
214
- return false;
290
+ const stopped = () => child.exitCode !== null || child.signalCode !== null;
291
+ while (Date.now() < deadline && !signal.aborted) {
292
+ if (stopped())
293
+ return "exited";
215
294
  const answered = await fetch(`${url}/login`, {
216
- signal: AbortSignal.timeout(2_000),
295
+ signal: AbortSignal.any([signal, AbortSignal.timeout(2_000)]),
217
296
  }).then((response) => response.status < 500, () => false);
297
+ if (stopped())
298
+ return "exited";
218
299
  if (answered)
219
- return true;
300
+ return "ready";
220
301
  await new Promise((wake) => setTimeout(wake, 500));
221
302
  }
222
- return false;
223
- }
224
- async function tail(path) {
225
- try {
226
- const text = await readFile(path, "utf8");
227
- return text.trim().split("\n").slice(-15).join("\n");
228
- }
229
- catch {
230
- return "(no log was written)";
231
- }
303
+ return signal.aborted ? "exited" : "timeout";
232
304
  }
233
305
  function startWrangler(input) {
234
306
  return (async () => {
307
+ input.signal.throwIfAborted();
235
308
  const wrangler = join(input.directory, "node_modules", "wrangler", "bin", "wrangler.js");
236
309
  if (!(await exists(wrangler)))
237
- throw new TryError(`wrangler is not installed in ${input.directory}.`, `Run \`npm install\` there, then run \`${command}\` again.`);
310
+ throw new TryError(`wrangler is not installed in ${input.directory}.`, `Run \`npm install\` there, then run \`${retryCommand(input.directory, input.port)}\` again.`);
238
311
  await mkdir(join(input.directory, ".oyster"), { recursive: true });
239
312
  const log = join(input.directory, logFile);
313
+ input.signal.throwIfAborted();
240
314
  const logStream = createWriteStream(log);
315
+ const logClosed = Promise.allSettled([finished(logStream)]);
241
316
  const url = `http://127.0.0.1:${String(input.port)}`;
242
317
  const child = spawn(process.execPath, [
243
318
  wrangler,
@@ -258,52 +333,92 @@ function startWrangler(input) {
258
333
  "OYSTER_ORIGIN:https://oyster.test",
259
334
  ], {
260
335
  cwd: input.directory,
336
+ detached: process.platform !== "win32",
337
+ signal: input.signal,
261
338
  stdio: ["ignore", "pipe", "pipe"],
262
339
  env: { ...process.env, WRANGLER_SEND_METRICS: "false" },
263
340
  });
264
341
  captureOutput(child, logStream, input.verbose);
342
+ const lifetime = new AbortController();
343
+ const spawnError = new Promise((done) => {
344
+ child.once("error", () => {
345
+ done("spawn-error");
346
+ lifetime.abort();
347
+ });
348
+ });
265
349
  const exited = new Promise((done) => {
266
350
  child.on("close", (code) => {
267
- logStream.end();
351
+ lifetime.abort();
268
352
  done(code);
269
353
  });
270
354
  });
271
- const stop = async () => {
272
- if (child.exitCode === null)
273
- child.kill("SIGTERM");
274
- const forced = setTimeout(() => {
275
- child.kill("SIGKILL");
276
- }, 10_000);
277
- await exited;
278
- clearTimeout(forced);
279
- };
280
- if (!(await waitUntilReady(url, child, 120_000))) {
355
+ let stopping;
356
+ const beginStop = () => (stopping ??= Promise.allSettled([
357
+ (async () => {
358
+ try {
359
+ await stopProcessGroup(child);
360
+ await exited;
361
+ }
362
+ finally {
363
+ abortListener[Symbol.dispose]();
364
+ logStream.end();
365
+ await awaitCleanup(logClosed);
366
+ }
367
+ })(),
368
+ ]));
369
+ const stop = () => awaitCleanup(beginStop());
370
+ const abortListener = addAbortListener(input.signal, () => {
371
+ void beginStop();
372
+ });
373
+ try {
374
+ const readiness = await Promise.race([
375
+ waitUntilReady(url, child, 120_000, AbortSignal.any([lifetime.signal, input.signal])),
376
+ spawnError,
377
+ ]);
378
+ input.signal.throwIfAborted();
379
+ if (readiness !== "ready") {
380
+ const diagnostic = readiness === "spawn-error"
381
+ ? "Oyster could not launch its server process."
382
+ : readiness === "exited"
383
+ ? `Oyster stopped before readiness (${child.signalCode === null ? `exit ${String(child.exitCode)}` : `signal ${child.signalCode}`}).`
384
+ : "Oyster did not answer within 120 seconds.";
385
+ await stop();
386
+ throw new TryError(diagnostic, `Read ${log} for the server output.`);
387
+ }
388
+ return { stop, exited };
389
+ }
390
+ catch (cause) {
281
391
  await stop();
282
- throw new TryError("Oyster did not start.", `Read ${log}, or run \`${command} --verbose\` to watch it start. The last lines:\n${await tail(log)}`);
392
+ throw cause;
283
393
  }
284
- return { stop, exited };
285
394
  })();
286
395
  }
287
- function openBrowser(url) {
396
+ function openBrowser(url, failed) {
288
397
  const [command, args] = process.platform === "darwin"
289
398
  ? ["open", [url]]
290
399
  : process.platform === "win32"
291
400
  ? ["cmd", ["/c", "start", "", url]]
292
401
  : ["xdg-open", [url]];
293
402
  const child = spawn(command, args, { stdio: "ignore", detached: true });
294
- child.on("error", () => undefined);
403
+ let reported = false;
404
+ const reportFailure = () => {
405
+ if (reported)
406
+ return;
407
+ reported = true;
408
+ failed();
409
+ };
410
+ child.once("error", reportFailure);
411
+ child.once("close", (code) => {
412
+ if (code !== 0)
413
+ reportFailure();
414
+ });
295
415
  child.unref();
296
416
  }
297
- function untilInterrupted() {
298
- return new Promise((done) => {
299
- const once = () => {
300
- process.off("SIGINT", once);
301
- process.off("SIGTERM", once);
302
- done();
303
- };
304
- process.on("SIGINT", once);
305
- process.on("SIGTERM", once);
306
- });
417
+ function isTryCancellation(cause, signal) {
418
+ return (signal.aborted &&
419
+ (cause === signal.reason ||
420
+ (cause instanceof Error && cause.name === "AbortError") ||
421
+ cause instanceof InstallationObservationError));
307
422
  }
308
423
  const realEffects = {
309
424
  installDependencies: runInstall,
@@ -311,15 +426,18 @@ const realEffects = {
311
426
  installHello: installHelloApp,
312
427
  installDesktop: async ({ directory, ...input }) => {
313
428
  process.env.PATH = `${join(directory, "node_modules", ".bin")}${delimiter}${process.env.PATH ?? ""}`;
314
- if (!(await isInstalled({ ...input, installationId: "tourtois" })))
315
- await installLocalDesktop(input);
429
+ const saved = await localDesktopState(input);
430
+ if (saved !== "missing")
431
+ return saved;
432
+ await installLocalDesktop(input);
433
+ const installed = await localDesktopState(input);
434
+ return installed === "missing" ? "unavailable" : installed;
316
435
  },
317
436
  signInLink: startSignInLink,
318
437
  open: openBrowser,
319
- interrupted: untilInterrupted,
320
438
  portFree,
321
439
  };
322
- export async function tryOyster(args, effects = realEffects, ui = createTryCli(args)) {
440
+ export async function tryOyster(args, effects = realEffects, ui = createTryCli(args), callerSignal) {
323
441
  const { values, positionals } = parseArgs({
324
442
  args: [...args],
325
443
  allowPositionals: true,
@@ -340,66 +458,172 @@ export async function tryOyster(args, effects = realEffects, ui = createTryCli(a
340
458
  if (positionals.length > 1)
341
459
  throw new Error(tryUsage);
342
460
  ui.welcome("Oyster: your own Apps, running on this machine");
343
- const major = Number(process.versions.node.split(".")[0]);
344
- if (major < requiredNodeMajor)
345
- throw new TryError(`Oyster needs Node ${String(requiredNodeMajor)} or newer; this is Node ${process.versions.node}.`, `Install a current Node from https://nodejs.org, then run \`${command}\` again.`);
346
- if (!gitAvailable())
347
- throw new TryError("Oyster builds the Hello App from a git commit, so it needs Git.", `Install Git from https://git-scm.com, then run \`${command}\` again.`);
348
461
  const port = Number(values.port ?? "8787");
349
462
  if (!Number.isInteger(port) || port < 1 || port > 65_535)
350
463
  throw new TryError("--port must be a number from 1 to 65535.", `For example: \`${command} --port 8788\`.`);
351
- const directory = resolve(positionals[0] ??
352
- ((await exists(join(process.cwd(), ownerKeyFile))) ? "." : "my-oyster"));
353
- const keyPath = join(directory, ownerKeyFile);
354
- const fresh = !(await exists(keyPath));
355
- if (fresh) {
356
- const occupied = (await exists(directory))
357
- ? (await readdir(directory)).length > 0
358
- : false;
359
- if (occupied)
360
- throw new TryError(`${directory} already has files and is not an Oyster made by \`oyster try\`.`, `Choose a new directory: \`${command} <directory>\`.`);
361
- }
362
- if (!(await effects.portFree(port)))
363
- throw new TryError(`Port ${String(port)} on 127.0.0.1 is already in use.`, `Stop whatever is using it, or choose another port: \`${command} --port ${String(port + 1)}\`.`);
364
- let key;
365
- if (fresh) {
366
- const manager = detectManager(process.env.npm_config_user_agent);
367
- const own = await ownManifest();
368
- await ui.task(`Creating ${basename(directory)}`, () => scaffold(directory, own, values.package, manager));
369
- await ui
370
- .task(`Installing dependencies with ${manager} (a minute or two)`, () => effects.installDependencies(directory, manager, verbose))
371
- .catch((cause) => {
372
- throw new TryError(cause instanceof Error ? cause.message : String(cause), `Read ${join(directory, installLogFile)} (or add --verbose), delete ${directory}, and run \`${command}\` again.`);
373
- });
374
- key = Array.from(randomBytes(24), (byte) => byte.toString(16).padStart(2, "0")).join("");
375
- await writeFile(keyPath, key + "\n", { mode: 0o600 });
376
- }
377
- else {
378
- key = (await readFile(keyPath, "utf8")).trim();
379
- ui.info(`Restarting the Oyster in ${directory}`);
380
- }
381
- const url = `http://127.0.0.1:${String(port)}`;
382
- const server = await ui.task("Starting Oyster", () => effects.startServer({ directory, port, key, verbose }));
383
- let closeLink = () => undefined;
464
+ let directory = resolve(positionals[0] ?? "my-oyster");
465
+ const retryAtPort = (chosenPort) => retryCommand(directory, chosenPort) +
466
+ (values["no-open"] === true ? " --no-open" : "") +
467
+ (verbose ? " --verbose" : "") +
468
+ (values.package === undefined ? "" : ` --package ${quote(values.package)}`);
469
+ let retry = retryAtPort(port);
470
+ const retryWithLogs = () => retry + (verbose ? "" : " --verbose");
471
+ const cancellation = new AbortController();
472
+ const signal = callerSignal === undefined
473
+ ? cancellation.signal
474
+ : AbortSignal.any([cancellation.signal, callerSignal]);
475
+ const interrupt = () => {
476
+ cancellation.abort();
477
+ };
478
+ process.on("SIGINT", interrupt);
479
+ process.on("SIGTERM", interrupt);
480
+ let acquiredServer;
481
+ let closeLink;
384
482
  try {
385
- await ui.task("Installing the Hello App", () => effects.installHello({ directory, url, key }));
386
- await ui
387
- .task(fresh
388
- ? "Building Tourtois (about 2 min the first time)"
389
- : "Checking Tourtois", () => effects.installDesktop({ directory, url, key }))
390
- .catch((cause) => {
391
- ui.warn(`Tourtois, the desktop, could not be built (${innermostError(cause).message}). Continuing with the Hello App.`, isNetworkFailure(innermostError(cause))
392
- ? `Connect to the internet and run \`${command}\` again from ${directory} to try the desktop again.`
393
- : `Run \`${command} --verbose\` from ${directory} and report this.`);
483
+ if (positionals[0] === undefined &&
484
+ (await exists(join(process.cwd(), ownerKeyFile)))) {
485
+ directory = process.cwd();
486
+ retry = retryAtPort(port);
487
+ }
488
+ signal.throwIfAborted();
489
+ const major = Number(process.versions.node.split(".")[0]);
490
+ if (major < requiredNodeMajor)
491
+ throw new TryError(`Oyster needs Node ${String(requiredNodeMajor)} or newer; this is Node ${process.versions.node}.`, `Install a current Node from https://nodejs.org, then run \`${retry}\` again.`);
492
+ if (!(await gitAvailable(signal)))
493
+ throw new TryError("Oyster builds the Hello App from a git commit, so it needs Git.", `Install Git from https://git-scm.com, then run \`${retry}\` again.`);
494
+ const task = (label, work) => timedTask(ui, label, async () => {
495
+ signal.throwIfAborted();
496
+ const result = await work();
497
+ signal.throwIfAborted();
498
+ return result;
499
+ });
500
+ const keyPath = join(directory, ownerKeyFile);
501
+ const fresh = !(await exists(keyPath));
502
+ if (fresh) {
503
+ const occupied = (await exists(directory))
504
+ ? (await readdir(directory)).length > 0
505
+ : false;
506
+ if (occupied)
507
+ throw new TryError(`${directory} already has files and is not an Oyster made by \`oyster try\`.`, `Choose a new directory: \`${command} <directory>\`.`);
508
+ }
509
+ const available = await effects.portFree(port);
510
+ signal.throwIfAborted();
511
+ if (!available)
512
+ throw new TryError(`Port ${String(port)} on 127.0.0.1 is already in use.`, `Leave that listener running. Choose another port: \`${retryAtPort(port === 65535 ? 8787 : port + 1)}\`.`);
513
+ let key;
514
+ if (fresh) {
515
+ const manager = detectManager(process.env.npm_config_user_agent);
516
+ const own = await ownManifest();
517
+ key = await task(`Creating ${basename(directory)}`, () => scaffold(directory, own, values.package, manager, signal));
518
+ }
519
+ else {
520
+ key = (await readFile(keyPath, "utf8")).trim();
521
+ ui.info(`Restarting the Oyster in ${directory}`);
522
+ }
523
+ if (fresh ||
524
+ (await exists(join(directory, pendingInstall))) ||
525
+ !(await exists(join(directory, "node_modules/wrangler/bin/wrangler.js")))) {
526
+ const manager = (await exists(join(directory, "pnpm-workspace.yaml")))
527
+ ? "pnpm"
528
+ : "npm";
529
+ await mkdir(join(directory, ".oyster"), { recursive: true });
530
+ await writeFile(join(directory, pendingInstall), "Dependencies have not finished installing.\n");
531
+ await task(`Installing dependencies with ${manager}`, () => effects.installDependencies(directory, manager, verbose, signal)).catch((cause) => {
532
+ if (isTryCancellation(cause, signal))
533
+ throw cause;
534
+ throw new TryError(innermostError(cause).message, `Keep this project. Read ${join(directory, installLogFile)}, fix the reported cause, then run \`${retry}\`. Dependencies will be retried; your key and files stay in place.`);
535
+ });
536
+ await rm(join(directory, pendingInstall));
537
+ }
538
+ const url = `http://127.0.0.1:${String(port)}`;
539
+ const server = await task("Starting Oyster", () => (async () => {
540
+ const resource = await effects.startServer({
541
+ directory,
542
+ port,
543
+ key,
544
+ verbose,
545
+ signal,
546
+ });
547
+ acquiredServer = resource;
548
+ return resource;
549
+ })()).catch((cause) => {
550
+ if (isTryCancellation(cause, signal))
551
+ throw cause;
552
+ throw new TryError(cause instanceof TryError ? cause.title : innermostError(cause).message, `Read ${join(directory, logFile)}, then run \`${retryWithLogs()}\`.`);
553
+ });
554
+ let serverExited = false;
555
+ const watchedExit = server.exited.then((code) => {
556
+ serverExited = true;
557
+ return code;
558
+ });
559
+ const assertRunning = () => {
560
+ signal.throwIfAborted();
561
+ if (serverExited)
562
+ throw new TryError("Oyster stopped unexpectedly during setup.", `Read ${join(directory, logFile)}, then run \`${retryWithLogs()}\`.`);
563
+ };
564
+ const setupTask = (label, work) => {
565
+ assertRunning();
566
+ return task(label, async () => {
567
+ const result = await work();
568
+ assertRunning();
569
+ return result;
570
+ });
571
+ };
572
+ await setupTask("Installing the Hello App", async () => {
573
+ const status = await effects.installHello({
574
+ directory,
575
+ url,
576
+ key,
577
+ signal,
578
+ });
579
+ if (status < 200 || status >= 300)
580
+ throw new Error(`Hello App installation returned HTTP ${String(status)}.`);
581
+ }).catch((cause) => {
582
+ if (signal.aborted || cause instanceof CleanupError)
583
+ throw cause;
584
+ assertRunning();
585
+ throw new TryError(innermostError(cause).message, `Keep your Hello source. Run \`${retryWithLogs()}\` and report the install error if it repeats.`);
394
586
  });
395
- const link = await ui.task("Opening your desktop", async () => {
396
- const made = await effects.signInLink({ oysterUrl: url, key });
587
+ const desktop = await setupTask(fresh ? "Building Tourtois" : "Checking Tourtois", () => effects.installDesktop({ directory, url, key, signal })).catch((cause) => {
588
+ if (signal.aborted || cause instanceof CleanupError)
589
+ throw cause;
590
+ assertRunning();
591
+ ui.warn(`Tourtois, the desktop, could not be built (${innermostError(cause).message}). Oyster is available for recovery; the desktop is not ready.`, isNetworkFailure(innermostError(cause))
592
+ ? `Check your connection, stop this trial with Ctrl-C, then run \`${retry}\` to retry the desktop.`
593
+ : `Stop this trial with Ctrl-C, then run \`${retryWithLogs()}\` and report the desktop build error.`);
594
+ return "failed";
595
+ });
596
+ const desktopReady = desktop === "ready";
597
+ const accessUrl = new URL("/api/installations/tourtois/grants", url).href;
598
+ if (desktop !== "ready" && desktop !== "failed")
599
+ ui.warn(desktop === "approval-required"
600
+ ? "Tourtois needs Shell approval."
601
+ : desktop === "disabled"
602
+ ? "Tourtois is disabled."
603
+ : desktop === "deleted"
604
+ ? "Tourtois was removed."
605
+ : "Tourtois is unavailable; its shell entry did not become ready.", desktop === "deleted"
606
+ ? `Sign in at ${url}/login, then open your Hello App at ${url}/apps/hello/. The desktop was not reinstalled.`
607
+ : `Sign in, then review App access at ${accessUrl}. Your saved installation and approvals were not changed.`);
608
+ const link = await setupTask(desktopReady ? "Preparing desktop sign-in" : "Preparing recovery sign-in", async () => {
609
+ const made = await effects.signInLink({ oysterUrl: url, key, signal });
397
610
  closeLink = made.close;
611
+ signal.throwIfAborted();
398
612
  if (values["no-open"] !== true && process.stdout.isTTY)
399
- effects.open(made.url);
613
+ effects.open(made.url, () => {
614
+ if (signal.aborted)
615
+ return;
616
+ ui.warn("The browser did not open.", "Use the sign-in link printed here to open Oyster.");
617
+ });
400
618
  return made;
619
+ }).catch((cause) => {
620
+ if (signal.aborted || cause instanceof CleanupError)
621
+ throw cause;
622
+ assertRunning();
623
+ throw new TryError(innermostError(cause).message, `Sign-in could not be prepared. Run \`${retryWithLogs()}\` again; your saved project is unchanged.`);
401
624
  });
402
- ui.note("Oyster is running", [
625
+ assertRunning();
626
+ ui.note(desktopReady ? "Oyster is running" : "Oyster needs desktop repair", [
403
627
  `Open (works once): ${link.url}`,
404
628
  `Oyster: ${url}`,
405
629
  `Owner key saved in: ${keyPath}`,
@@ -407,21 +631,62 @@ export async function tryOyster(args, effects = realEffects, ui = createTryCli(a
407
631
  `Sign in later by pasting that key at ${url}/login.`,
408
632
  "Press Ctrl-C to stop.",
409
633
  ]);
410
- const outcome = await Promise.race([
411
- effects.interrupted().then(() => "interrupted"),
412
- server.exited.then(() => "exited"),
413
- ]);
414
- if (outcome === "exited")
415
- throw new TryError("Oyster stopped unexpectedly.", `Read ${join(directory, logFile)}, then run \`${command}\` again.`);
634
+ let stopListener;
635
+ try {
636
+ const requested = new Promise((done) => {
637
+ stopListener = addAbortListener(signal, () => {
638
+ done();
639
+ });
640
+ });
641
+ const outcome = await Promise.race([
642
+ requested.then(() => "interrupted"),
643
+ watchedExit.then(() => "exited"),
644
+ ]);
645
+ if (outcome === "exited")
646
+ throw new TryError("Oyster stopped unexpectedly.", `Read ${join(directory, logFile)}, then run \`${retry}\` again.`);
647
+ }
648
+ finally {
649
+ stopListener?.[Symbol.dispose]();
650
+ }
651
+ }
652
+ catch (cause) {
653
+ if (!isTryCancellation(cause, signal))
654
+ throw cause;
655
+ if (cause instanceof InstallationObservationError)
656
+ ui.info(cause.message);
416
657
  }
417
658
  finally {
418
- closeLink();
419
- ui.step("Stopping Oyster");
420
- await server.stop();
659
+ try {
660
+ const cleanup = async () => {
661
+ const outcomes = await Promise.allSettled([
662
+ Promise.resolve().then(() => closeLink?.()),
663
+ Promise.resolve().then(() => acquiredServer?.stop()),
664
+ ]);
665
+ if (outcomes.some((result) => result.status === "rejected"))
666
+ throw new TryError("Oyster cleanup did not complete.", `Check ${join(directory, logFile)} and the local listener before running \`${retry}\` again.`);
667
+ };
668
+ if (acquiredServer !== undefined || closeLink !== undefined)
669
+ await timedTask(ui, "Stopping Oyster", cleanup);
670
+ else
671
+ await cleanup();
672
+ }
673
+ finally {
674
+ process.off("SIGINT", interrupt);
675
+ process.off("SIGTERM", interrupt);
676
+ }
421
677
  }
422
- ui.outro("Stopped. Run the same command again to start it again.");
678
+ ui.outro(`Stopped. Restart with \`${retry}\`.`);
423
679
  }
424
680
  /** Whether `git` is available; Hello App packing reads its commit. */
425
- function gitAvailable() {
426
- return spawnSync("git", ["--version"], { stdio: "ignore" }).status === 0;
681
+ async function gitAvailable(signal) {
682
+ try {
683
+ await runGit(["--version"], process.cwd(), signal, process.env);
684
+ return true;
685
+ }
686
+ catch (cause) {
687
+ if (cause instanceof CleanupError)
688
+ throw cause;
689
+ signal.throwIfAborted();
690
+ return false;
691
+ }
427
692
  }