@antelopejs/dms 0.18.2 → 0.19.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.
Files changed (77) hide show
  1. package/CHANGELOG.md +86 -0
  2. package/README.md +1 -1
  3. package/bin/control/backend.mjs +1 -1
  4. package/bin/control/base.mjs +24 -9
  5. package/bin/control/base.test.mjs +88 -0
  6. package/bin/control/browser-client.mjs +1 -1
  7. package/bin/control/commands-stack.mjs +8 -6
  8. package/bin/control/commands-verify.mjs +2 -2
  9. package/bin/control/consumer-install.test.mjs +86 -0
  10. package/bin/control/database.mjs +66 -0
  11. package/bin/control/doctor.mjs +7 -0
  12. package/bin/control/frontend-check.mjs +2 -1
  13. package/bin/control/frontend-mode.test.mjs +24 -0
  14. package/bin/control/identity.mjs +45 -16
  15. package/bin/control/journey.mjs +31 -3
  16. package/bin/control/journey.test.mjs +207 -2
  17. package/bin/control/launch.mjs +123 -0
  18. package/bin/control/module-root.mjs +40 -0
  19. package/bin/control/module-root.test.mjs +67 -0
  20. package/bin/control/mongo-server.test.mjs +91 -0
  21. package/bin/control/mongo.mjs +125 -12
  22. package/bin/control/namespaces.test.mjs +33 -0
  23. package/bin/control/options.mjs +1 -0
  24. package/bin/control/pid-reuse.test.mjs +278 -0
  25. package/bin/control/processes.mjs +91 -29
  26. package/bin/control/renderer.test.mjs +1 -1
  27. package/bin/control/run-copy.mjs +6 -1
  28. package/bin/control/run-state.mjs +31 -12
  29. package/bin/control/stack.mjs +86 -173
  30. package/bin/control/verify/behaviour.test.mjs +36 -23
  31. package/bin/control/verify/decode.mjs +1 -0
  32. package/bin/control/verify/emit.mjs +11 -11
  33. package/bin/control/verify/formal.mjs +29 -15
  34. package/bin/control/verify/formal.test.mjs +15 -0
  35. package/bin/control/verify/map.test.mjs +2 -6
  36. package/bin/control/verify/types.mjs +1 -1
  37. package/bin/control/verify/verdict.mjs +4 -4
  38. package/bin/dms-control.mjs +4 -2
  39. package/dist/attachments/save.js +2 -1
  40. package/dist/attachments/save.js.map +1 -1
  41. package/dist/db/models/userNotifications.model.js +14 -8
  42. package/dist/db/models/userNotifications.model.js.map +1 -1
  43. package/dist/pages/public/auth/not-a-member.d.ts +9 -0
  44. package/dist/pages/public/auth/not-a-member.js +27 -0
  45. package/dist/pages/public/auth/not-a-member.js.map +1 -0
  46. package/dist/pages/public/index.d.ts +1 -0
  47. package/dist/pages/public/index.js +1 -0
  48. package/dist/pages/public/index.js.map +1 -1
  49. package/dist/routes/auth/oauth/identity-resolution.js +10 -0
  50. package/dist/routes/auth/oauth/identity-resolution.js.map +1 -1
  51. package/dist/routes/onboarding.js +1 -5
  52. package/dist/routes/onboarding.js.map +1 -1
  53. package/dist/utils/ensure-default-tenant.js +23 -3
  54. package/dist/utils/ensure-default-tenant.js.map +1 -1
  55. package/frontend-vue/layers/dms-auth/app/build/utils/noWorkspaceRoute.ts +19 -0
  56. package/frontend-vue/layers/dms-auth/app/custom-pages/auth/login.vue +4 -6
  57. package/frontend-vue/layers/dms-auth/app/custom-pages/auth/not-a-member.vue +21 -0
  58. package/frontend-vue/layers/dms-auth/app/custom-pages/auth/oauth-complete.vue +2 -4
  59. package/frontend-vue/layers/dms-auth/i18n/locales/auth-en-GB.json +6 -0
  60. package/frontend-vue/layers/dms-auth/i18n/locales/auth-fr-FR.json +6 -0
  61. package/frontend-vue/layers/dms-core/app/types/live.ts +2 -0
  62. package/frontend-vue/layers/dms-ui/app/build/components/containers/drawer/DynamicDrawer.vue +9 -3
  63. package/frontend-vue/layers/dms-ui/app/build/composables/live/currentPageLive.ts +7 -0
  64. package/frontend-vue/layers/dms-ui/app/build/composables/live/pageLiveController.ts +23 -3
  65. package/frontend-vue/layers/dms-ui/app/build/composables/live/usePageDataRefresh.ts +2 -1
  66. package/frontend-vue/layers/dms-ui/app/build/composables/table-view/tableViewRealtime.ts +21 -2
  67. package/frontend-vue/layers/dms-ui/app/build/composables/table-view/useTableLiveHold.ts +4 -3
  68. package/frontend-vue/layers/dms-ui/app/build/utils/accessibilityPreferences.ts +1 -21
  69. package/frontend-vue/layers/dms-ui/app/build/utils/blockPreview.ts +8 -4
  70. package/frontend-vue/layers/dms-ui/app/build/utils/link.ts +35 -7
  71. package/frontend-vue/layers/dms-ui/app/components/chart/ApexChartHost.vue +51 -8
  72. package/frontend-vue/layers/dms-ui/app/components/kpi/KpiCard.vue +3 -0
  73. package/frontend-vue/layers/dms-ui/app/composables/chart/types.ts +2 -0
  74. package/frontend-vue/layers/dms-ui/app/composables/chart/useApexChart.ts +1 -1
  75. package/frontend-vue/layers/dms-ui/app/utils/reducedMotion.ts +22 -0
  76. package/package.json +6 -6
  77. package/skills/dms-pages/REFERENCE.md +1 -1
@@ -13,10 +13,13 @@ import { setTimeout as sleep } from "node:timers/promises";
13
13
  import {
14
14
  assertOwnProc,
15
15
  assertSignalable,
16
+ hasProc,
16
17
  isAlive,
17
18
  isSameProcess,
18
19
  isSignalable,
20
+ startedAs,
19
21
  startTimeOf,
22
+ statOf,
20
23
  } from "./identity.mjs";
21
24
 
22
25
  const POLL_MS = 500;
@@ -244,39 +247,50 @@ function procEntries() {
244
247
  }
245
248
  }
246
249
 
247
- /** @param {string} pid */
248
- function parentOf(pid) {
249
- try {
250
- const stat = readFileSync(`/proc/${pid}/stat`, "utf8");
251
- return Number(stat.slice(stat.lastIndexOf(")") + 2).split(" ")[1]);
252
- } catch {
253
- return -1;
250
+ /** @typedef {Map<number, { parent: number, startTime: number }>} ProcessTable Each process /proc lists, with its parent and start time from one read of its stat */
251
+
252
+ /** @returns {ProcessTable} */
253
+ function processTable() {
254
+ /** @type {ProcessTable} */
255
+ const table = new Map();
256
+ for (const pid of procEntries().map(Number)) {
257
+ const stat = statOf(pid);
258
+ if (stat) table.set(pid, stat);
254
259
  }
260
+ return table;
255
261
  }
256
262
 
257
263
  /**
258
- * Every live descendant of `pids`, read from /proc. Empty where /proc is
259
- * missing. A child that left the process group is found here too.
260
- *
261
- * @param {number[]} pids The roots
262
- * @returns {number[]} The descendants, roots excluded
264
+ * @param {number[]} roots
265
+ * @param {ProcessTable} table
266
+ * @returns {Set<number>} The roots and every process of `table` below one of them
263
267
  */
264
- export function descendantsOf(pids) {
265
- const parents = new Map(
266
- procEntries().map((entry) => [Number(entry), parentOf(entry)]),
267
- );
268
- const found = new Set(pids);
268
+ function familyOf(roots, table) {
269
+ const found = new Set(roots);
269
270
  let grew = true;
270
271
  while (grew) {
271
272
  grew = false;
272
- for (const [pid, parent] of parents) {
273
+ for (const [pid, { parent }] of table) {
273
274
  if (!found.has(pid) && found.has(parent)) {
274
275
  found.add(pid);
275
276
  grew = true;
276
277
  }
277
278
  }
278
279
  }
279
- return [...found].filter((pid) => !pids.includes(pid));
280
+ return found;
281
+ }
282
+
283
+ /**
284
+ * Every live descendant of `pids`, read from /proc. Empty where /proc is
285
+ * missing. A child that left the process group is found here too.
286
+ *
287
+ * @param {number[]} pids The roots
288
+ * @returns {number[]} The descendants, roots excluded
289
+ */
290
+ export function descendantsOf(pids) {
291
+ return [...familyOf(pids, processTable())].filter(
292
+ (pid) => !pids.includes(pid),
293
+ );
280
294
  }
281
295
 
282
296
  /** @param {number} port */
@@ -349,17 +363,64 @@ function signalGroup(pid, signal) {
349
363
  /**
350
364
  * The recorded processes that still run as the run started them, and their
351
365
  * descendants, each with the start time that tells it apart from a later
352
- * process given its pid. A record whose pid another process holds now, or
353
- * whose pid is not a whole number above 1, is left out, so no descendant of
354
- * 0 or 1 is ever looked up.
366
+ * process given its pid. Each process is found and identified by one read
367
+ * of its stat, so a pid another process takes while the tree is read never
368
+ * joins it with the newcomer's start time. Once the tree is read, a process
369
+ * whose start time changed is left out with everything found below it, so
370
+ * a child of a process that took a parent's pid during the walk never joins
371
+ * it. A record whose pid another process holds now, or whose pid is not a
372
+ * whole number above 1, is left out, so no descendant of 0 or 1 is ever
373
+ * looked up.
355
374
  *
356
375
  * @param {RecordedProcess[]} records The recorded processes
357
376
  * @returns {{ pid: number, startTime: number | null }[]} One entry per process
358
377
  */
359
378
  function ownProcesses(records) {
360
- const roots = records.filter(isSameProcess).map((record) => record.pid);
361
- const pids = [...new Set([...roots, ...descendantsOf(roots)])];
362
- return pids.map((pid) => ({ pid, startTime: startTimeOf(pid) }));
379
+ const live = records.filter(isSameProcess);
380
+ if (!hasProc()) {
381
+ return [...new Set(live.map(({ pid }) => pid))].map((pid) => ({
382
+ pid,
383
+ startTime: null,
384
+ }));
385
+ }
386
+ const table = processTable();
387
+ const roots = live
388
+ .filter((record) => {
389
+ const stat = table.get(record.pid);
390
+ return stat !== undefined && startedAs(record, stat.startTime);
391
+ })
392
+ .map(({ pid }) => pid);
393
+ /** @type {ProcessTable} */
394
+ const unchanged = new Map();
395
+ for (const pid of familyOf(roots, table)) {
396
+ const stat = table.get(pid);
397
+ if (stat && startTimeOf(pid) === stat.startTime) unchanged.set(pid, stat);
398
+ }
399
+ const kept = roots.filter((pid) => unchanged.has(pid));
400
+ return [...familyOf(kept, unchanged)].flatMap((pid) => {
401
+ const stat = unchanged.get(pid);
402
+ return stat ? [{ pid, startTime: stat.startTime }] : [];
403
+ });
404
+ }
405
+
406
+ /**
407
+ * Signals the group of `target` only while its pid still names that
408
+ * process, checked by its start time right before the signal. A zombie
409
+ * still has its start time, and its pid cannot be reused until it is
410
+ * reaped, so a group whose leader exited unreaped still gets the signal.
411
+ *
412
+ * @param {{ pid: number, startTime: number | null }} target A process of {@link ownProcesses}
413
+ * @param {NodeJS.Signals} signal The signal
414
+ * @returns {boolean} True when the signal was sent
415
+ */
416
+ function signalIfSame(target, signal) {
417
+ const same =
418
+ target.startTime === null
419
+ ? isSameProcess(target)
420
+ : startTimeOf(target.pid) === target.startTime;
421
+ if (!same) return false;
422
+ signalGroup(target.pid, signal);
423
+ return true;
363
424
  }
364
425
 
365
426
  /**
@@ -387,13 +448,14 @@ function skippedRecords(records) {
387
448
  */
388
449
  export async function stopRecorded(records) {
389
450
  const targets = ownProcesses(records);
390
- for (const target of targets) signalGroup(target.pid, "SIGTERM");
451
+ for (const target of targets) signalIfSame(target, "SIGTERM");
391
452
  const deadline = Date.now() + STOP_GRACE_MS;
392
453
  while (targets.some(isSameProcess) && Date.now() < deadline) {
393
454
  await sleep(READY_POLL_MS);
394
455
  }
395
- const stubborn = targets.filter(isSameProcess);
396
- for (const target of stubborn) signalGroup(target.pid, "SIGKILL");
456
+ const stubborn = targets
457
+ .filter(isSameProcess)
458
+ .filter((target) => signalIfSame(target, "SIGKILL"));
397
459
  return [
398
460
  ...skippedRecords(records),
399
461
  ...targets.map(
@@ -420,7 +482,7 @@ export async function stopRecorded(records) {
420
482
  */
421
483
  export async function killRecorded(records) {
422
484
  const targets = ownProcesses(records);
423
- for (const target of targets) signalGroup(target.pid, "SIGKILL");
485
+ for (const target of targets) signalIfSame(target, "SIGKILL");
424
486
  const deadline = Date.now() + STOP_GRACE_MS;
425
487
  while (targets.some(isSameProcess)) {
426
488
  if (Date.now() >= deadline) {
@@ -16,7 +16,7 @@ import { git } from "./git.mjs";
16
16
  import { resolveRenderer } from "./renderer.mjs";
17
17
  import { decodeSkillConfig } from "./verify/decode.mjs";
18
18
  import { layOutCopy } from "./run-copy.mjs";
19
- import { cliPaths } from "./stack.mjs";
19
+ import { cliPaths } from "./launch.mjs";
20
20
 
21
21
  /**
22
22
  * @param {import("node:test").TestContext} t The test
@@ -8,7 +8,12 @@ import {
8
8
  import { basename, join, relative, sep } from "node:path";
9
9
  import { WORKSPACE_FOLDER } from "./build-key.mjs";
10
10
 
11
- const COPY_SKIPPED = new Set(["node_modules", ".antelope", WORKSPACE_FOLDER]);
11
+ /** The playground entries a copy leaves out: installed modules and builds. */
12
+ export const COPY_SKIPPED = new Set([
13
+ "node_modules",
14
+ ".antelope",
15
+ WORKSPACE_FOLDER,
16
+ ]);
12
17
  const SHADOW_SKIPPED = new Set([".antelope", WORKSPACE_FOLDER, ".git"]);
13
18
 
14
19
  /**
@@ -21,6 +21,7 @@ import {
21
21
  isString,
22
22
  nullable,
23
23
  objectOf,
24
+ oneOf,
24
25
  recordOf,
25
26
  } from "./json.mjs";
26
27
 
@@ -33,7 +34,8 @@ const TIMESTAMP_LENGTH = 15;
33
34
  * @typedef {ProcessRecord & { port: number }} ServerRecord
34
35
  * @typedef {ServerRecord & { database: string }} BackendRecord A backend the run started, with the database it serves
35
36
  * @typedef {{ email: string, password: string, userId?: string | null }} Account
36
- * @typedef {{ dir: string, root: string, home: string, logs: string, mongo: string, browser?: ServerRecord, evidence: string, cache: string, id: string, createdAt: string, environment: string, playground: string, moduleRoot: string, repo: string | null, headSha: string | null, renderer?: string, baseRef: string, skill: string | null, apiPort: number, webPort: number, smtpPort: number, mail: string, apiUrl: string, webUrl: string, databasePrefix: string, database: string, mongoUrl: string, ownsMongo: boolean, secrets: Record<string, string>, adminPassword: string, extraEnv: Record<string, string>, processes: ProcessRecord[], namespaces?: import("./identity.mjs").Namespaces, noStandby?: boolean, buildRoots?: string[], accounts: Record<string, Account>, tokens: Record<string, string>, ready: boolean, error?: string, runPlayground?: string, baseRoot?: string, resetCount?: number, journeyCount?: number, frontendBuild?: FrontendBuild, bakedEnv?: Record<string, string> }} RunState
37
+ * @typedef {{ dir: string, root: string, home: string, logs: string, mongo: string, browser?: ServerRecord, evidence: string, cache: string, id: string, createdAt: string, environment: string, playground: string, moduleRoot: string, repo: string | null, headSha: string | null, renderer?: string, baseRef: string, skill: string | null, apiPort: number, webPort: number, smtpPort: number, mail: string, apiUrl: string, webUrl: string, databasePrefix: string, database: string, mongoUrl: string, ownsMongo: boolean, secrets: Record<string, string>, adminPassword: string, extraEnv: Record<string, string>, processes: ProcessRecord[], namespaces?: import("./identity.mjs").Namespaces, noStandby?: boolean, frontendMode?: FrontendMode, buildRoots?: string[], accounts: Record<string, Account>, tokens: Record<string, string>, ready: boolean, error?: string, runPlayground?: string, baseRoot?: string, resetCount?: number, journeyCount?: number, frontendBuild?: FrontendBuild, bakedEnv?: Record<string, string> }} RunState
38
+ * @typedef {"build" | "dev"} FrontendMode How the run serves its dashboard: `build` runs `ajs dms build` then `ajs dms start`, `dev` runs `ajs dms dev` on the sources. A run without one serves a build.
37
39
  * @typedef {{ key: string | null, cached: boolean, reason?: string }} FrontendBuild The key of the inputs of the run's frontend build (null when it was not keyed), whether the build came from the build cache, and why the cache was not used or not filled when it should have been
38
40
  */
39
41
 
@@ -109,7 +111,7 @@ export function createRunFolders(dir) {
109
111
  }
110
112
 
111
113
  /**
112
- * @typedef {Omit<RunState, "browser" | "accounts"> & { browser?: string | ServerRecord, accounts: Record<string, Omit<Account, "password"> & { password?: string }> }} StoredRunState The state as a file may hold it. A run saved by an earlier release holds the browser's folder in `browser` until the browser starts, and `down` leaves an account without its `password`.
114
+ * @typedef {Omit<RunState, "browser" | "accounts"> & { browser?: string | ServerRecord, accounts: Record<string, Omit<Account, "password"> & { password?: string }>, stoppedAt?: string }} StoredRunState The state as a file may hold it. A run saved by an earlier release holds the browser's folder in `browser` until the browser starts, and `down` leaves an account without its `password` and records when it stopped in `stoppedAt`.
113
115
  */
114
116
 
115
117
  const isStrings = recordOf(isString);
@@ -186,6 +188,7 @@ const isStoredRun = objectOf(
186
188
  browser: either(isString, isServerRecord),
187
189
  namespaces: objectOf({}, { pid: isString, time: isString }),
188
190
  noStandby: isBoolean,
191
+ frontendMode: oneOf(["build", "dev"]),
189
192
  buildRoots: arrayOf(isString),
190
193
  error: isString,
191
194
  renderer: isString,
@@ -202,19 +205,19 @@ const isStoredRun = objectOf(
202
205
  );
203
206
 
204
207
  /**
205
- * Reads the state `up` recorded for a run. A folder an earlier release stored
206
- * in `browser` is dropped, since nothing creates or reads that folder. An
207
- * account that `down` left without its `password` reads with an empty one.
208
- * Every command opens its run here, so a command run outside the PID or
209
- * time namespace `up` ran in refuses before it reads a process or changes
210
- * anything.
208
+ * Reads the state `up` recorded for a run, from any PID or time namespace.
209
+ * A folder an earlier release stored in `browser` is dropped, since nothing
210
+ * creates or reads that folder. An account that `down` left without its
211
+ * `password` reads with an empty one. Only a command that never reads,
212
+ * starts, signals or forgets a process the run recorded opens its run here:
213
+ * `mail`, `timings`, `api`, `onboard` and `verdict`. Every other command
214
+ * opens it with {@link loadRun}.
211
215
  *
212
216
  * @param {string} dir The run root, as `up` printed it
213
217
  * @returns {RunState} The run state
214
218
  * @throws When the folder holds no run.json
215
- * @throws When the run was started in another PID or time namespace
216
219
  */
217
- export function loadRun(dir) {
220
+ export function readRun(dir) {
218
221
  const file = join(resolve(dir), RUN_FILE);
219
222
  if (!existsSync(file)) {
220
223
  throw new Error(
@@ -224,7 +227,6 @@ export function loadRun(dir) {
224
227
  /** @type {unknown} */
225
228
  const parsed = JSON.parse(readFileSync(file, "utf8"));
226
229
  const stored = decode(isStoredRun, parsed, file, "a run state");
227
- assertSameNamespaces(stored.namespaces);
228
230
  const { browser, accounts, ...rest } = stored;
229
231
  const run = {
230
232
  ...rest,
@@ -238,11 +240,28 @@ export function loadRun(dir) {
238
240
  return browser === undefined || isString(browser) ? run : { ...run, browser };
239
241
  }
240
242
 
243
+ /**
244
+ * Reads the state `up` recorded for a run, as {@link readRun} does, for
245
+ * every command that {@link readRun} does not name. Run outside the PID or
246
+ * time namespace `up` ran in, it refuses before the command reads a process
247
+ * or changes anything.
248
+ *
249
+ * @param {string} dir The run root, as `up` printed it
250
+ * @returns {RunState} The run state
251
+ * @throws When the folder holds no run.json
252
+ * @throws When the run was started in another PID or time namespace
253
+ */
254
+ export function loadRun(dir) {
255
+ const run = readRun(dir);
256
+ assertSameNamespaces(run.namespaces);
257
+ return run;
258
+ }
259
+
241
260
  /**
242
261
  * Writes the run state, readable by its owner only since it holds the run's
243
262
  * secrets and the admin password.
244
263
  *
245
- * @param {RunState} state The run state
264
+ * @param {StoredRunState} state The run state
246
265
  */
247
266
  export function saveRun(state) {
248
267
  writeFileSync(
@@ -1,8 +1,6 @@
1
1
  import { randomBytes } from "node:crypto";
2
2
  import { existsSync, rmSync } from "node:fs";
3
- import { createRequire } from "node:module";
4
- import { homedir } from "node:os";
5
- import { dirname, join, resolve } from "node:path";
3
+ import { join, resolve } from "node:path";
6
4
  import { layOutFrontendBuild } from "./build-cache.mjs";
7
5
  import { existingBuildRoots } from "./build-inputs.mjs";
8
6
  import { describeFailure } from "./failure.mjs";
@@ -29,14 +27,23 @@ import {
29
27
  runsRoot,
30
28
  saveRun,
31
29
  } from "./run-state.mjs";
32
- import { RENDERER_CLI, resolveRenderer } from "./renderer.mjs";
30
+ import { resolveRenderer } from "./renderer.mjs";
31
+ import { moduleRootOf } from "./module-root.mjs";
32
+ import {
33
+ cliPaths,
34
+ CONTROL_BIN,
35
+ ENVIRONMENT,
36
+ frontendPackage,
37
+ resolutionFolders,
38
+ spec,
39
+ } from "./launch.mjs";
33
40
  import { layOutCopy } from "./run-copy.mjs";
34
41
  import { newPassword } from "./session.mjs";
35
42
  import { appendTiming, recordTiming, stopwatch, timed } from "./timing.mjs";
36
43
 
37
44
  /**
38
45
  * @typedef {import("./run-state.mjs").RunState} RunState
39
- * @typedef {{ playground: string, renderer?: string, runs?: string, mongoUrl?: string, env?: string[], base?: string, skill?: string, prepared?: import("./timing.mjs").TimingEntry[], noStandby?: boolean, buildCache?: boolean }} UpOptions Where the playground and the runs are, the `prepare` entries to record once the run exists, whether fresh databases start their backend on the spot, and whether the frontend build may come from the build cache (it may unless `buildCache` is false)
46
+ * @typedef {{ playground: string, renderer?: string, runs?: string, mongoUrl?: string, env?: string[], base?: string, skill?: string, prepared?: import("./timing.mjs").TimingEntry[], noStandby?: boolean, buildCache?: boolean, frontendMode?: import("./run-state.mjs").FrontendMode }} UpOptions Where the playground and the runs are, the `prepare` entries to record once the run exists, whether fresh databases start their backend on the spot, whether the frontend build may come from the build cache (it may unless `buildCache` is false), and how the dashboard is served (a build unless `frontendMode` is `dev`)
40
47
  */
41
48
 
42
49
  const READY_TIMEOUT_MS = 180_000;
@@ -52,103 +59,6 @@ const SECRET_NAMES = [
52
59
  "DMS_SESSION_SECRET",
53
60
  "DMS_SETUP_TOKEN",
54
61
  ];
55
- const DROPPED_PREFIXES = ["ANTELOPEJS_", "npm_", "PNPM_", "DMS_", "MONGO_"];
56
-
57
- /** This package's root, which resolves dms-control's own dependencies. */
58
- export const PACKAGE_ROOT = resolve(import.meta.dirname, "..", "..");
59
-
60
- /** The dms-control entry, which also serves the mail sink and the browser. */
61
- export const CONTROL_BIN = join(PACKAGE_ROOT, "bin", "dms-control.mjs");
62
-
63
- /** The AntelopeJS environment every run builds and starts. */
64
- export const ENVIRONMENT = "docs";
65
-
66
- /**
67
- * The folders the project's dependencies resolve from: the playground, the
68
- * module it belongs to, then this package.
69
- *
70
- * @param {{ playground: string, moduleRoot: string }} state The run
71
- * @returns {string[]} The folders, in order
72
- */
73
- export function resolutionFolders(state) {
74
- return [state.playground, state.moduleRoot, PACKAGE_ROOT];
75
- }
76
-
77
- /**
78
- * The `ajs` and `ajs dms` entry points the playground installs, `ajs dms`
79
- * being the renderer checkout's when the run serves one.
80
- *
81
- * @param {string} playground The playground folder
82
- * @param {string} [renderer] The renderer checkout the run serves
83
- * @returns {{ ajs: string, dms: string }} Their scripts
84
- */
85
- export function cliPaths(playground, renderer) {
86
- const require = createRequire(join(playground, "package.json"));
87
- const core = dirname(require.resolve("@antelopejs/core/package.json"));
88
- return {
89
- ajs: join(core, "dist", "core", "cli", "index.js"),
90
- dms: join(frontendPackage(playground, renderer), RENDERER_CLI),
91
- };
92
- }
93
-
94
- /**
95
- * The `@antelopejs/dms-frontend` that builds and serves the run's dashboard:
96
- * the renderer checkout, else the one the playground installs.
97
- *
98
- * @param {string} playground The playground folder
99
- * @param {string} [renderer] The renderer checkout the run serves
100
- * @returns {string} Its folder
101
- */
102
- export function frontendPackage(playground, renderer) {
103
- const require = createRequire(join(playground, "package.json"));
104
- return (
105
- renderer ??
106
- dirname(require.resolve("@antelopejs/dms-frontend/package.json"))
107
- );
108
- }
109
-
110
- function inheritedEnv() {
111
- return Object.fromEntries(
112
- Object.entries(process.env).filter(
113
- ([key]) => !DROPPED_PREFIXES.some((prefix) => key.startsWith(prefix)),
114
- ),
115
- );
116
- }
117
-
118
- /**
119
- * The environment of every process a run starts: its own HOME, ports,
120
- * database, origin and secrets, an npm cache and a pnpm store shared by
121
- * every run, no update checks and no colors. Extra `KEY=VALUE` pairs from `--env` come last.
122
- *
123
- * @param {import("./run-state.mjs").RunState} state The run
124
- * @returns {NodeJS.ProcessEnv} The environment
125
- */
126
- export function runEnv(state) {
127
- const cacheHome = process.env.XDG_CACHE_HOME ?? join(homedir(), ".cache");
128
- return {
129
- ...inheritedEnv(),
130
- HOME: state.home,
131
- USERPROFILE: state.home,
132
- CI: "1",
133
- NO_COLOR: "1",
134
- AJS_NO_UPDATE_CHECK: "1",
135
- NO_UPDATE_NOTIFIER: "1",
136
- COREPACK_HOME:
137
- process.env.COREPACK_HOME ?? join(cacheHome, "node", "corepack"),
138
- npm_config_cache: join(cacheHome, "dms-control", "npm"),
139
- npm_config_store_dir: join(cacheHome, "dms-control", "pnpm-store"),
140
- PORT: String(state.apiPort),
141
- DMS_CLIENT_BASE_URL: state.webUrl,
142
- DMS_API_BASE_URL: state.apiUrl,
143
- DMS_PREBUILT: "1",
144
- DMS_SMTP_PORT: String(state.smtpPort),
145
- MONGO_URL: state.mongoUrl,
146
- MONGO_DATABASE: state.database,
147
- ...state.secrets,
148
- ...state.extraEnv,
149
- };
150
- }
151
-
152
62
  /**
153
63
  * @param {string[]} pairs
154
64
  * @returns {Record<string, string>}
@@ -186,7 +96,7 @@ async function initialState(options) {
186
96
  createdAt: new Date().toISOString(),
187
97
  environment: ENVIRONMENT,
188
98
  playground,
189
- moduleRoot: dirname(playground),
99
+ moduleRoot: moduleRootOf(playground),
190
100
  repo: checkout.root,
191
101
  headSha: verified.head,
192
102
  baseRef: options.base ?? "origin/main",
@@ -217,31 +127,10 @@ async function initialState(options) {
217
127
  };
218
128
  if (renderer) state.renderer = renderer;
219
129
  if (options.noStandby) state.noStandby = true;
130
+ if (options.frontendMode === "dev") state.frontendMode = "dev";
220
131
  return state;
221
132
  }
222
133
 
223
- /**
224
- * How to run one of the playground's CLIs for the run: its own log, the
225
- * run's environment, from the run's playground copy or `cwd`.
226
- *
227
- * @param {import("./run-state.mjs").RunState} state The run
228
- * @param {string} name The log name
229
- * @param {string} script The CLI script
230
- * @param {string[]} args Its arguments
231
- * @param {string} [cwd] Where to run it
232
- * @returns {{ name: string, program: string, args: string[], cwd: string, env: NodeJS.ProcessEnv, logs: string }} The process spec
233
- */
234
- export function spec(state, name, script, args, cwd = state.runPlayground) {
235
- return {
236
- name,
237
- program: process.execPath,
238
- args: [script, ...args],
239
- cwd,
240
- env: runEnv(state),
241
- logs: state.logs,
242
- };
243
- }
244
-
245
134
  /**
246
135
  * Records a process of the run, in place of the one of the same name.
247
136
  *
@@ -421,13 +310,71 @@ export function workspaceSetup(state, name, project, install) {
421
310
  );
422
311
  }
423
312
 
313
+ /**
314
+ * Builds the run's dashboard as `ajs dms build` does, in a prepared
315
+ * workspace, or lays out the build of the same inputs from the build cache.
316
+ *
317
+ * @param {RunState} state The run, after its project build
318
+ * @param {boolean} useCache Whether the build may come from the build cache
319
+ * @returns {Promise<void>} Resolves once the build is in the run's workspace
320
+ */
321
+ function buildFrontend(state, useCache) {
322
+ const { dms } = cliPaths(state.playground, state.renderer);
323
+ return layOutFrontendBuild(
324
+ state,
325
+ frontendPackage(state.playground, state.renderer),
326
+ {
327
+ prepare: (workspace) =>
328
+ timed(state, "frontend-prepare", () =>
329
+ workspaceSetup(
330
+ state,
331
+ "frontend-prepare",
332
+ state.runPlayground ?? "",
333
+ true,
334
+ )(workspace),
335
+ ),
336
+ build: (prepared) => {
337
+ const build = spec(state, "frontend-build", dms, [
338
+ "build",
339
+ "-e",
340
+ ENVIRONMENT,
341
+ ]);
342
+ if (prepared) build.args.unshift("--import", PREPARED_WORKSPACE);
343
+ return runToEnd(build);
344
+ },
345
+ },
346
+ useCache,
347
+ );
348
+ }
349
+
350
+ /**
351
+ * How the run serves its dashboard on its web port against its API:
352
+ * `ajs dms start` on the build `up` made, or `ajs dms dev` on the sources
353
+ * when the run's `frontendMode` is `dev`.
354
+ *
355
+ * @param {RunState} state The run
356
+ * @returns {ReturnType<typeof spec>} The frontend's process spec
357
+ */
358
+ export function frontendSpec(state) {
359
+ const { dms } = cliPaths(state.playground, state.renderer);
360
+ return spec(state, "frontend", dms, [
361
+ state.frontendMode === "dev" ? "dev" : "start",
362
+ "-e",
363
+ ENVIRONMENT,
364
+ "-b",
365
+ state.apiUrl,
366
+ "-p",
367
+ String(state.webPort),
368
+ ]);
369
+ }
370
+
424
371
  /**
425
372
  * @param {RunState} state
426
373
  * @param {boolean} useCache
427
374
  * @returns {Promise<void>}
428
375
  */
429
376
  async function buildAndStart(state, useCache) {
430
- const clis = cliPaths(state.playground, state.renderer);
377
+ const { ajs } = cliPaths(state.playground, state.renderer);
431
378
  state.runPlayground = await timed(state, "layout", () =>
432
379
  layOutCopy(
433
380
  state.playground,
@@ -446,7 +393,7 @@ async function buildAndStart(state, useCache) {
446
393
  await timed(state, "mail", () => startFirstMail(state));
447
394
  await timed(state, "project-build", () =>
448
395
  runToEnd(
449
- spec(state, "project-build", clis.ajs, [
396
+ spec(state, "project-build", ajs, [
450
397
  "project",
451
398
  "build",
452
399
  "-e",
@@ -454,48 +401,14 @@ async function buildAndStart(state, useCache) {
454
401
  ]),
455
402
  ),
456
403
  );
457
- await timed(state, "frontend-build", () =>
458
- layOutFrontendBuild(
459
- state,
460
- frontendPackage(state.playground, state.renderer),
461
- {
462
- prepare: (workspace) =>
463
- timed(state, "frontend-prepare", () =>
464
- workspaceSetup(
465
- state,
466
- "frontend-prepare",
467
- state.runPlayground ?? "",
468
- true,
469
- )(workspace),
470
- ),
471
- build: (prepared) => {
472
- const build = spec(state, "frontend-build", clis.dms, [
473
- "build",
474
- "-e",
475
- ENVIRONMENT,
476
- ]);
477
- if (prepared) build.args.unshift("--import", PREPARED_WORKSPACE);
478
- return runToEnd(build);
479
- },
480
- },
481
- useCache,
482
- ),
483
- );
404
+ if (state.frontendMode !== "dev") {
405
+ await timed(state, "frontend-build", () => buildFrontend(state, useCache));
406
+ }
484
407
  state.buildRoots = existingBuildRoots(state);
485
408
  saveRun(state);
486
409
  await timed(state, "backend-start", () => startBackend(state));
487
410
  await timed(state, "frontend-start", async () => {
488
- const frontend = startDetached(
489
- spec(state, "frontend", clis.dms, [
490
- "start",
491
- "-e",
492
- ENVIRONMENT,
493
- "-b",
494
- state.apiUrl,
495
- "-p",
496
- String(state.webPort),
497
- ]),
498
- );
411
+ const frontend = startDetached(frontendSpec(state));
499
412
  record(state, { ...frontend, port: state.webPort });
500
413
  await waitForOk(`${state.webUrl}/dms-preview`, frontend, READY_TIMEOUT_MS);
501
414
  });
@@ -581,21 +494,21 @@ export async function down(state) {
581
494
  lines.push(`removed ${folder}`);
582
495
  }
583
496
  }
584
- Object.assign(state, {
585
- processes: [],
586
- browser: undefined,
587
- secrets: {},
588
- adminPassword: "",
589
- tokens: {},
497
+ state.processes = [];
498
+ state.browser = undefined;
499
+ state.secrets = {};
500
+ state.adminPassword = "";
501
+ state.tokens = {};
502
+ state.ready = false;
503
+ saveRun({
504
+ ...state,
590
505
  accounts: Object.fromEntries(
591
506
  Object.entries(state.accounts ?? {}).map(([name, account]) => [
592
507
  name,
593
508
  { email: account.email },
594
509
  ]),
595
510
  ),
596
- ready: false,
597
511
  stoppedAt: new Date().toISOString(),
598
512
  });
599
- saveRun(state);
600
513
  return [...new Set(lines)];
601
514
  }