@metaobjectsdev/cli 1.0.2 → 1.0.4-rc.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 (115) hide show
  1. package/README.md +13 -5
  2. package/dist/src/commands/deps.d.ts +3 -0
  3. package/dist/src/commands/deps.d.ts.map +1 -0
  4. package/dist/src/commands/deps.js +200 -0
  5. package/dist/src/commands/deps.js.map +1 -0
  6. package/dist/src/commands/docs.d.ts.map +1 -1
  7. package/dist/src/commands/docs.js +19 -3
  8. package/dist/src/commands/docs.js.map +1 -1
  9. package/dist/src/commands/eject.d.ts +2 -1
  10. package/dist/src/commands/eject.d.ts.map +1 -1
  11. package/dist/src/commands/eject.js +235 -75
  12. package/dist/src/commands/eject.js.map +1 -1
  13. package/dist/src/commands/gen.d.ts.map +1 -1
  14. package/dist/src/commands/gen.js +173 -30
  15. package/dist/src/commands/gen.js.map +1 -1
  16. package/dist/src/commands/init.d.ts +5 -9
  17. package/dist/src/commands/init.d.ts.map +1 -1
  18. package/dist/src/commands/init.js +92 -402
  19. package/dist/src/commands/init.js.map +1 -1
  20. package/dist/src/commands/migrate.d.ts.map +1 -1
  21. package/dist/src/commands/migrate.js +24 -19
  22. package/dist/src/commands/migrate.js.map +1 -1
  23. package/dist/src/commands/prompt-snapshot.d.ts.map +1 -1
  24. package/dist/src/commands/prompt-snapshot.js +2 -1
  25. package/dist/src/commands/prompt-snapshot.js.map +1 -1
  26. package/dist/src/commands/verify.d.ts.map +1 -1
  27. package/dist/src/commands/verify.js +186 -29
  28. package/dist/src/commands/verify.js.map +1 -1
  29. package/dist/src/index.d.ts.map +1 -1
  30. package/dist/src/index.js +97 -15
  31. package/dist/src/index.js.map +1 -1
  32. package/dist/src/lib/advisory.d.ts +6 -0
  33. package/dist/src/lib/advisory.d.ts.map +1 -1
  34. package/dist/src/lib/advisory.js +10 -0
  35. package/dist/src/lib/advisory.js.map +1 -1
  36. package/dist/src/lib/agent-context-staleness.d.ts.map +1 -1
  37. package/dist/src/lib/agent-context-staleness.js +7 -1
  38. package/dist/src/lib/agent-context-staleness.js.map +1 -1
  39. package/dist/src/lib/args.d.ts +75 -3
  40. package/dist/src/lib/args.d.ts.map +1 -1
  41. package/dist/src/lib/args.js +54 -5
  42. package/dist/src/lib/args.js.map +1 -1
  43. package/dist/src/lib/catalog-listing.d.ts +92 -0
  44. package/dist/src/lib/catalog-listing.d.ts.map +1 -0
  45. package/dist/src/lib/catalog-listing.js +268 -0
  46. package/dist/src/lib/catalog-listing.js.map +1 -0
  47. package/dist/src/lib/catalog.d.ts +41 -0
  48. package/dist/src/lib/catalog.d.ts.map +1 -0
  49. package/dist/src/lib/catalog.js +89 -0
  50. package/dist/src/lib/catalog.js.map +1 -0
  51. package/dist/src/lib/collection-load-options.d.ts +13 -0
  52. package/dist/src/lib/collection-load-options.d.ts.map +1 -0
  53. package/dist/src/lib/collection-load-options.js +25 -0
  54. package/dist/src/lib/collection-load-options.js.map +1 -0
  55. package/dist/src/lib/dependency-sync.d.ts +170 -0
  56. package/dist/src/lib/dependency-sync.d.ts.map +1 -0
  57. package/dist/src/lib/dependency-sync.js +457 -0
  58. package/dist/src/lib/dependency-sync.js.map +1 -0
  59. package/dist/src/lib/install-set.d.ts +31 -0
  60. package/dist/src/lib/install-set.d.ts.map +1 -0
  61. package/dist/src/lib/install-set.js +103 -0
  62. package/dist/src/lib/install-set.js.map +1 -0
  63. package/dist/src/lib/library-eject.d.ts +79 -0
  64. package/dist/src/lib/library-eject.d.ts.map +1 -0
  65. package/dist/src/lib/library-eject.js +241 -0
  66. package/dist/src/lib/library-eject.js.map +1 -0
  67. package/dist/src/lib/library-listing.d.ts +63 -0
  68. package/dist/src/lib/library-listing.d.ts.map +1 -0
  69. package/dist/src/lib/library-listing.js +178 -0
  70. package/dist/src/lib/library-listing.js.map +1 -0
  71. package/dist/src/lib/library-prefix-advisory.d.ts +17 -0
  72. package/dist/src/lib/library-prefix-advisory.d.ts.map +1 -0
  73. package/dist/src/lib/library-prefix-advisory.js +67 -0
  74. package/dist/src/lib/library-prefix-advisory.js.map +1 -0
  75. package/dist/src/lib/load-metaobjects-config.d.ts +1 -2
  76. package/dist/src/lib/load-metaobjects-config.d.ts.map +1 -1
  77. package/dist/src/lib/load-metaobjects-config.js +11 -17
  78. package/dist/src/lib/load-metaobjects-config.js.map +1 -1
  79. package/dist/src/lib/migrate-scope.d.ts +32 -1
  80. package/dist/src/lib/migrate-scope.d.ts.map +1 -1
  81. package/dist/src/lib/migrate-scope.js +51 -3
  82. package/dist/src/lib/migrate-scope.js.map +1 -1
  83. package/dist/src/lib/overlay-lint.d.ts +37 -0
  84. package/dist/src/lib/overlay-lint.d.ts.map +1 -0
  85. package/dist/src/lib/overlay-lint.js +102 -0
  86. package/dist/src/lib/overlay-lint.js.map +1 -0
  87. package/dist/src/lib/requirement-check.d.ts +26 -3
  88. package/dist/src/lib/requirement-check.d.ts.map +1 -1
  89. package/dist/src/lib/requirement-check.js +71 -13
  90. package/dist/src/lib/requirement-check.js.map +1 -1
  91. package/package.json +10 -10
  92. package/src/commands/deps.ts +231 -0
  93. package/src/commands/docs.ts +19 -3
  94. package/src/commands/eject.ts +304 -90
  95. package/src/commands/gen.ts +189 -29
  96. package/src/commands/init.ts +95 -407
  97. package/src/commands/migrate.ts +26 -16
  98. package/src/commands/prompt-snapshot.ts +2 -1
  99. package/src/commands/verify.ts +213 -30
  100. package/src/index.ts +97 -15
  101. package/src/lib/advisory.ts +13 -0
  102. package/src/lib/agent-context-staleness.ts +7 -1
  103. package/src/lib/args.ts +118 -8
  104. package/src/lib/catalog-listing.ts +369 -0
  105. package/src/lib/catalog.ts +107 -0
  106. package/src/lib/collection-load-options.ts +42 -0
  107. package/src/lib/dependency-sync.ts +656 -0
  108. package/src/lib/install-set.ts +116 -0
  109. package/src/lib/library-eject.ts +298 -0
  110. package/src/lib/library-listing.ts +258 -0
  111. package/src/lib/library-prefix-advisory.ts +78 -0
  112. package/src/lib/load-metaobjects-config.ts +15 -21
  113. package/src/lib/migrate-scope.ts +59 -4
  114. package/src/lib/overlay-lint.ts +129 -0
  115. package/src/lib/requirement-check.ts +100 -14
@@ -0,0 +1,116 @@
1
+ // What a catalog entry costs to install — the one derivation behind both
2
+ // `meta gen --list --format json` and `meta eject --format json`.
3
+ //
4
+ // Two kinds of package, resolved two different ways:
5
+ //
6
+ // dev the `@metaobjectsdev/codegen-*` package the generator lives in. Its range
7
+ // is the CLI's own version: the engine and the CLI ship in lockstep, so a
8
+ // generator from a different minor is a version mismatch, not a choice.
9
+ // runtime the `@metaobjectsdev` runtime the EMITTED code imports, plus the
10
+ // third-party packages it imports. The runtime's range is the CLI's version
11
+ // for the same reason; the third-party RANGES are read from that runtime
12
+ // package's own `peerDependencies` and are never written here.
13
+ //
14
+ // That last rule is the point of this module. A second copy of a peer range in the CLI
15
+ // is a second thing to keep in step, and the failure mode of drift is an adopter
16
+ // installing a major nothing was tested against — the ERESOLVE trap FR-040 §4.4
17
+ // documented, closed by construction rather than by a warning. If a range cannot be
18
+ // read, the package is reported WITHOUT one rather than guessed at.
19
+
20
+ import { createRequire } from "node:module";
21
+ import { existsSync, readFileSync } from "node:fs";
22
+ import { dirname, join } from "node:path";
23
+ import type { GeneratorRegistryEntry } from "@metaobjectsdev/codegen-ts";
24
+ import { cliVersion } from "./version.js";
25
+ import { packageOf } from "./catalog.js";
26
+ import type { PackageManifest } from "./package-manifest.js";
27
+
28
+ /**
29
+ * A package's declared peer ranges, or `{}` if they cannot be read.
30
+ *
31
+ * Resolves the package's ENTRY and walks up to the nearest manifest, rather than asking
32
+ * for `"<pkg>/package.json"` directly. The direct form is the obvious one and it is
33
+ * WRONG: a package's `exports` map gates every subpath, and `@metaobjectsdev/runtime-ts`
34
+ * exports `.` / `./drivers` / `./fastify` / `./drizzle-fastify` / `./hono` and no
35
+ * `./package.json`, so under real Node it throws ERR_PACKAGE_PATH_NOT_EXPORTED. It
36
+ * appeared to work in-repo only because bun resolves a symlinked source tree; against
37
+ * the published package it failed silently on the first try. Resolving the entry is
38
+ * never gated — `.` is the one subpath every package exports.
39
+ */
40
+ export function peerRangesOf(packageName: string): Record<string, string> {
41
+ try {
42
+ const req = createRequire(import.meta.url);
43
+ let dir = dirname(req.resolve(packageName));
44
+ // The entry sits under dist/; the manifest is at the package root above it.
45
+ for (let hops = 0; hops < 8; hops++) {
46
+ const candidate = join(dir, "package.json");
47
+ if (existsSync(candidate)) {
48
+ const manifest = JSON.parse(readFileSync(candidate, "utf8")) as PackageManifest & {
49
+ name?: string;
50
+ };
51
+ // Guard against stopping at a nested manifest that is not the package itself.
52
+ if (manifest.name === packageName) {
53
+ return (manifest.peerDependencies ?? {}) as Record<string, string>;
54
+ }
55
+ }
56
+ const up = dirname(dir);
57
+ if (up === dir) break;
58
+ dir = up;
59
+ }
60
+ return {};
61
+ } catch {
62
+ return {};
63
+ }
64
+ }
65
+
66
+ export interface InstallSet {
67
+ /** Build-time packages, `name@range`. */
68
+ dev: string[];
69
+ /** Application-runtime packages, `name@range` (or bare `name` if no range is known). */
70
+ runtime: string[];
71
+ /** A paste-ready shell line, or "" when there is nothing to install. */
72
+ command: string;
73
+ }
74
+
75
+ function spec(name: string, range: string | undefined): string {
76
+ return range === undefined ? name : `${name}@${range}`;
77
+ }
78
+
79
+ /**
80
+ * The consolidated install set for a group of catalog entries.
81
+ *
82
+ * Consolidated, not per-entry: ejecting `hooks` and `grid` needs
83
+ * `@metaobjectsdev/codegen-ts-tanstack` ONCE, and an adopter handed the same package
84
+ * twice reasonably wonders which one to run.
85
+ */
86
+ export function installSetFor(entries: readonly GeneratorRegistryEntry[]): InstallSet {
87
+ const version = cliVersion();
88
+ const dev = new Set<string>();
89
+ const runtime = new Set<string>();
90
+
91
+ for (const entry of entries) {
92
+ const pkg = packageOf(entry.name);
93
+ if (pkg !== undefined) dev.add(spec(pkg, `^${version}`));
94
+
95
+ for (const rt of entry.runtimePackages ?? []) runtime.add(spec(rt, `^${version}`));
96
+
97
+ if (entry.runtimePeers !== undefined && entry.runtimePeers.length > 0) {
98
+ // Ranges come from whichever runtime package declares these as peers — the union
99
+ // over this generator's runtimes, since a generator emitting against two of them
100
+ // may take a peer from either. A generator with third-party peers but no runtime
101
+ // package of its own has none to read, so its peers are named UNPINNED: honest,
102
+ // and better than a made-up bound.
103
+ const ranges: Record<string, string> = {};
104
+ for (const rt of entry.runtimePackages ?? []) Object.assign(ranges, peerRangesOf(rt));
105
+ for (const peer of entry.runtimePeers) runtime.add(spec(peer, ranges[peer]));
106
+ }
107
+ }
108
+
109
+ const devList = [...dev].sort();
110
+ const runtimeList = [...runtime].sort();
111
+ const parts: string[] = [];
112
+ if (devList.length > 0) parts.push(`npm i -D ${devList.join(" ")}`);
113
+ if (runtimeList.length > 0) parts.push(`npm i ${runtimeList.join(" ")}`);
114
+
115
+ return { dev: devList, runtime: runtimeList, command: parts.join(" && ") };
116
+ }
@@ -0,0 +1,298 @@
1
+ // `meta eject <library>` — FR-043 §3.4, the copy door for a shipped library's METADATA.
2
+ //
3
+ // ADR-0034 ruled that a reference GENERATOR is copied into the adopter's repo because
4
+ // the adopter owns their code. §3.4 extends the same ruling to declared design, and
5
+ // makes it the EXPECTED mode rather than the fallback: a library is first a reference —
6
+ // something to copy, rename, and cut down. Using one in place, tracking upstream, is the
7
+ // deliberate minority choice.
8
+ //
9
+ // Two things follow, and both are here rather than in the generator path:
10
+ //
11
+ // The destination is `Collection.sourceRoots[0]` — the project's first DECLARED
12
+ // source root, resolved through `resolveCollection()`. Never `metaobjects/`: that
13
+ // string is the default value of `sources` and nothing else (CLAUDE.md names the five
14
+ // sites allowed to spell it, and this is not one of them).
15
+ //
16
+ // Every file carries a provenance header. It is what makes the copy's origin legible
17
+ // a year later, what `--list` reads to report staleness against the shipped tree, and
18
+ // what carries the ONE instruction that makes the eject complete: remove the library
19
+ // from `libraries`, or both trees load and merge (ERR_LIBRARY_PACKAGE_COLLISION).
20
+ import { mkdir, readFile, stat, writeFile } from "node:fs/promises";
21
+ import { basename, join } from "node:path";
22
+ import { MetaDataLoader, PACKAGE_SEPARATOR, canonicalSerialize, type MetaData } from "@metaobjectsdev/metadata";
23
+ import {
24
+ libraryManifests, libraryRefSource, libraryRefs, librarySources,
25
+ knownLibraryTokens, splitLayerToken,
26
+ } from "@metaobjectsdev/metadata/library";
27
+ import { resolveCollection } from "@metaobjectsdev/sdk";
28
+ import { cliVersion } from "./version.js";
29
+
30
+ /** The first line of every ejected file — the marker `--list` scans for. */
31
+ export const EJECT_MARKER = "# meta-eject:";
32
+
33
+ /** True when `name` is a shipped library rather than a generator. */
34
+ export function isLibraryName(name: string): boolean {
35
+ return name in libraryManifests();
36
+ }
37
+
38
+ /** Every shipped library name, sorted. */
39
+ export function ejectableLibraryNames(): string[] {
40
+ return Object.keys(libraryManifests()).sort();
41
+ }
42
+
43
+ /**
44
+ * Where an ejected ref lands: `meta.<library>.<file>.yaml`.
45
+ *
46
+ * Not the library's own basename. `model.yaml` / `db.yaml` / `requirements.yaml` are
47
+ * meaningful inside `library/iam/` and meaningless in a directory holding an
48
+ * application's whole model — and three libraries ejected into one root would collide
49
+ * outright. The `meta.<concept>.<...>` shape is the file-naming convention this project
50
+ * documents.
51
+ */
52
+ export function ejectedFileName(library: string, ref: string): string {
53
+ return `meta.${library}.${basename(ref)}.yaml`;
54
+ }
55
+
56
+ function header(library: string, ref: string): string {
57
+ return [
58
+ `${EJECT_MARKER} library=${library} ref=${ref} cli=${cliVersion()}`,
59
+ `# Copied from the MetaObjects shipped library "${library}". YOU OWN THIS FILE: rename`,
60
+ `# the package, delete what you do not need, change anything. Nothing regenerates it,`,
61
+ `# and no gate compares it to the shipped tree except \`meta eject --list\`.`,
62
+ `#`,
63
+ `# ONE STEP REMAINS: remove "${library}" (and any "${library}/<layer>") from`,
64
+ `# \`libraries\` in .metaobjects/config.json. Left there, the shipped tree and this`,
65
+ `# copy BOTH load and merge — additions take effect and deletions do not, because the`,
66
+ `# library still declares what you removed. The loader refuses that outright`,
67
+ `# (ERR_LIBRARY_PACKAGE_COLLISION) rather than letting it run.`,
68
+ "",
69
+ ].join("\n");
70
+ }
71
+
72
+ export interface EjectedLibraryFile {
73
+ ref: string;
74
+ /** Path relative to the project root. */
75
+ path: string;
76
+ status: "created" | "preserved" | "replaced";
77
+ }
78
+
79
+ export interface LibraryEjectResult {
80
+ library: string;
81
+ /** Absolute destination directory. */
82
+ root: string;
83
+ files: EjectedLibraryFile[];
84
+ /** The tokens for this library the project currently declares — what to remove. */
85
+ stillOptedIn: readonly string[];
86
+ }
87
+
88
+ async function fileExists(p: string): Promise<boolean> {
89
+ try {
90
+ return (await stat(p)).isFile();
91
+ } catch {
92
+ return false;
93
+ }
94
+ }
95
+
96
+ export async function ejectLibrary(opts: {
97
+ cwd: string;
98
+ name: string;
99
+ force?: boolean;
100
+ }): Promise<LibraryEjectResult> {
101
+ const manifest = libraryManifests()[opts.name];
102
+ if (manifest === undefined) {
103
+ throw new Error(
104
+ `unknown library "${opts.name}". Shipped libraries: ${ejectableLibraryNames().join(", ")}.`,
105
+ );
106
+ }
107
+ const collection = await resolveCollection(opts.cwd);
108
+ const root = collection.sourceRoots[0];
109
+ if (root === undefined) {
110
+ throw new Error(
111
+ `this project declares no metadata source root, so there is nowhere to put ` +
112
+ `"${opts.name}". Declare "sources" in .metaobjects/config.json, or run 'meta init'.`,
113
+ );
114
+ }
115
+
116
+ await mkdir(root, { recursive: true });
117
+ const files: EjectedLibraryFile[] = [];
118
+ for (const ref of libraryRefs(opts.name)) {
119
+ const text = header(opts.name, ref) + (await libraryRefSource(ref).read());
120
+ const name = ejectedFileName(opts.name, ref);
121
+ const abs = join(root, name);
122
+ const existed = await fileExists(abs);
123
+ if (existed && opts.force !== true) {
124
+ files.push({ ref, path: name, status: "preserved" });
125
+ continue;
126
+ }
127
+ await writeFile(abs, text, "utf8");
128
+ files.push({ ref, path: name, status: existed ? "replaced" : "created" });
129
+ }
130
+
131
+ return {
132
+ library: opts.name,
133
+ root,
134
+ files,
135
+ stillOptedIn: collection.libraries.filter((t) => splitLayerToken(t)[0] === opts.name),
136
+ };
137
+ }
138
+
139
+ // ---------------------------------------------------------------------------
140
+ // staleness — `meta eject --list`
141
+ // ---------------------------------------------------------------------------
142
+
143
+ export interface LibraryStaleness {
144
+ library: string;
145
+ /** Files in this project carrying the eject marker for this library. */
146
+ files: string[];
147
+ verdict: "identical" | "differs" | "unreadable";
148
+ /** Nodes present in both whose own-mode serialization differs. */
149
+ changed: number;
150
+ /** Nodes the SHIPPED tree has that the ejected copy does not — upstream moved. */
151
+ upstreamOnly: number;
152
+ /** Nodes the ejected copy has that the shipped tree does not — your additions. */
153
+ localOnly: number;
154
+ /** Why the comparison could not be made, when `verdict` is "unreadable". */
155
+ reason?: string;
156
+ /** Still named in `libraries` — the ejection is not finished. */
157
+ stillOptedIn: boolean;
158
+ }
159
+
160
+ /** The longest package prefix every node shares — the library's own root package.
161
+ *
162
+ * Segment-wise, never by string prefix: `acme::identity` and `acme::identityhub` share
163
+ * six characters and no package at all. */
164
+ function commonPackagePrefix(packages: readonly string[]): string {
165
+ if (packages.length === 0) return "";
166
+ let common = packages[0]!.split(PACKAGE_SEPARATOR);
167
+ for (const pkg of packages.slice(1)) {
168
+ const segments = pkg.split(PACKAGE_SEPARATOR);
169
+ let i = 0;
170
+ while (i < common.length && i < segments.length && common[i] === segments[i]) i++;
171
+ common = common.slice(0, i);
172
+ }
173
+ return common.join(PACKAGE_SEPARATOR);
174
+ }
175
+
176
+ /** Root-level nodes keyed by their package path RELATIVE to the library's own root
177
+ * package, canonically serialized in OWN mode.
178
+ *
179
+ * Relative rather than by resolution key, because §3.4 says an adopter who ejects "may
180
+ * rename the package freely" — keying on the FQN would report every node of a renamed
181
+ * copy as both upstream-only and local-only, which is the least useful answer
182
+ * available. Relative rather than by BARE NAME, because a library free to use two
183
+ * packages is free to declare `User` in both, and one key for two declarations means
184
+ * the one serialized last silently wins: a real divergence in the other is reported as
185
+ * `identical`. The relative path is what survives the rename — moving the root leaves
186
+ * every suffix below it exactly where it was — so it distinguishes without giving that
187
+ * edit anything to catch on. A single-package library yields the bare names it always
188
+ * did. Own mode, because the question is what each file DECLARES; the effective tree
189
+ * would fold a shipped base's fields into a subtype and report a difference that is not
190
+ * in either file. */
191
+ export function ownNodesByName(root: MetaData): Map<string, string> {
192
+ const nodes = [...root.children()];
193
+ const packageOf = (node: MetaData) => node.package ?? node.fileDefaultPackage ?? "";
194
+ // The ROOT package, neutralized in every node's serialization — for the same reason
195
+ // the keying is relative to it. A rename reaches the `package` key AND every `extends`
196
+ // inside the node, so comparing the raw text would report a renamed copy as wholly
197
+ // changed: the loudest possible answer to the one edit §3.4 explicitly invites. The
198
+ // root rather than each node's own package, so that a deeper node's reference back up
199
+ // to the root package is neutralized in it too.
200
+ const rootPackage = commonPackagePrefix(nodes.map(packageOf));
201
+
202
+ const out = new Map<string, string>();
203
+ for (const node of nodes) {
204
+ const pkg = packageOf(node);
205
+ const suffix =
206
+ rootPackage === "" ? pkg
207
+ : pkg === rootPackage ? ""
208
+ : pkg.slice(rootPackage.length + PACKAGE_SEPARATOR.length);
209
+ const key = suffix === "" ? node.name : `${suffix}${PACKAGE_SEPARATOR}${node.name}`;
210
+ const text = canonicalSerialize(node);
211
+ out.set(key, rootPackage === "" ? text : text.replaceAll(rootPackage, "<package>"));
212
+ }
213
+ return out;
214
+ }
215
+
216
+ /** Every project file carrying an eject marker, grouped by library. */
217
+ async function ejectedFilesByLibrary(files: readonly string[]): Promise<Map<string, string[]>> {
218
+ const out = new Map<string, string[]>();
219
+ for (const file of files) {
220
+ let head: string;
221
+ try {
222
+ head = (await readFile(file, "utf8")).slice(0, 400);
223
+ } catch {
224
+ continue;
225
+ }
226
+ const match = new RegExp(`^${EJECT_MARKER} library=(\\S+)`, "m").exec(head);
227
+ const library = match?.[1];
228
+ if (library === undefined) continue;
229
+ out.set(library, [...(out.get(library) ?? []), file]);
230
+ }
231
+ return out;
232
+ }
233
+
234
+ /**
235
+ * Per-library staleness for the copies THIS project owns.
236
+ *
237
+ * The same gap `--list` closes for generators, one level up: an ejected copy can sit any
238
+ * number of releases behind the tree it came from and nothing compares the two. The
239
+ * comparison is structural, through the canonical serializer, so re-indentation and key
240
+ * order never show up — the only thing that can be reported is a declaration that
241
+ * actually changed.
242
+ */
243
+ export async function libraryStaleness(cwd: string): Promise<LibraryStaleness[]> {
244
+ let collection;
245
+ try {
246
+ collection = await resolveCollection(cwd);
247
+ } catch {
248
+ return []; // no project — nothing is ejected here
249
+ }
250
+ const byLibrary = await ejectedFilesByLibrary(collection.ownFiles);
251
+ const selected = new Set(collection.libraries.map((t) => splitLayerToken(t)[0]));
252
+
253
+ const rows: LibraryStaleness[] = [];
254
+ for (const [library, files] of [...byLibrary].sort(([a], [b]) => a.localeCompare(b))) {
255
+ const row: LibraryStaleness = {
256
+ library,
257
+ files: files.map((f) => f.slice(cwd.length + 1)),
258
+ verdict: "identical",
259
+ changed: 0,
260
+ upstreamOnly: 0,
261
+ localOnly: 0,
262
+ stillOptedIn: selected.has(library),
263
+ };
264
+ if (!(library in libraryManifests())) {
265
+ rows.push({ ...row, verdict: "unreadable", reason: `this build ships no library "${library}"` });
266
+ continue;
267
+ }
268
+
269
+ // Both trees WHOLE, never file by file: a db layer is nothing but `overlay: true`
270
+ // redeclarations, so loading one alone is ERR_OVERLAY_NO_TARGET by construction.
271
+ const tokens = knownLibraryTokens().filter((t) => splitLayerToken(t)[0] === library);
272
+ const shipped = await new MetaDataLoader({ strict: true }).load(librarySources(tokens));
273
+ const { FileSource } = await import("@metaobjectsdev/metadata/core");
274
+ const local = await new MetaDataLoader({ strict: true }).load(
275
+ files.map((f) => new FileSource(f)),
276
+ );
277
+ if (local.errors.length > 0) {
278
+ rows.push({
279
+ ...row,
280
+ verdict: "unreadable",
281
+ reason: `the ejected copy does not load on its own: ${local.errors[0]!.message}`,
282
+ });
283
+ continue;
284
+ }
285
+
286
+ const up = ownNodesByName(shipped.root);
287
+ const mine = ownNodesByName(local.root);
288
+ for (const [name, text] of up) {
289
+ if (!mine.has(name)) row.upstreamOnly++;
290
+ else if (mine.get(name) !== text) row.changed++;
291
+ }
292
+ for (const name of mine.keys()) if (!up.has(name)) row.localOnly++;
293
+ row.verdict =
294
+ row.changed + row.upstreamOnly + row.localOnly === 0 ? "identical" : "differs";
295
+ rows.push(row);
296
+ }
297
+ return rows;
298
+ }
@@ -0,0 +1,258 @@
1
+ // `meta gen --list` — the LIBRARY rows (FR-043 §4).
2
+ //
3
+ // It is the codegen catalog, with `kind: "library"` rows in the same table rather than
4
+ // a parallel one: one door, one namespace, one `--probe`, one skill procedure. An agent
5
+ // about to model "users and permissions" should meet `iam` in the list it was already
6
+ // reading, not in a second command it has to know exists.
7
+ //
8
+ // THE ROW DESCRIBES THE BOX; THE PROJECT BLOCK DESCRIBES YOUR SHELF. `provides` counts
9
+ // what the library ships across ALL its layers — what you would get if you took every
10
+ // layer — while `project.tablesAdded` counts what YOUR selection actually put into the
11
+ // model. Those are different numbers whenever an adopter takes the core layer alone,
12
+ // which Amendment 1 makes the common case: `libraries: ["iam"]` provides nine entities
13
+ // and adds zero tables.
14
+ //
15
+ // Every fact here is COMPUTED — from the manifest, or by loading the library and
16
+ // counting. Nothing is a second copy of a sentence written somewhere else, which is the
17
+ // rule §4 states as "every manifest fact is resolved, not trusted".
18
+ import {
19
+ MetaDataLoader,
20
+ TYPE_OBJECT,
21
+ TYPE_REQUIREMENT,
22
+ OBJECT_SUBTYPE_ENTITY,
23
+ isWritableSource,
24
+ type MetaData,
25
+ } from "@metaobjectsdev/metadata";
26
+ import {
27
+ libraryManifests,
28
+ librarySources,
29
+ knownLibraryTokens,
30
+ splitLayerToken,
31
+ type LibraryManifest,
32
+ } from "@metaobjectsdev/metadata/library";
33
+ import { SERVER_LANGS } from "@metaobjectsdev/sdk";
34
+
35
+ /** One `--list` row for a shipped library. */
36
+ export interface LibraryCatalogRow {
37
+ name: string;
38
+ kind: "library";
39
+ /** The manifest's own `kind` — what SORT of library this is (`feature`, `nfr`). A
40
+ * second axis from the row's `kind`, which is the catalog discriminator. */
41
+ libraryKind: string;
42
+ stability: string;
43
+ /** The language ports this library is reachable from. Every port embeds the whole
44
+ * `library/` tree from one generator script, so this is all of them — and a test
45
+ * resolves that against each port's embedded module rather than trusting it. */
46
+ ports: readonly string[];
47
+ description: string;
48
+ useWhen?: string;
49
+ packages: readonly string[];
50
+ /** Selection tokens, core first — `["iam", "iam/db"]`. The bare name IS the core
51
+ * layer, and a layer token implies it. This is the field an adopter acts on: under
52
+ * Amendment 1 you do not opt into a library, you opt into its layers. */
53
+ layers: ReadonlyArray<{ token: string; description?: string }>;
54
+ /** What is in the box, across every layer. */
55
+ provides: {
56
+ entities: number;
57
+ abstracts: number;
58
+ requirements: number;
59
+ generators: readonly string[];
60
+ };
61
+ project?: LibraryProjectFacts;
62
+ }
63
+
64
+ export interface LibraryProjectFacts {
65
+ /** Does this project's `libraries` name this library at all? */
66
+ optedIn: boolean;
67
+ /** The tokens this project selected, in config order. Empty when not opted in. */
68
+ selectedLayers: readonly string[];
69
+ /** Project entities whose `extends` chain reaches a node this library owns — the
70
+ * adoption that opting out would break. `null` unless the model was loaded. */
71
+ extendedBy: readonly string[] | null;
72
+ /** Tables this library's SELECTED layers contribute to the loaded model. Zero for a
73
+ * core-only selection, which is the inertness promise expressed as a number. */
74
+ tablesAdded: number | null;
75
+ /** Requirement entries the library put into this project's ledger. */
76
+ requirementsAdded: number | null;
77
+ /** Generators the manifest says this library implies, which this project has not
78
+ * wired. Not an error: the library is metadata, and wiring is the adopter's call. */
79
+ impliedGeneratorsNotWired: readonly string[];
80
+ }
81
+
82
+ /** What a `--list` caller knows about the project, for the library rows. */
83
+ export interface LibraryProjectContext {
84
+ /** The project's `libraries` selection, verbatim. */
85
+ libraries: readonly string[];
86
+ /** Stable names wired in `generators: [...]`. */
87
+ wiredNames: ReadonlySet<string>;
88
+ /** The loaded model, when one was loaded (`--probe`). */
89
+ metadata?: MetaData;
90
+ }
91
+
92
+ /** Every selection token belonging to one library, core first. */
93
+ function tokensOf(name: string): string[] {
94
+ return knownLibraryTokens().filter((t) => splitLayerToken(t)[0] === name);
95
+ }
96
+
97
+ /** Walk every node, since a requirement nests to any depth and an object does not. */
98
+ function walk(node: MetaData, visit: (n: MetaData) => void): void {
99
+ for (const child of node.children()) {
100
+ visit(child);
101
+ walk(child, visit);
102
+ }
103
+ }
104
+
105
+ function effectivePackage(node: MetaData): string {
106
+ return node.package ?? node.fileDefaultPackage ?? "";
107
+ }
108
+
109
+ /**
110
+ * Load one library with ALL of its layers and count what it ships.
111
+ *
112
+ * The FULL selection, not the core: `provides` answers "what is in this library",
113
+ * and an adopter reading it is deciding whether to opt in at all. What their current
114
+ * selection actually added is the project block's job.
115
+ */
116
+ async function providesOf(name: string, manifest: LibraryManifest): Promise<LibraryCatalogRow["provides"]> {
117
+ const result = await new MetaDataLoader({ strict: true }).load(librarySources(tokensOf(name)));
118
+ let entities = 0;
119
+ let abstracts = 0;
120
+ let requirements = 0;
121
+ walk(result.root, (n) => {
122
+ if (n.type === TYPE_REQUIREMENT) requirements++;
123
+ else if (n.type === TYPE_OBJECT && n.subType === OBJECT_SUBTYPE_ENTITY) {
124
+ if (n.isAbstract) abstracts++;
125
+ else entities++;
126
+ }
127
+ });
128
+ return {
129
+ entities,
130
+ abstracts,
131
+ requirements,
132
+ generators: (manifest.generators ?? []).map((g) => g.name),
133
+ };
134
+ }
135
+
136
+ /**
137
+ * The project facts for one library.
138
+ *
139
+ * `extendedBy` and the two counts read the LOADED model rather than the library,
140
+ * because that is the question being answered: not "what does iam contain" but "what
141
+ * is iam doing in this repo". Without `--probe` there is no model and they are null —
142
+ * never zero, which would read as "nothing", the opposite of "not measured".
143
+ */
144
+ function projectFactsFor(
145
+ manifest: LibraryManifest,
146
+ ctx: LibraryProjectContext,
147
+ ): LibraryProjectFacts {
148
+ const name = manifest.name;
149
+ const selectedLayers = ctx.libraries.filter((t) => splitLayerToken(t)[0] === name);
150
+ const impliedGeneratorsNotWired = (manifest.generators ?? [])
151
+ .map((g) => g.name)
152
+ .filter((g) => !ctx.wiredNames.has(g));
153
+
154
+ const facts: LibraryProjectFacts = {
155
+ optedIn: selectedLayers.length > 0,
156
+ selectedLayers,
157
+ extendedBy: null,
158
+ tablesAdded: null,
159
+ requirementsAdded: null,
160
+ impliedGeneratorsNotWired,
161
+ };
162
+ if (ctx.metadata === undefined) return facts;
163
+
164
+ const owned = new Set(manifest.packages ?? []);
165
+ const extendedBy: string[] = [];
166
+ let tablesAdded = 0;
167
+ let requirementsAdded = 0;
168
+ walk(ctx.metadata, (n) => {
169
+ const mine = owned.has(effectivePackage(n));
170
+ if (n.type === TYPE_REQUIREMENT && mine) requirementsAdded++;
171
+ if (n.type !== TYPE_OBJECT) return;
172
+ if (mine) {
173
+ // A writable source is what migrate keys a CREATE TABLE off (#248 —
174
+ // persistability derives from source presence, never from the subtype), so
175
+ // counting them here and counting tables there cannot drift apart.
176
+ if (n.children().some(isWritableSource)) tablesAdded++;
177
+ return;
178
+ }
179
+ // A project entity reaching this library through `extends`, at any depth: the
180
+ // adoption an adopter would break by removing the library from `libraries`.
181
+ for (let sup = n.superData; sup !== undefined; sup = sup.superData) {
182
+ if (owned.has(effectivePackage(sup))) {
183
+ extendedBy.push(`${effectivePackage(n)}::${n.name}`);
184
+ return;
185
+ }
186
+ }
187
+ });
188
+
189
+ facts.extendedBy = extendedBy.sort();
190
+ facts.tablesAdded = tablesAdded;
191
+ facts.requirementsAdded = requirementsAdded;
192
+ return facts;
193
+ }
194
+
195
+ /** Every shipped library, as `--list` rows, in name order. */
196
+ export async function buildLibraryRows(
197
+ ctx?: LibraryProjectContext,
198
+ ): Promise<LibraryCatalogRow[]> {
199
+ const rows: LibraryCatalogRow[] = [];
200
+ for (const [name, manifest] of Object.entries(libraryManifests()).sort(([a], [b]) =>
201
+ a.localeCompare(b),
202
+ )) {
203
+ const layers = tokensOf(name).map((token) => {
204
+ const layer = (manifest.layers ?? {})[splitLayerToken(token)[1]];
205
+ return layer?.description === undefined
206
+ ? { token }
207
+ : { token, description: layer.description };
208
+ });
209
+ rows.push({
210
+ name,
211
+ kind: "library",
212
+ libraryKind: manifest.kind ?? "feature",
213
+ stability: manifest.stability ?? "preview",
214
+ ports: SERVER_LANGS,
215
+ description: manifest.description ?? "",
216
+ ...(manifest.useWhen !== undefined ? { useWhen: manifest.useWhen } : {}),
217
+ packages: manifest.packages ?? [],
218
+ layers,
219
+ provides: await providesOf(name, manifest),
220
+ ...(ctx === undefined ? {} : { project: projectFactsFor(manifest, ctx) }),
221
+ });
222
+ }
223
+ return rows;
224
+ }
225
+
226
+ function plural(n: number, one: string, many: string): string {
227
+ return `${n} ${n === 1 ? one : many}`;
228
+ }
229
+
230
+ /** The human rendering — one section, after the generator layers. */
231
+ export function renderLibraryText(rows: readonly LibraryCatalogRow[]): string[] {
232
+ if (rows.length === 0) return [];
233
+ const lines: string[] = [];
234
+ lines.push("");
235
+ lines.push("libraries — declared design you opt into, a LAYER at a time; the core layer adds no tables");
236
+ for (const r of rows) {
237
+ const marks: string[] = [r.stability];
238
+ if (r.project?.optedIn) marks.push(`opted in: ${r.project.selectedLayers.join(", ")}`);
239
+ if (r.project?.tablesAdded) marks.push(`${plural(r.project.tablesAdded, "table", "tables")} added`);
240
+ lines.push(` ${r.name} — ${r.description} [${marks.join(", ")}]`);
241
+ if (r.useWhen !== undefined) lines.push(` use when: ${r.useWhen}`);
242
+ lines.push(
243
+ ` provides: ${plural(r.provides.entities, "entity", "entities")}, ` +
244
+ `${r.provides.abstracts} abstract, ` +
245
+ `${plural(r.provides.requirements, "requirement", "requirements")}`,
246
+ );
247
+ lines.push(` layers: ${r.layers.map((l) => l.token).join(", ")}`);
248
+ if (r.project !== null && r.project?.impliedGeneratorsNotWired.length) {
249
+ lines.push(
250
+ ` implies: ${r.project.impliedGeneratorsNotWired.join(", ")} (not wired)`,
251
+ );
252
+ }
253
+ }
254
+ lines.push("");
255
+ lines.push('Opt in with `"libraries": ["iam", "iam/db"]` in .metaobjects/config.json —');
256
+ lines.push("the bare name is the core layer, and a layer token implies it.");
257
+ return lines;
258
+ }