@plexus-ms/lib 0.122.1 → 0.124.0

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 (90) hide show
  1. package/dist/bookkeeping.d.ts +0 -8
  2. package/dist/bookkeeping.d.ts.map +1 -1
  3. package/dist/bookkeeping.js +5 -16
  4. package/dist/bookkeeping.js.map +1 -1
  5. package/dist/compose.d.ts +41 -0
  6. package/dist/compose.d.ts.map +1 -0
  7. package/dist/compose.js +169 -0
  8. package/dist/compose.js.map +1 -0
  9. package/dist/consumers.d.ts +3 -18
  10. package/dist/consumers.d.ts.map +1 -1
  11. package/dist/consumers.js +13 -42
  12. package/dist/consumers.js.map +1 -1
  13. package/dist/context.d.ts +6 -0
  14. package/dist/context.d.ts.map +1 -1
  15. package/dist/context.js +14 -5
  16. package/dist/context.js.map +1 -1
  17. package/dist/deploy.d.ts +11 -3
  18. package/dist/deploy.d.ts.map +1 -1
  19. package/dist/deploy.js +185 -120
  20. package/dist/deploy.js.map +1 -1
  21. package/dist/deployTargets.d.ts.map +1 -1
  22. package/dist/deployTargets.js +8 -7
  23. package/dist/deployTargets.js.map +1 -1
  24. package/dist/doctor.d.ts +121 -15
  25. package/dist/doctor.d.ts.map +1 -1
  26. package/dist/doctor.js +512 -71
  27. package/dist/doctor.js.map +1 -1
  28. package/dist/effects.d.ts +3 -0
  29. package/dist/effects.d.ts.map +1 -1
  30. package/dist/effects.js.map +1 -1
  31. package/dist/frontmatter.js +1 -1
  32. package/dist/frontmatter.js.map +1 -1
  33. package/dist/index.d.ts +10 -10
  34. package/dist/index.d.ts.map +1 -1
  35. package/dist/index.js +10 -10
  36. package/dist/index.js.map +1 -1
  37. package/dist/io.d.ts +28 -0
  38. package/dist/io.d.ts.map +1 -1
  39. package/dist/io.js +86 -4
  40. package/dist/io.js.map +1 -1
  41. package/dist/marker.d.ts +22 -5
  42. package/dist/marker.d.ts.map +1 -1
  43. package/dist/marker.js +100 -13
  44. package/dist/marker.js.map +1 -1
  45. package/dist/model.d.ts +48 -4
  46. package/dist/model.d.ts.map +1 -1
  47. package/dist/model.js +59 -11
  48. package/dist/model.js.map +1 -1
  49. package/dist/need.d.ts +11 -34
  50. package/dist/need.d.ts.map +1 -1
  51. package/dist/need.js +92 -54
  52. package/dist/need.js.map +1 -1
  53. package/dist/overview.d.ts +25 -0
  54. package/dist/overview.d.ts.map +1 -1
  55. package/dist/overview.js +106 -14
  56. package/dist/overview.js.map +1 -1
  57. package/dist/propagate.d.ts +3 -3
  58. package/dist/propagate.d.ts.map +1 -1
  59. package/dist/propagate.js +8 -6
  60. package/dist/propagate.js.map +1 -1
  61. package/dist/requirements.d.ts +1 -1
  62. package/dist/requirements.d.ts.map +1 -1
  63. package/dist/requirements.js +6 -5
  64. package/dist/requirements.js.map +1 -1
  65. package/dist/standard-index.json +90 -6
  66. package/dist/take.d.ts +1 -1
  67. package/dist/take.d.ts.map +1 -1
  68. package/dist/take.js +6 -25
  69. package/dist/take.js.map +1 -1
  70. package/dist/templates.d.ts +21 -0
  71. package/dist/templates.d.ts.map +1 -0
  72. package/dist/templates.js +55 -0
  73. package/dist/templates.js.map +1 -0
  74. package/dist/update.d.ts +3 -3
  75. package/dist/update.d.ts.map +1 -1
  76. package/dist/update.js +58 -71
  77. package/dist/update.js.map +1 -1
  78. package/dist/version.d.ts +7 -2
  79. package/dist/version.d.ts.map +1 -1
  80. package/dist/version.js +17 -2
  81. package/dist/version.js.map +1 -1
  82. package/package.json +1 -1
  83. package/dist/catalog.d.ts +0 -23
  84. package/dist/catalog.d.ts.map +0 -1
  85. package/dist/catalog.js +0 -38
  86. package/dist/catalog.js.map +0 -1
  87. package/dist/manifest.d.ts +0 -20
  88. package/dist/manifest.d.ts.map +0 -1
  89. package/dist/manifest.js +0 -59
  90. package/dist/manifest.js.map +0 -1
package/dist/doctor.js CHANGED
@@ -1,79 +1,520 @@
1
- // doctor: the staleness check (§ 13.4 PLX), a verb, not a system.
1
+ // doctor: the repo's checks (§ 13.4 PLX). Does this unit do what its
2
+ // contracts require?
2
3
  //
3
- // Every PLEXUS.md marker under a directory is read, and for each module it
4
- // declares the module's `changed` version is compared with the marker's
5
- // `plexus`; every `depends` entry of a declared module has to be declared
6
- // where § 1.4 says it is satisfied: by the unit itself, by an enclosing
7
- // declaration (an app's repo, a repo's tenant) or by a contained one (a
8
- // repo's apps, a tenant's repos). What a module `consumes` is the other side
9
- // of a seam and never this unit's to declare. Findings are reported, never
10
- // fixed. A tenant is a directory whose repos sit side by side; the repo whose
11
- // marker declares PLX-Tenancy is the tenant's declaration.
4
+ // A unit is a repo or an app (§ 1.2 PLX; `examine` below): every repo is bound by
5
+ // PLX-Repo, every app by PLX-App with the profile its marker states, and an app
6
+ // under the operations repo's `apps/` is third-party, every other app built
7
+ // (§ 2 PLX-App). Each check is named after its requirement and lives in one
8
+ // small function; CHECKS maps the name to it. The list of names is the one
9
+ // the contract pages give below each requirements block ("`plx doctor`
10
+ // checks …", § 1.3 PLX), and a test holds the two equal.
12
11
  //
13
- // plx doctor # every marker, one line each
14
- // plx doctor ~/dev --compendium ~/dev/plexus-ms/compendium
15
- import { relative } from 'node:path';
16
- /** A scanned tree against a catalogue: pure, so a test compares reports. */
17
- export function diagnose(root, catalog) {
18
- const units = collect(root, []);
19
- const declarations = units.map((u) => diagnoseUnit(u, units, catalog, root.path));
20
- return { declarations, stale: declarations.filter((d) => d.findings.length > 0).length };
21
- }
22
- function collect(dir, ancestors, parent) {
23
- const here = dir.declaration || dir.problems?.some((p) => p.startsWith('PLEXUS.md')) ? [{ dir, ancestors, parent }] : [];
24
- const below = dir.declaration ? [...ancestors, dir] : ancestors;
25
- return [...here, ...dir.children.flatMap((c) => collect(c, below, dir))];
26
- }
27
- function diagnoseUnit(unit, units, catalog, root) {
28
- const { dir } = unit;
29
- const path = relative(root, dir.path) || '.';
30
- const problem = dir.problems?.find((p) => p.startsWith('PLEXUS.md'));
31
- if (!dir.declaration)
32
- return { path, modules: [], findings: [problem?.replace(/^PLEXUS\.md: /, '') ?? 'unreadable marker'] };
33
- const { plexus, modules } = dir.declaration;
34
- const context = new Set(contextOf(unit, units).flatMap((d) => d.declaration?.modules ?? []));
12
+ // The checks are static: they read the marker, `docker/compose.yaml`, the
13
+ // task list as mise reports it, an app's `package.json`, and git's list of
14
+ // tracked files. They never reach a host or a running app, and need no
15
+ // compendium: the requirement names a deviation may list come from the index
16
+ // this plx carries (standardIndex.ts). A deviation the marker lists silences
17
+ // its check; a deviation without a reason in the marker's body, or naming no
18
+ // requirement, is a finding of its own. Findings are reported, never fixed.
19
+ //
20
+ // plx doctor # this repo and its apps, from anywhere inside it
21
+ // plx doctor ~/dev # every Plexus repo beneath, and its apps
22
+ import { realpath } from 'node:fs/promises';
23
+ import { dirname, join, relative, resolve } from 'node:path';
24
+ import { APP_SERVICE, declaresHealthcheck, healthcheckOf, isMapping, labelsOf, normalImage, parseCompose, truthy, } from "./compose.js";
25
+ import { ExecError } from "./io.js";
26
+ import { REQUIREMENT_NAME } from "./lints.js";
27
+ import { MARKER_FILE, reasonGiven } from "./marker.js";
28
+ import { hasMarker, isOperations } from "./model.js";
29
+ import { appsOf, directoryAt, overview } from "./overview.js";
30
+ import { bundledIndex } from "./standardIndex.js";
31
+ // --- the checks ---------------------------------------------------------------
32
+ //
33
+ // Each returns what is wrong, one line per problem; an empty list passes.
34
+ const ROOT_VERBS = ['dev', 'build', 'verify'];
35
+ const SUB_VERBS = ['lint', 'check', 'test', 'verify'];
36
+ function repoMarker(repo) {
37
+ if (!repo.marker)
38
+ return [`no ${MARKER_FILE} at the repo's root`];
39
+ return repo.marker.problem ? [repo.marker.problem] : [];
40
+ }
41
+ const missingTasks = (repo, wanted) => 'names' in repo.tasks
42
+ ? wanted
43
+ .filter((t) => !repo.tasks.names.includes(t))
44
+ .map((t) => `no root mise task \`${t}\``)
45
+ : [];
46
+ function verbs(repo) {
47
+ if ('problem' in repo.tasks)
48
+ return [`mise could not list the tasks: ${repo.tasks.problem}`];
49
+ return missingTasks(repo, ROOT_VERBS);
50
+ }
51
+ /** Existence only: what `verify` runs, in which order, and what `check` includes is not read (see the report). */
52
+ const subVerbs = (repo) => missingTasks(repo, SUB_VERBS);
53
+ function appMarker(app) {
54
+ const { declaration, problem } = app.marker;
55
+ if (problem || !declaration)
56
+ return [problem ?? `no ${MARKER_FILE}`];
57
+ if (declaration.profile === undefined)
58
+ return ['the marker sets no `profile`: stateless or stateful'];
59
+ if (!isProfile(declaration.profile))
60
+ return [`\`profile\` is \`${declaration.profile}\`, not stateless or stateful`];
61
+ return [];
62
+ }
63
+ /** What the contract page says doctor checks of it: the file exists and declares the app service. */
64
+ function composeFile(app) {
65
+ if (app.composeProblem)
66
+ return [app.composeProblem];
67
+ if (!app.compose)
68
+ return ['no docker/compose.yaml'];
69
+ if (!app.compose.services[APP_SERVICE])
70
+ return [
71
+ `docker/compose.yaml declares no \`${APP_SERVICE}\` service${app.compose.includes ? ' itself (the files it includes are not read)' : ''}, the app service the deploy verb reads`,
72
+ ];
73
+ return [];
74
+ }
75
+ function tenantLabel(compose) {
76
+ return Object.entries(compose.services)
77
+ .filter(([, service]) => (labelsOf(service)['plexus.tenant'] ?? '').trim() === '')
78
+ .map(([name]) => `service \`${name}\` carries no \`plexus.tenant\` label`);
79
+ }
80
+ function envFileLoad(compose) {
81
+ const loaded = envFilesOf(compose.services[APP_SERVICE] ?? {});
82
+ const problems = [];
83
+ if (!loaded.has('.env'))
84
+ problems.push(`the ${APP_SERVICE} service does not load .env via env_file`);
85
+ const secret = loaded.get('.env.secret');
86
+ if (secret === undefined)
87
+ problems.push(`the ${APP_SERVICE} service does not load .env.secret via env_file`);
88
+ else if (secret)
89
+ problems.push('.env.secret is loaded, but not marked `required: false`');
90
+ return problems;
91
+ }
92
+ /** The bare form and the recommended `:?message` form (§ 3 PLX-App). */
93
+ const IMAGE_REF = /^\$\{PLEXUS_DEPLOYMENT_IMAGE(:\?[^}]*)?\}$/;
94
+ function imageRef(compose) {
95
+ const image = compose.services[APP_SERVICE]?.image;
96
+ if (typeof image === 'string' && IMAGE_REF.test(image))
97
+ return [];
98
+ return [
99
+ image === undefined
100
+ ? `the ${APP_SERVICE} service names no image; a built app's is \${PLEXUS_DEPLOYMENT_IMAGE}`
101
+ : `the ${APP_SERVICE} service's image is \`${String(image)}\`, not \${PLEXUS_DEPLOYMENT_IMAGE}`,
102
+ ];
103
+ }
104
+ /**
105
+ * A tracked `.env` or `.env.secret` is reported once, on the unit that holds
106
+ * it: the app whose directory it is in, else the repo, when the repo is the
107
+ * source repo of any app.
108
+ */
109
+ function noCommittedValues(unit) {
110
+ const repo = unit.kind === 'app' ? unit.repo : unit;
111
+ if (repo.apps.length === 0)
112
+ return [];
113
+ const within = (file, dir) => file.startsWith(`${dir}/`);
114
+ const held = (file) => unit.kind === 'app' ? within(file, unit.dir) : !repo.apps.some((dir) => within(file, dir));
115
+ return (repo.tracked ?? [])
116
+ .filter((f) => /(^|\/)\.env(\.secret)?$/.test(f) && held(f))
117
+ .map((f) => `the source repo tracks \`${f}\``);
118
+ }
119
+ function singlePort(compose) {
120
+ const ports = portsOf(compose.services[APP_SERVICE] ?? {});
121
+ if (ports.length === 1)
122
+ return [];
123
+ return [
124
+ ports.length === 0
125
+ ? `the ${APP_SERVICE} service publishes no port`
126
+ : `the ${APP_SERVICE} service publishes ${ports.length} ports, not one`,
127
+ ];
128
+ }
129
+ /** The platform's binding of the app's port (§ 4 PLX-App), as the compose file spells it. */
130
+ const LOOPBACK_PORT = `\${PLEXUS_LOOPBACK_PORT}`;
131
+ const LOOPBACK_FORM = `127.0.0.1:${LOOPBACK_PORT}:<container-port>`;
132
+ /**
133
+ * The host port the platform sets: `${PLEXUS_LOOPBACK_PORT}`, with a
134
+ * `:?message` that fails loudly when it is unset, or `$PLEXUS_LOOPBACK_PORT`.
135
+ * A default (`:-3000`) fixes a port, and is not it.
136
+ */
137
+ const isLoopbackVar = (host) => /^(?:\$\{PLEXUS_LOOPBACK_PORT(?::\?[^}]*)?\}|\$PLEXUS_LOOPBACK_PORT)$/.test(host);
138
+ function loopbackPort(compose) {
139
+ const problems = [];
140
+ const own = portsOf(compose.services[APP_SERVICE] ?? {});
141
+ if (own.length === 0)
142
+ problems.push(`the ${APP_SERVICE} service publishes no port as ${LOOPBACK_FORM}`);
143
+ for (const port of own)
144
+ if (!isLoopback(port))
145
+ problems.push(`the ${APP_SERVICE} service publishes \`${renderPort(port)}\`, not ${LOOPBACK_FORM}`);
146
+ for (const [name, service] of Object.entries(compose.services)) {
147
+ if (name === APP_SERVICE)
148
+ continue;
149
+ for (const port of portsOf(service)) {
150
+ const host = hostPortOf(port);
151
+ if (host && !isLoopbackVar(host))
152
+ problems.push(`service \`${name}\` fixes host port \`${host}\` (\`${renderPort(port)}\`)`);
153
+ }
154
+ }
155
+ return problems;
156
+ }
157
+ function healthcheck(compose) {
158
+ if (declaresHealthcheck(healthcheckOf(compose)))
159
+ return [];
160
+ return [`the ${APP_SERVICE} service declares no healthcheck with a test of its own`];
161
+ }
162
+ const dockerfile = (app) => (app.dockerfile ? [] : ['no docker/Dockerfile']);
163
+ function noState(compose) {
164
+ const problems = [];
165
+ if (compose.services.migrate)
166
+ problems.push('a stateless app declares a `migrate` service');
167
+ for (const [name, service] of Object.entries(compose.services))
168
+ if ('plexus.backup' in labelsOf(service))
169
+ problems.push(`service \`${name}\` of a stateless app carries a \`plexus.backup\` label`);
170
+ return problems;
171
+ }
172
+ function migrateService(compose) {
173
+ const migrate = compose.services.migrate;
174
+ if (!migrate)
175
+ return ['declares no `migrate` service'];
176
+ const problems = [];
177
+ const profiles = Array.isArray(migrate.profiles) ? migrate.profiles.map(String) : [];
178
+ if (!profiles.includes('migrate'))
179
+ problems.push('the `migrate` service is not under `profiles: ["migrate"]`, so a plain `up` starts it');
180
+ const own = compose.services[APP_SERVICE]?.image;
181
+ const same = typeof own === 'string' && typeof migrate.image === 'string' && normalImage(migrate.image) === normalImage(own);
182
+ if (own !== undefined && !same)
183
+ problems.push(`the \`migrate\` service runs \`${String(migrate.image ?? 'no image')}\`, not the app's own image \`${String(own)}\``);
184
+ return problems;
185
+ }
186
+ function seed(app) {
187
+ if (app.packageJsonProblem)
188
+ return [app.packageJsonProblem];
189
+ const scripts = app.packageJson?.scripts;
190
+ if (!app.packageJson || (isMapping(scripts) && typeof scripts.seed === 'string' && scripts.seed.trim() !== ''))
191
+ return [];
192
+ return ['package.json has no `seed` script'];
193
+ }
194
+ /**
195
+ * A compose check: runs once the file was read, on what the file itself
196
+ * declares (an `include`d file is not read; the unit gets a hint saying so);
197
+ * PLX-App/Compose reports why it was not read.
198
+ */
199
+ const onCompose = (check) => (app) => app.compose ? check(app.compose) : [];
200
+ /** A check of the app service: runs once the file declares it; PLX-App/Compose reports why it does not. */
201
+ const onAppService = (check) => (app) => app.compose?.services[APP_SERVICE] ? check(app.compose) : [];
202
+ /** Every requirement doctor checks, by name: what the contract pages list, in their order. */
203
+ export const CHECKS = {
204
+ 'PLX-Repo/Marker': { binds: 'repo', check: repoMarker },
205
+ 'PLX-Repo/Verbs': { binds: 'repo', check: verbs },
206
+ 'PLX-Repo/SubVerbs': { binds: 'repo', check: subVerbs },
207
+ 'PLX-App/Marker': { binds: 'app', check: appMarker },
208
+ 'PLX-App/Compose': { binds: 'app', check: composeFile },
209
+ 'PLX-App/TenantLabel': { binds: 'app', check: onCompose(tenantLabel) },
210
+ 'PLX-App/EnvFileLoad': { binds: 'app', check: onAppService(envFileLoad) },
211
+ 'PLX-App/ImageRef': { binds: 'app', built: true, check: onAppService(imageRef) },
212
+ 'PLX-App/NoCommittedValues': { binds: 'unit', check: noCommittedValues },
213
+ 'PLX-App/SinglePort': { binds: 'app', check: onAppService(singlePort) },
214
+ 'PLX-App/LoopbackPort': { binds: 'app', check: onAppService(loopbackPort) },
215
+ 'PLX-App/Healthcheck': { binds: 'app', check: onAppService(healthcheck) },
216
+ 'PLX-App/Dockerfile': { binds: 'app', built: true, check: dockerfile },
217
+ 'PLX-App/Stateless/NoState': { binds: 'app', profile: 'stateless', check: onCompose(noState) },
218
+ 'PLX-App/Stateful/MigrateService': { binds: 'app', profile: 'stateful', check: onAppService(migrateService) },
219
+ 'PLX-App/Stateful/Seed': { binds: 'app', profile: 'stateful', check: seed },
220
+ };
221
+ const isProfile = (value) => value === 'stateless' || value === 'stateful';
222
+ /** The requirement names the index this plx carries knows: what a deviation may name. */
223
+ export const knownRequirements = () => new Set(bundledIndex().citable.filter((c) => new RegExp(`^${REQUIREMENT_NAME}$`).test(c)));
224
+ /** What was read, against the checks: pure, so a test compares reports. */
225
+ export function diagnose(facts, known = knownRequirements()) {
226
+ const units = facts.map((unit) => diagnoseUnit(unit, known));
227
+ return { units, failed: units.filter((u) => u.findings.length > 0).length };
228
+ }
229
+ function diagnoseUnit(unit, known) {
230
+ const declaration = unit.marker?.declaration;
231
+ const deviations = declaration?.deviations ?? [];
232
+ const profile = unit.kind === 'app' && isProfile(declaration?.profile) ? declaration.profile : undefined;
35
233
  const findings = [];
36
- for (const code of modules) {
37
- const module = catalog.get(code);
38
- if (!module) {
39
- findings.push(`declares ${code}, which no module carries`);
234
+ for (const name of deviations) {
235
+ if (!known.has(name))
236
+ findings.push({ requirement: name, problem: 'listed under `deviations`, but no requirement has this name' });
237
+ else if (!reasonGiven(declaration?.body ?? '', name))
238
+ findings.push({
239
+ requirement: name,
240
+ problem: "listed under `deviations`, but no bullet of the marker's body names it with a reason",
241
+ });
242
+ }
243
+ for (const [name, c] of Object.entries(CHECKS)) {
244
+ if (deviations.includes(name))
40
245
  continue;
246
+ for (const problem of run(c, unit, profile))
247
+ findings.push({ requirement: name, problem });
248
+ }
249
+ const obsolete = (declaration?.obsolete ?? []).map((k) => `\`${k}\``).join(' and ');
250
+ const hints = [];
251
+ if (obsolete)
252
+ hints.push(`the marker's ${obsolete} ${obsolete.includes(' and ') ? 'are' : 'is'} no longer read and can go`);
253
+ if (unit.kind === 'app' && unit.compose?.includes)
254
+ hints.push('docker/compose.yaml uses `include`: the compose checks read what the file itself declares, not the files it includes');
255
+ return {
256
+ path: unit.path,
257
+ kind: unit.kind,
258
+ ...(profile ? { profile } : {}),
259
+ deviations,
260
+ findings,
261
+ ...(hints.length > 0 ? { hints } : {}),
262
+ };
263
+ }
264
+ /** A check's problems with a unit, or none where it does not bind the unit: another kind, profile, or a third-party app. */
265
+ function run(c, unit, profile) {
266
+ if (c.binds === 'unit')
267
+ return c.check(unit);
268
+ if (c.binds === 'repo')
269
+ return unit.kind === 'app' ? [] : c.check(unit);
270
+ if (unit.kind !== 'app')
271
+ return [];
272
+ if (c.profile && c.profile !== profile)
273
+ return [];
274
+ if (c.built && unit.thirdParty)
275
+ return [];
276
+ return c.check(unit);
277
+ }
278
+ /**
279
+ * Read the units (§ 1.2 PLX) under `dir`. A repo is a git root; its apps are
280
+ * what `appsOf` finds in its `apps/` (overview.ts; overview reads them by it
281
+ * too), with a marker or without. `dir` is a workspace when git roots lie
282
+ * beneath it, whatever lies above: every git root beneath it is read that is
283
+ * a Plexus repo, which carries a marker or has an app, and the others are
284
+ * named. Otherwise `dir` is in a repo, the nearest git root at or above it,
285
+ * and that repo is read from its root, with no git root nested in it: that
286
+ * is another repo, and none of its files are this repo's. A directory that
287
+ * cannot be read, and a symbolic link to an app or a repo, are named, never
288
+ * fatal.
289
+ */
290
+ export async function examine(ctx, dir) {
291
+ const given = resolve(dir);
292
+ const own = await ctx.readDir(given).catch(() => []);
293
+ let top = own.some((e) => e.name === '.git') ? given : undefined;
294
+ const tree = top ? undefined : await overview(ctx, given, { git: false });
295
+ if (tree && !holdsGitRoot(tree))
296
+ top = await enclosingGitRoot(ctx, dirname(given));
297
+ if (top) {
298
+ const repo = await directoryAt(ctx, top);
299
+ const found = await appsOf(ctx, top);
300
+ const rel = (path) => relative(top, path);
301
+ return {
302
+ root: top,
303
+ inRepo: true,
304
+ facts: await readUnits(ctx, repo, found.apps, top),
305
+ skipped: [],
306
+ links: found.links.map(rel),
307
+ unreadable: found.unreadable.map(({ path, why }) => ({ path: rel(path), why })),
308
+ };
309
+ }
310
+ const examination = { root: given, inRepo: false, facts: [], skipped: [], links: [], unreadable: [] };
311
+ const rel = (path) => relative(given, path) || '.';
312
+ const visit = async (d) => {
313
+ if (d.unreadable)
314
+ examination.unreadable.push({ path: rel(d.path), why: d.unreadable });
315
+ if (d.symlink)
316
+ examination.links.push(rel(d.path));
317
+ if (d.gitRoot) {
318
+ const apps = d.apps ?? [];
319
+ if (hasMarker(d) || apps.length > 0)
320
+ examination.facts.push(...(await readUnits(ctx, d, apps, given)));
321
+ else
322
+ examination.skipped.push(rel(d.path));
41
323
  }
42
- if (module.changed && compareVersions(module.changed, plexus) > 0)
43
- findings.push(`${code} changed in ${module.changed}, declared at ${plexus}`);
44
- for (const dep of module.depends)
45
- if (!modules.includes(dep) && !context.has(dep))
46
- findings.push(`${code} depends on ${dep}, declared neither here nor by an enclosing or contained declaration`);
324
+ for (const child of d.children)
325
+ await visit(child);
326
+ };
327
+ if (tree)
328
+ await visit(tree);
329
+ return examination;
330
+ }
331
+ /** Whether a git root lies anywhere in the walked tree, the directory itself included. */
332
+ const holdsGitRoot = (d) => Boolean(d.gitRoot) || d.children.some(holdsGitRoot);
333
+ /** The nearest directory at or above `dir` that holds `.git`, if any. */
334
+ async function enclosingGitRoot(ctx, dir) {
335
+ for (let at = resolve(dir);; at = dirname(at)) {
336
+ const entries = await ctx.readDir(at).catch(() => []);
337
+ if (entries.some((e) => e.name === '.git'))
338
+ return at;
339
+ if (dirname(at) === at)
340
+ return undefined;
47
341
  }
48
- return { path, plexus, modules, findings };
49
- }
50
- /** The declarations that may satisfy a unit's dependencies: enclosing and contained ones (§ 1.4 PLX). */
51
- function contextOf(unit, units) {
52
- const { dir, ancestors } = unit;
53
- const context = [...ancestors, ...descendants(dir)];
54
- // The tenant: the repo's siblings. A unit inside a repo belongs to that repo; a repo is its own.
55
- const repo = ancestors[0] ?? dir;
56
- const repoParent = units.find((u) => u.dir === repo)?.parent;
57
- const siblings = repoParent?.children.filter((c) => c !== repo && c.declaration) ?? [];
58
- const isTenancy = (d) => d.declaration?.modules.includes('PLX-Tenancy') ?? false;
59
- context.push(...siblings.filter(isTenancy));
60
- if (isTenancy(dir))
61
- context.push(...siblings);
62
- return context;
63
- }
64
- function descendants(dir) {
65
- return dir.children.flatMap((c) => [...(c.declaration ? [c] : []), ...descendants(c)]);
66
- }
67
- /** Numeric comparison of two Plexus versions; suffixes ignored. */
68
- export function compareVersions(a, b) {
69
- const nums = (v) => v
70
- .split('.')
71
- .slice(0, 3)
72
- .map((p) => Number.parseInt(p, 10) || 0);
73
- const [x, y] = [nums(a), nums(b)];
74
- for (let i = 0; i < 3; i++)
75
- if ((x[i] ?? 0) !== (y[i] ?? 0))
76
- return (x[i] ?? 0) > (y[i] ?? 0) ? 1 : -1;
77
- return 0;
342
+ }
343
+ /** A repo and its apps, with paths relative to `base`. */
344
+ async function readUnits(ctx, dir, apps, base) {
345
+ const repo = await readRepo(ctx, dir, relative(base, dir.path) || '.', isOperations(dir) ? 'operations' : 'repo');
346
+ repo.apps = apps.map((path) => relative(dir.path, path));
347
+ const facts = [repo];
348
+ for (const path of apps)
349
+ facts.push(await readApp(ctx, await directoryAt(ctx, path), relative(base, path), relative(dir.path, path), repo));
350
+ return facts;
351
+ }
352
+ function markerOf(dir) {
353
+ if (dir.declaration)
354
+ return { declaration: dir.declaration };
355
+ const problem = dir.problems?.find((p) => p.startsWith(`${MARKER_FILE}: `));
356
+ return problem ? { problem } : undefined;
357
+ }
358
+ async function readRepo(ctx, dir, path, kind) {
359
+ const marker = markerOf(dir);
360
+ const tracked = await ctx
361
+ .read('git', ['ls-files', '-z'], { cwd: dir.path })
362
+ .then((out) => out.split('\0').filter(Boolean))
363
+ .catch((error) => {
364
+ if (error instanceof ExecError)
365
+ return undefined;
366
+ throw error;
367
+ });
368
+ return { kind, path, ...(marker ? { marker } : {}), tasks: await rootTasks(ctx, dir.path), tracked, apps: [] };
369
+ }
370
+ /**
371
+ * The repo's root mise tasks, hidden ones included, as mise lists them, so
372
+ * that tasks from every file mise reads count; a task counts under its name
373
+ * and each of its aliases, as `mise run` finds it by either. A task is the
374
+ * repo's when it is not global and either its `source` is under the repo or
375
+ * its `dir` is the repo's root: a file the repo includes from outside it
376
+ * (`[task_config] includes`) is named by its own path, outside, but its tasks
377
+ * run in the repo, while a parent directory's config gives its tasks the
378
+ * parent as their `dir`. mise names files and dirs by their canonical path,
379
+ * and an include as written (`<repo>/../shared/tasks.toml`), so the repo is
380
+ * compared canonically and the source once normalized. Whatever keeps the
381
+ * list from being read (no mise on PATH, an untrusted config, output without
382
+ * the `source` that tells the repo's tasks apart) is one problem, which
383
+ * PLX-Repo/Verbs reports.
384
+ */
385
+ async function rootTasks(ctx, repo) {
386
+ let out;
387
+ try {
388
+ out = await ctx.read('mise', ['tasks', 'ls', '--json', '--hidden'], { cwd: repo });
389
+ }
390
+ catch (error) {
391
+ if (error.code === 'ENOENT')
392
+ return { problem: 'mise is not on PATH' };
393
+ if (!(error instanceof ExecError))
394
+ return { problem: error.message };
395
+ const lines = error.stderr
396
+ .split('\n')
397
+ .map((l) => l.replace(/^mise ERROR /, '').trim())
398
+ .filter((l) => l && !/^(Version:|Run with )/.test(l));
399
+ return { problem: lines.join(' ') || error.message };
400
+ }
401
+ let tasks;
402
+ try {
403
+ tasks = JSON.parse(out);
404
+ }
405
+ catch {
406
+ return { problem: '`mise tasks ls --json` printed no JSON' };
407
+ }
408
+ if (!Array.isArray(tasks))
409
+ return { problem: '`mise tasks ls --json` printed no list' };
410
+ const listed = tasks.filter((t) => isMapping(t) && typeof t.name === 'string');
411
+ if (listed.some((t) => typeof t.source !== 'string'))
412
+ return { problem: "`mise tasks ls --json` gives no task's `source`, which tells the repo's own tasks apart" };
413
+ const roots = new Set([resolve(repo), await realpath(repo).catch(() => resolve(repo))]);
414
+ const under = (path) => [...roots].some((root) => path.startsWith(`${root}/`));
415
+ const isOwn = (task) => task.global !== true &&
416
+ (under(resolve(String(task.source))) || (typeof task.dir === 'string' && roots.has(resolve(task.dir))));
417
+ const names = [];
418
+ for (const task of listed) {
419
+ if (!isOwn(task))
420
+ continue;
421
+ const aliases = Array.isArray(task.aliases)
422
+ ? task.aliases.filter((a) => typeof a === 'string')
423
+ : [];
424
+ for (const name of [task.name, ...aliases]) {
425
+ // A monorepo root names its own tasks `//:<task>`; `//<project>:<task>` is a sub-project's.
426
+ if (name.startsWith('//:'))
427
+ names.push(name.slice(3));
428
+ else if (!name.startsWith('//'))
429
+ names.push(name);
430
+ }
431
+ }
432
+ return { names };
433
+ }
434
+ async function readApp(ctx, dir, path, inRepo, repo) {
435
+ const app = {
436
+ kind: 'app',
437
+ path,
438
+ repo,
439
+ dir: inRepo,
440
+ thirdParty: repo.kind === 'operations',
441
+ marker: markerOf(dir) ?? {},
442
+ dockerfile: (await ctx.readDir(join(dir.path, 'docker')).catch(() => [])).some((e) => e.name === 'Dockerfile' && !e.directory),
443
+ };
444
+ const compose = await ctx.readFile(join(dir.path, 'docker/compose.yaml')).catch(() => undefined);
445
+ if (compose !== undefined) {
446
+ try {
447
+ app.compose = parseCompose(compose, 'docker/compose.yaml');
448
+ }
449
+ catch (error) {
450
+ app.composeProblem = error.message;
451
+ }
452
+ }
453
+ const manifest = await ctx.readFile(join(dir.path, 'package.json')).catch(() => undefined);
454
+ if (manifest !== undefined) {
455
+ try {
456
+ const data = JSON.parse(manifest);
457
+ app.packageJson = isMapping(data) ? data : {};
458
+ }
459
+ catch {
460
+ app.packageJsonProblem = 'package.json is not JSON';
461
+ }
462
+ }
463
+ return app;
464
+ }
465
+ // --- compose's spellings -----------------------------------------------------------
466
+ /** The env files a service loads, by path, each with whether it is required (compose's default). */
467
+ function envFilesOf(service) {
468
+ const { env_file: files } = service;
469
+ const entries = files === undefined ? [] : Array.isArray(files) ? files : [files];
470
+ const loaded = new Map();
471
+ for (const entry of entries) {
472
+ const path = isMapping(entry) ? entry.path : entry;
473
+ if (typeof path !== 'string')
474
+ continue;
475
+ const required = isMapping(entry) && entry.required != null ? truthy(entry.required) : true;
476
+ loaded.set(path.replace(/^\.\//, ''), required);
477
+ }
478
+ return loaded;
479
+ }
480
+ const portsOf = (service) => (Array.isArray(service.ports) ? service.ports : []);
481
+ const renderPort = (port) => (isMapping(port) ? JSON.stringify(port) : String(port));
482
+ /** A short port spec's parts, `[ip:][host:]container[/protocol]`, split where no `${…}` is open. */
483
+ function partsOf(spec) {
484
+ const parts = [''];
485
+ let depth = 0;
486
+ for (const ch of spec.replace(/\/(tcp|udp)$/, '')) {
487
+ if (ch === '{')
488
+ depth++;
489
+ if (ch === '}')
490
+ depth--;
491
+ if (ch === ':' && depth === 0)
492
+ parts.push('');
493
+ else
494
+ parts[parts.length - 1] += ch;
495
+ }
496
+ return parts;
497
+ }
498
+ /** The host side of a published port: '' or undefined when compose picks one. */
499
+ function hostPortOf(port) {
500
+ if (isMapping(port))
501
+ return port.published == null ? undefined : String(port.published);
502
+ const parts = partsOf(String(port));
503
+ return parts.length >= 2 ? parts[parts.length - 2] : undefined;
504
+ }
505
+ /** The app service's port as the platform binds it: the loopback address, its host port, one container port, over TCP (HTTP). */
506
+ function isLoopback(port) {
507
+ if (isMapping(port))
508
+ return (port.host_ip === '127.0.0.1' &&
509
+ isLoopbackVar(String(port.published ?? '')) &&
510
+ /^\d+$/.test(String(port.target)) &&
511
+ (port.protocol == null || port.protocol === 'tcp'));
512
+ const spec = String(port);
513
+ const [ip, host, container, ...rest] = partsOf(spec);
514
+ return (ip === '127.0.0.1' &&
515
+ isLoopbackVar(host ?? '') &&
516
+ /^\d+$/.test(container ?? '') &&
517
+ rest.length === 0 &&
518
+ !spec.endsWith('/udp'));
78
519
  }
79
520
  //# sourceMappingURL=doctor.js.map