@metaobjectsdev/codegen-ts 0.7.0-rc.8 → 0.7.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 (66) hide show
  1. package/dist/generator.d.ts +9 -0
  2. package/dist/generator.d.ts.map +1 -1
  3. package/dist/generator.js.map +1 -1
  4. package/dist/generators/docs-data-builder.d.ts +16 -0
  5. package/dist/generators/docs-data-builder.d.ts.map +1 -0
  6. package/dist/generators/docs-data-builder.js +381 -0
  7. package/dist/generators/docs-data-builder.js.map +1 -0
  8. package/dist/generators/docs-data.d.ts +98 -0
  9. package/dist/generators/docs-data.d.ts.map +1 -0
  10. package/dist/generators/docs-data.js +43 -0
  11. package/dist/generators/docs-data.js.map +1 -0
  12. package/dist/generators/docs-file.d.ts +8 -0
  13. package/dist/generators/docs-file.d.ts.map +1 -0
  14. package/dist/generators/docs-file.js +77 -0
  15. package/dist/generators/docs-file.js.map +1 -0
  16. package/dist/generators/index.d.ts +5 -0
  17. package/dist/generators/index.d.ts.map +1 -1
  18. package/dist/generators/index.js +4 -0
  19. package/dist/generators/index.js.map +1 -1
  20. package/dist/generators/routes-file-hono.d.ts +21 -0
  21. package/dist/generators/routes-file-hono.d.ts.map +1 -0
  22. package/dist/generators/routes-file-hono.js +38 -0
  23. package/dist/generators/routes-file-hono.js.map +1 -0
  24. package/dist/generators/template-generator.d.ts +41 -0
  25. package/dist/generators/template-generator.d.ts.map +1 -0
  26. package/dist/generators/template-generator.js +62 -0
  27. package/dist/generators/template-generator.js.map +1 -0
  28. package/dist/index.d.ts +6 -2
  29. package/dist/index.d.ts.map +1 -1
  30. package/dist/index.js +7 -1
  31. package/dist/index.js.map +1 -1
  32. package/dist/overwrite-policy.d.ts +39 -2
  33. package/dist/overwrite-policy.d.ts.map +1 -1
  34. package/dist/overwrite-policy.js +233 -13
  35. package/dist/overwrite-policy.js.map +1 -1
  36. package/dist/render-engine/framework-provider.d.ts +28 -0
  37. package/dist/render-engine/framework-provider.d.ts.map +1 -0
  38. package/dist/render-engine/framework-provider.js +104 -0
  39. package/dist/render-engine/framework-provider.js.map +1 -0
  40. package/dist/runner.d.ts +15 -1
  41. package/dist/runner.d.ts.map +1 -1
  42. package/dist/runner.js +44 -6
  43. package/dist/runner.js.map +1 -1
  44. package/dist/templates/docs-file.d.ts +17 -0
  45. package/dist/templates/docs-file.d.ts.map +1 -0
  46. package/dist/templates/docs-file.js +37 -0
  47. package/dist/templates/docs-file.js.map +1 -0
  48. package/dist/templates/routes-file-hono.d.ts +4 -0
  49. package/dist/templates/routes-file-hono.d.ts.map +1 -0
  50. package/dist/templates/routes-file-hono.js +119 -0
  51. package/dist/templates/routes-file-hono.js.map +1 -0
  52. package/package.json +6 -5
  53. package/src/generator.ts +9 -0
  54. package/src/generators/docs-data-builder.ts +470 -0
  55. package/src/generators/docs-data.ts +154 -0
  56. package/src/generators/docs-file.ts +87 -0
  57. package/src/generators/index.ts +17 -0
  58. package/src/generators/routes-file-hono.ts +48 -0
  59. package/src/generators/template-generator.ts +106 -0
  60. package/src/index.ts +33 -2
  61. package/src/overwrite-policy.ts +325 -14
  62. package/src/render-engine/framework-provider.ts +107 -0
  63. package/src/runner.ts +65 -6
  64. package/src/templates/docs-file.ts +51 -0
  65. package/src/templates/routes-file-hono.ts +142 -0
  66. package/templates/docs/entity-page.md.mustache +54 -0
@@ -0,0 +1,87 @@
1
+ // docsFile() — emits `<Entity>.md` next to each generated entity module.
2
+ //
3
+ // rc.12+: structured around a shared Mustache template at
4
+ // `templates/docs/entity-page.md.mustache` + a data builder at
5
+ // `docs-data-builder.ts`. Adopters can override the framework template by
6
+ // dropping their own `templates/docs/entity-page.md.mustache` into the
7
+ // project root (resolved via the project-then-framework provider chain).
8
+ //
9
+ // docsFile() calls `render()` directly rather than wrapping
10
+ // `templateGenerator()` because the per-entity output path depends on
11
+ // `GenContext.config.outputLayout`, which the generic templateGenerator
12
+ // `walk(root)` signature doesn't expose. Other future docs-style adopters
13
+ // with ctx-free walks (single-file aggregators, etc.) compose
14
+ // `templateGenerator()` directly.
15
+ //
16
+ // The conformance fixture (`fixtures/conformance/docs-file-basic`) gates
17
+ // byte-identity — the codegen output must match the hand-coded rc.11
18
+ // byte-for-byte. If you're hacking on this and the conformance test
19
+ // breaks, the refactor is the bug, not the fixture.
20
+
21
+ import type { MetaObject } from "@metaobjectsdev/metadata";
22
+ import { render } from "@metaobjectsdev/render";
23
+ import type { Generator, GeneratorFactory } from "../generator.js";
24
+ import { entityOutputPath } from "../import-path.js";
25
+ import { projectProvider } from "../render-engine/framework-provider.js";
26
+ import { buildEntityDocData } from "./docs-data-builder.js";
27
+
28
+ export interface DocsFileOpts {
29
+ filter?: (entity: MetaObject) => boolean;
30
+ target?: string;
31
+ }
32
+
33
+ /** The names of the generators that may emit sibling files for an entity.
34
+ * We always list them in the "Generated code" section — adopters cross-
35
+ * reference their own metaobjects.config.ts to confirm which are wired in.
36
+ * Matches the rc.11 behavior. */
37
+ const KNOWN_SIBLING_GENERATORS = new Set([
38
+ "queries-file",
39
+ "routes-file",
40
+ "routes-file-hono",
41
+ ]);
42
+
43
+ const TEMPLATE_REF = "docs/entity-page.md";
44
+
45
+ export const docsFile = function docsFile(opts?: DocsFileOpts): Generator {
46
+ const generator: Generator = {
47
+ name: "docs-file",
48
+ async generate(ctx) {
49
+ if (!ctx.renderContext) {
50
+ throw new Error("docs-file: renderContext is required (provided by runGen)");
51
+ }
52
+ const rc = ctx.renderContext;
53
+ const provider = projectProvider(ctx.projectRoot ?? process.cwd());
54
+ const layout = ctx.config.outputLayout ?? "flat";
55
+ return ctx.loadedRoot.objects().filter(ctx.matches).map((entity: MetaObject) => {
56
+ const path = entityOutputPath(layout, entity.package, `${entity.name}.md`);
57
+ const payload = buildEntityDocData(entity, {
58
+ dialect: rc.dialect,
59
+ ...(rc.columnNamingStrategy !== undefined && {
60
+ columnNamingStrategy: rc.columnNamingStrategy,
61
+ }),
62
+ loadedRoot: rc.loadedRoot,
63
+ generatorNames: KNOWN_SIBLING_GENERATORS,
64
+ });
65
+ let content: string;
66
+ try {
67
+ content = render({
68
+ ref: TEMPLATE_REF,
69
+ payload,
70
+ provider,
71
+ format: "markdown",
72
+ });
73
+ } catch (err) {
74
+ const msg = err instanceof Error ? err.message : String(err);
75
+ throw new Error(
76
+ `docs-file: failed rendering '${TEMPLATE_REF}' for '${path}': ${msg}`,
77
+ { cause: err instanceof Error ? err : undefined },
78
+ );
79
+ }
80
+ return { path, content };
81
+ });
82
+ },
83
+ };
84
+ if (opts?.filter) generator.filter = opts.filter;
85
+ if (opts?.target) generator.target = opts.target;
86
+ return generator;
87
+ } as GeneratorFactory<DocsFileOpts>;
@@ -1,7 +1,24 @@
1
1
  export { entityFile, type EntityFileOpts } from "./entity-file.js";
2
2
  export { queriesFile, type QueriesFileOpts } from "./queries-file.js";
3
3
  export { routesFile, type RoutesFileOpts } from "./routes-file.js";
4
+ export { routesFileHono, type RoutesFileHonoOpts } from "./routes-file-hono.js";
4
5
  export { barrel, type BarrelOpts } from "./barrel.js";
5
6
  export { mermaidErDiagram, type MermaidErOptions } from "./mermaid-er.js";
6
7
  export { promptRender, type PromptRenderOpts } from "./prompt-render-file.js";
7
8
  export { outputParser, type OutputParserOpts } from "./output-parser-file.js";
9
+ export { docsFile, type DocsFileOpts } from "./docs-file.js";
10
+ export {
11
+ templateGenerator,
12
+ type TemplateGeneratorOpts,
13
+ type TemplateWalkResult,
14
+ type TemplateFormat,
15
+ } from "./template-generator.js";
16
+ export type {
17
+ EntityDocData,
18
+ StorageFieldDoc,
19
+ IdentityDoc,
20
+ RelationshipDoc,
21
+ UsedByDoc,
22
+ GeneratedFileDoc,
23
+ } from "./docs-data.js";
24
+ export { buildEntityDocData } from "./docs-data-builder.js";
@@ -0,0 +1,48 @@
1
+ import type { MetaObject } from "@metaobjectsdev/metadata";
2
+ import { perEntity, type Generator, type GeneratorFactory } from "../generator.js";
3
+ import { renderRoutesFileHono } from "../templates/routes-file-hono.js";
4
+ import { formatTs } from "../format.js";
5
+ import { entityOutputPath } from "../import-path.js";
6
+
7
+ export interface RoutesFileHonoOpts {
8
+ filter?: (entity: MetaObject) => boolean;
9
+ target?: string;
10
+ }
11
+
12
+ /**
13
+ * Hono variant of routesFile() — emits `<Entity>.routes.hono.ts` mounting
14
+ * the same five CRUD verbs (GET list / GET :id / POST / PATCH+PUT / DELETE)
15
+ * against `@metaobjectsdev/runtime-ts/hono` rather than `…/drizzle-fastify`.
16
+ *
17
+ * Same cross-port wire contract (envelope shape, status codes, filter +
18
+ * sort + withCount semantics) as the Fastify flavor. Workers / Bun / Node
19
+ * consumers running Hono can replace hand-written route registration with
20
+ * this generator output one entity at a time.
21
+ *
22
+ * Per-entity opt-out via `@emitRoutes: false` is honored. If the user
23
+ * supplies their own filter, both must pass (AND).
24
+ */
25
+ export const routesFileHono = function routesFileHono(opts?: RoutesFileHonoOpts): Generator {
26
+ const userFilter = opts?.filter ?? (() => true);
27
+ const generator: Generator = {
28
+ name: "routes-file-hono",
29
+ filter: (e: MetaObject) => e.ownAttr("emitRoutes") !== false && userFilter(e),
30
+ generate: perEntity(async (entity, ctx) => {
31
+ if (!ctx.renderContext) {
32
+ throw new Error("routes-file-hono: renderContext is required (provided by runGen)");
33
+ }
34
+ return {
35
+ path: entityOutputPath(
36
+ ctx.config.outputLayout ?? "flat",
37
+ entity.package,
38
+ `${entity.name}.routes.hono.ts`,
39
+ ),
40
+ content: await formatTs(renderRoutesFileHono(entity, ctx.renderContext)),
41
+ };
42
+ }),
43
+ };
44
+ if (opts?.target) {
45
+ generator.target = opts.target;
46
+ }
47
+ return generator;
48
+ } as GeneratorFactory<RoutesFileHonoOpts>;
@@ -0,0 +1,106 @@
1
+ // templateGenerator() — the missing primitive identified by the
2
+ // template-driven-codegen design (2026-05-28). Walks the loaded MetaRoot
3
+ // → renders shared Mustache templates via @metaobjectsdev/render → emits
4
+ // EmittedFile[]. Same Generator interface as the per-port hand-coded
5
+ // generators; just adds the "Mustache template" + "walk that yields a
6
+ // data dict per output" primitives.
7
+ //
8
+ // Design line we adopted (from the design doc):
9
+ // Code → hand-coded generators (ts-poet, idiomatic per-port).
10
+ // Documents → templateGenerator (shared Mustache templates).
11
+ //
12
+ // docsFile() is the first templateGenerator instance (rc.12). OpenAPI specs,
13
+ // Mermaid diagrams, HTML doc sites, etc. follow as templates + a walk
14
+ // function each.
15
+
16
+ import type { MetaRoot, MetaObject } from "@metaobjectsdev/metadata";
17
+ import { render, type Provider, type RenderFormat } from "@metaobjectsdev/render";
18
+ import type { Generator, GenContext, EmittedFile, GeneratorFactory } from "../generator.js";
19
+ import { projectProvider } from "../render-engine/framework-provider.js";
20
+
21
+ export type TemplateFormat = RenderFormat;
22
+
23
+ export interface TemplateWalkResult {
24
+ /** The data dict to render against. Templates reference its keys; the
25
+ * shape is the public-API contract template authors consume. */
26
+ data: object;
27
+ /** Output path RELATIVE to the generator's target outDir. */
28
+ outputPath: string;
29
+ }
30
+
31
+ export interface TemplateGeneratorOpts {
32
+ /** kebab-case identifier; surfaces in diagnostics and the overwrite-policy
33
+ * per-file snapshot key. */
34
+ name: string;
35
+ /** Walk the loaded metadata tree and produce `{ data, outputPath }` tuples
36
+ * — one per emitted file. Pattern A (per-entity), pattern B (single
37
+ * aggregator), pattern C (mixed), pattern D (filter inline) all fit. */
38
+ walk: (root: MetaRoot) => TemplateWalkResult[] | Promise<TemplateWalkResult[]>;
39
+ /** Template reference. Resolved by the configured Provider chain — by
40
+ * default the project's `templates/<ref>.mustache` first, then the
41
+ * framework defaults at `codegen-ts/templates/<ref>.mustache`. */
42
+ template: string;
43
+ /** Drives the render engine's escaper. Defaults to "text". */
44
+ format?: TemplateFormat;
45
+ /** Optional per-entity filter for adopters who want to scope a generator
46
+ * via the standard `Generator.filter` plumbing. Not consulted by the
47
+ * default `walk` — adopters apply filters inside their walk function. */
48
+ filter?: (entity: MetaObject) => boolean;
49
+ /** Override the Provider used for template resolution. When omitted the
50
+ * generator resolves via `projectProvider(ctx.projectRoot)`, which layers
51
+ * the project's `templates/` over the framework defaults. (The project
52
+ * root is the directory holding `.metaobjects/config.json`, threaded
53
+ * through `GenContext` by the runner. Adopters needing a different
54
+ * lookup chain can pass an explicit provider.) */
55
+ provider?: Provider;
56
+ /** Optional named target — same as the other generators. */
57
+ target?: string;
58
+ }
59
+
60
+ export const templateGenerator = function templateGenerator(
61
+ opts: TemplateGeneratorOpts,
62
+ ): Generator {
63
+ const fmt: TemplateFormat = opts.format ?? "text";
64
+ const generator: Generator = {
65
+ name: opts.name,
66
+ async generate(ctx: GenContext): Promise<EmittedFile[]> {
67
+ let provider: Provider;
68
+ if (opts.provider !== undefined) {
69
+ provider = opts.provider;
70
+ } else if (ctx.projectRoot !== undefined) {
71
+ provider = projectProvider(ctx.projectRoot);
72
+ } else {
73
+ ctx.warn(
74
+ "templateGenerator: ctx.projectRoot is undefined; falling back to process.cwd() for project-template resolution. " +
75
+ "Project-scoped template overrides will resolve relative to the current working directory, which is fragile under " +
76
+ "`meta gen` invoked from a sub-directory. Drive via runGen(opts.projectRoot) to remove this warning.",
77
+ );
78
+ provider = projectProvider(process.cwd());
79
+ }
80
+ const walkRes = await opts.walk(ctx.loadedRoot);
81
+ const files: EmittedFile[] = [];
82
+ for (const { data, outputPath } of walkRes) {
83
+ let content: string;
84
+ try {
85
+ content = render({
86
+ ref: opts.template,
87
+ payload: data,
88
+ provider,
89
+ format: fmt,
90
+ });
91
+ } catch (err) {
92
+ const msg = err instanceof Error ? err.message : String(err);
93
+ throw new Error(
94
+ `templateGenerator(${opts.name}) failed rendering '${opts.template}' for '${outputPath}': ${msg}`,
95
+ { cause: err instanceof Error ? err : undefined },
96
+ );
97
+ }
98
+ files.push({ path: outputPath, content });
99
+ }
100
+ return files;
101
+ },
102
+ };
103
+ if (opts.filter) generator.filter = opts.filter;
104
+ if (opts.target) generator.target = opts.target;
105
+ return generator;
106
+ } as GeneratorFactory<TemplateGeneratorOpts>;
package/src/index.ts CHANGED
@@ -24,8 +24,14 @@ export { buildRelationMap } from "./relation-resolver.js";
24
24
  export type { RenderContext } from "./render-context.js";
25
25
  export { makeRenderContext } from "./render-context.js";
26
26
 
27
- export type { WriteStatus, WriteResult, MergeStrategy } from "./overwrite-policy.js";
28
- export { decideAndWrite } from "./overwrite-policy.js";
27
+ export type {
28
+ WriteStatus,
29
+ WriteResult,
30
+ MergeStrategy,
31
+ BaselineMode,
32
+ DecideAndWriteOpts,
33
+ } from "./overwrite-policy.js";
34
+ export { decideAndWrite, GitMissingError } from "./overwrite-policy.js";
29
35
 
30
36
  export { CodegenError } from "./errors.js";
31
37
  export { GENERATED_HEADER, EXTRA_SUFFIX, DEFAULT_OUT_DIR } from "./constants.js";
@@ -45,3 +51,28 @@ export type { EmitOptions as ViewDdlEmitOptions } from "./projection/view-ddl-em
45
51
  export type { JoinNode, JoinTree, SelectColumn, SelectSpec, ViewSpec } from "./projection/view-spec.js";
46
52
  // Prompt construction (FR-004): typed payload + render-handle codegen.
47
53
  export { generatePayloadInterfaces, generatePayloadInterfacesBatch, generateRenderHandle } from "./payload-codegen.js";
54
+
55
+ // Template-driven codegen (rc.12). Factory + framework Provider for adopters
56
+ // who want to wire their own templateGenerator instances. The default
57
+ // docsFile() uses this internally.
58
+ export {
59
+ templateGenerator,
60
+ type TemplateGeneratorOpts,
61
+ type TemplateWalkResult,
62
+ type TemplateFormat,
63
+ } from "./generators/template-generator.js";
64
+ export {
65
+ FileSystemProvider,
66
+ ProviderChain,
67
+ frameworkTemplatesProvider,
68
+ projectProvider,
69
+ } from "./render-engine/framework-provider.js";
70
+ export type {
71
+ EntityDocData,
72
+ StorageFieldDoc,
73
+ IdentityDoc,
74
+ RelationshipDoc,
75
+ UsedByDoc,
76
+ GeneratedFileDoc,
77
+ } from "./generators/docs-data.js";
78
+ export { buildEntityDocData } from "./generators/docs-data-builder.js";
@@ -1,39 +1,350 @@
1
- // Overwrite policy: drives the per-file write decision based on the @generated header.
2
- // Per design §8 read-only generated files; refuse to clobber hand-written code.
1
+ // Overwrite policy: per-file write decision using three-way merge against a
2
+ // canonical snapshot kept under `.metaobjects/.gen-state/`.
3
+ //
4
+ // Replaces the rc.11 marker-based clobber-or-refuse policy (strategy (a) from
5
+ // spike 002) with strategy (b) — git-merge-file-driven three-way merge. The
6
+ // `@generated` marker becomes purely informational (templates may still emit
7
+ // it for human readers); the policy no longer consults it.
8
+ //
9
+ // Per-file flow:
10
+ //
11
+ // 1. Render fresh content to a tmpfile.
12
+ // 2. If the output doesn't exist → write + copy to .gen-state/.
13
+ // 3. If .gen-state/<relPath> exists → run `git merge-file --diff3` against
14
+ // (current, .gen-state snapshot, fresh tmpfile). Exit 0 → clean merge,
15
+ // advance .gen-state to fresh content. Exit > 0 → leave conflict markers
16
+ // in the output file, do NOT advance .gen-state; status "conflict".
17
+ // 4. If .gen-state/<relPath> is absent but the file exists ("first-time
18
+ // regen on an existing file") → write-if-different against the existing
19
+ // file as the baseline (no merge, no clobber). The `baseline: "fresh"`
20
+ // flag opts into "overwrite from fresh and re-baseline".
21
+ //
22
+ // Integrity (caveat 2 from the spike): we keep a sha-256 of each canonical
23
+ // snapshot at `.gen-state/.hashes.json`. On load, mismatch → fall back to
24
+ // first-time semantics and warn naming the file so the user can investigate.
3
25
 
4
- import { existsSync, readFileSync, writeFileSync, mkdirSync } from "node:fs";
5
- import { dirname } from "node:path";
6
- import { GENERATED_HEADER } from "./constants.js";
26
+ import {
27
+ existsSync,
28
+ readFileSync,
29
+ writeFileSync,
30
+ mkdirSync,
31
+ copyFileSync,
32
+ } from "node:fs";
33
+ import { dirname, join, isAbsolute, relative, resolve } from "node:path";
34
+ import { spawnSync } from "node:child_process";
35
+ import { tmpdir } from "node:os";
36
+ import { createHash, randomBytes } from "node:crypto";
7
37
 
8
- export type WriteStatus = "new" | "overwrite" | "refused" | "skipped";
38
+ export type WriteStatus =
39
+ | "new"
40
+ | "unchanged"
41
+ | "overwrite"
42
+ | "merged"
43
+ | "conflict"
44
+ | "refused"
45
+ | "skipped";
46
+
47
+ /**
48
+ * "overwrite" — default; three-way merge if .gen-state exists, else write-if-
49
+ * different / first-time-existing flow.
50
+ * "skip-existing" — never write over an existing file; status "skipped".
51
+ * Useful for `meta gen --dry-run` style flows.
52
+ */
9
53
  export type MergeStrategy = "overwrite" | "skip-existing";
10
54
 
55
+ /** "default" — the standard three-way merge flow described in the file header.
56
+ * "fresh" — opt-in via `meta gen --baseline=fresh`. When .gen-state is absent
57
+ * but the file exists, OVERWRITE with fresh content and seed .gen-state from
58
+ * the fresh content (caveat 3 escape hatch). */
59
+ export type BaselineMode = "default" | "fresh";
60
+
61
+ export interface DecideAndWriteOpts {
62
+ strategy?: MergeStrategy;
63
+ /** Absolute path to the .gen-state/ root for this project. When undefined,
64
+ * we fall back to a process-isolated tmpdir — fine for tests but the CLI
65
+ * always supplies the real project value via runGen(). */
66
+ genStateDir?: string;
67
+ /** Path the snapshot is keyed by — usually the path relative to the
68
+ * project root, but ANY stable identifier works. When undefined, derived
69
+ * from `path` (so unit tests can call without supplying it). */
70
+ outputRelPath?: string;
71
+ /** First-time-existing-file behavior. */
72
+ baseline?: BaselineMode;
73
+ }
74
+
11
75
  export interface WriteResult {
12
76
  path: string;
13
77
  status: WriteStatus;
78
+ /** Present when status is "conflict" — human-readable hint identifying the
79
+ * file the user must resolve. */
80
+ conflictHint?: string;
81
+ }
82
+
83
+ const HASHES_FILE = ".hashes.json";
84
+
85
+ type HashesFile = Record<string, string>;
86
+
87
+ function sha256(content: string | Buffer): string {
88
+ return createHash("sha256").update(content).digest("hex");
89
+ }
90
+
91
+ function loadHashes(genStateDir: string): HashesFile {
92
+ const f = join(genStateDir, HASHES_FILE);
93
+ if (!existsSync(f)) return {};
94
+ try {
95
+ const txt = readFileSync(f, "utf-8");
96
+ const parsed: unknown = JSON.parse(txt);
97
+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
98
+ return parsed as HashesFile;
99
+ }
100
+ return {};
101
+ } catch {
102
+ return {};
103
+ }
14
104
  }
15
105
 
106
+ function saveHashes(genStateDir: string, hashes: HashesFile): void {
107
+ mkdirSync(genStateDir, { recursive: true });
108
+ writeFileSync(join(genStateDir, HASHES_FILE), JSON.stringify(hashes, null, 2) + "\n");
109
+ }
110
+
111
+ function snapshotPath(genStateDir: string, relPath: string): string {
112
+ // `.hashes.json` is reserved at the top of .gen-state/; relPath must never
113
+ // collide with it. Output paths derived from entity names ("Post.ts" etc.)
114
+ // are JS-identifier-shape so this is a non-issue in practice.
115
+ return join(genStateDir, relPath);
116
+ }
117
+
118
+ /** Synchronously copy `src` content into the snapshot at `<genStateDir>/<relPath>`
119
+ * and refresh the hash for `relPath`. */
120
+ function advanceSnapshot(
121
+ genStateDir: string,
122
+ relPath: string,
123
+ content: string,
124
+ ): void {
125
+ const dest = snapshotPath(genStateDir, relPath);
126
+ mkdirSync(dirname(dest), { recursive: true });
127
+ writeFileSync(dest, content);
128
+ const hashes = loadHashes(genStateDir);
129
+ hashes[relPath] = sha256(content);
130
+ saveHashes(genStateDir, hashes);
131
+ }
132
+
133
+ /** Return the snapshot text iff present AND the hash matches; else undefined. */
134
+ function readSnapshotChecked(
135
+ genStateDir: string,
136
+ relPath: string,
137
+ ): { text: string } | undefined {
138
+ const path = snapshotPath(genStateDir, relPath);
139
+ if (!existsSync(path)) return undefined;
140
+ const text = readFileSync(path, "utf-8");
141
+ const hashes = loadHashes(genStateDir);
142
+ const expected = hashes[relPath];
143
+ if (expected !== undefined && expected !== sha256(text)) {
144
+ return undefined;
145
+ }
146
+ return { text };
147
+ }
148
+
149
+ /** Thrown when git is unavailable. Surfaces as a clear CLI error rather than
150
+ * a generic ENOENT halfway through a regen. */
151
+ export class GitMissingError extends Error {
152
+ constructor() {
153
+ super(
154
+ "meta gen: `git` binary not found on PATH. Three-way-merge regen " +
155
+ "requires git (any modern version). Install git and re-run.",
156
+ );
157
+ this.name = "GitMissingError";
158
+ }
159
+ }
160
+
161
+ interface MergeOutcome {
162
+ /** 0 → clean merge; > 0 → conflicts present (file contains diff3 markers). */
163
+ exitCode: number;
164
+ /** stderr text — surfaced on unexpected errors. */
165
+ stderr: string;
166
+ /** Resulting file contents on disk after the merge (always read; clean or
167
+ * conflicting). */
168
+ mergedContent: string;
169
+ }
170
+
171
+ /** Run `git merge-file --diff3 -L<...> <out> <base> <fresh>`. The output is
172
+ * written in-place into `outPath`. Returns the exit code (0 = clean, > 0 =
173
+ * conflicts) and the resulting file contents.
174
+ *
175
+ * The git binary is "git" by default; set `META_GEN_GIT` in the environment
176
+ * to a different path (useful for tests that simulate "git not installed"). */
177
+ function runGitMergeFile(
178
+ outPath: string,
179
+ basePath: string,
180
+ freshPath: string,
181
+ ): MergeOutcome {
182
+ const gitBin = process.env.META_GEN_GIT ?? "git";
183
+ let res;
184
+ try {
185
+ res = spawnSync(
186
+ gitBin,
187
+ [
188
+ "merge-file",
189
+ "--diff3",
190
+ "-L",
191
+ "your edits",
192
+ "-L",
193
+ "last generated",
194
+ "-L",
195
+ "fresh from meta gen",
196
+ outPath,
197
+ basePath,
198
+ freshPath,
199
+ ],
200
+ { encoding: "utf-8" },
201
+ );
202
+ } catch (err) {
203
+ const msg = (err as Error).message ?? "";
204
+ if (msg.includes("ENOENT")) throw new GitMissingError();
205
+ throw err;
206
+ }
207
+ if (res.error) {
208
+ const code = (res.error as NodeJS.ErrnoException).code;
209
+ if (code === "ENOENT") throw new GitMissingError();
210
+ throw res.error;
211
+ }
212
+ // `git merge-file` returns the conflict count (0 = clean, > 0 = conflicts,
213
+ // < 0 = error). Negative is unexpected — surface verbatim.
214
+ const exitCode = res.status ?? 0;
215
+ if (exitCode < 0) {
216
+ throw new Error(
217
+ `git merge-file failed for ${outPath}: ${res.stderr || res.stdout}`,
218
+ );
219
+ }
220
+ const mergedContent = readFileSync(outPath, "utf-8");
221
+ return { exitCode, stderr: res.stderr ?? "", mergedContent };
222
+ }
223
+
224
+ /** Write `content` to a freshly-named tmpfile under the OS tmpdir; return the
225
+ * path. Caller is responsible for cleanup (acceptable for codegen — tmpdir
226
+ * is process-scoped). */
227
+ function writeTmpfile(content: string): string {
228
+ const dir = join(tmpdir(), "meta-gen-merge");
229
+ mkdirSync(dir, { recursive: true });
230
+ const path = join(dir, `${Date.now()}-${randomBytes(6).toString("hex")}.tmp`);
231
+ writeFileSync(path, content);
232
+ return path;
233
+ }
234
+
235
+ /** Resolve the snapshot key for a given output path. Falls back to a stable
236
+ * hash-of-path so unit tests that pass arbitrary tmpdir outputs still get a
237
+ * consistent .gen-state key. */
238
+ function defaultOutputRelPath(outputPath: string): string {
239
+ // Use sha256 of the absolute path → hex; lets tests work without supplying
240
+ // an explicit relPath. NOT used by the runner — runGen always passes the
241
+ // real project-relative path.
242
+ return sha256(resolve(outputPath)).slice(0, 32);
243
+ }
244
+
245
+ /**
246
+ * The main entry point. Backward-compatible with the rc.11 signature: passing
247
+ * a `MergeStrategy` string as the third argument continues to work; passing
248
+ * an options object opts into three-way merge.
249
+ */
16
250
  export function decideAndWrite(
17
251
  path: string,
18
252
  content: string,
19
- strategy: MergeStrategy = "overwrite",
253
+ optsOrStrategy: DecideAndWriteOpts | MergeStrategy = {},
20
254
  ): WriteResult {
21
- // 'skip-existing' only skips overwrites, not new files.
255
+ const opts: DecideAndWriteOpts =
256
+ typeof optsOrStrategy === "string"
257
+ ? { strategy: optsOrStrategy }
258
+ : optsOrStrategy;
259
+ const strategy: MergeStrategy = opts.strategy ?? "overwrite";
260
+ const baseline: BaselineMode = opts.baseline ?? "default";
261
+ const genStateDir =
262
+ opts.genStateDir !== undefined
263
+ ? (isAbsolute(opts.genStateDir)
264
+ ? opts.genStateDir
265
+ : resolve(opts.genStateDir))
266
+ : join(tmpdir(), "meta-gen-state-fallback");
267
+ const relPath = opts.outputRelPath ?? defaultOutputRelPath(path);
268
+
269
+ // 1. First-time write — file doesn't exist.
22
270
  if (!existsSync(path)) {
23
271
  mkdirSync(dirname(path), { recursive: true });
24
272
  writeFileSync(path, content);
273
+ advanceSnapshot(genStateDir, relPath, content);
25
274
  return { path, status: "new" };
26
275
  }
27
276
 
277
+ if (strategy === "skip-existing") {
278
+ return { path, status: "skipped" };
279
+ }
280
+
281
+ // 2. File exists. Load the canonical snapshot if any.
282
+ const snapshot = readSnapshotChecked(genStateDir, relPath);
283
+
284
+ // 3. First-time regen on a pre-existing file (no snapshot).
285
+ if (snapshot === undefined) {
286
+ const current = readFileSync(path, "utf-8");
287
+
288
+ if (baseline === "fresh") {
289
+ // Opt-in escape hatch: overwrite and seed the snapshot from fresh.
290
+ if (current === content) {
291
+ advanceSnapshot(genStateDir, relPath, content);
292
+ return { path, status: "unchanged" };
293
+ }
294
+ writeFileSync(path, content);
295
+ advanceSnapshot(genStateDir, relPath, content);
296
+ return { path, status: "overwrite" };
297
+ }
298
+
299
+ // Default: write-if-different. The EXISTING file is treated as the
300
+ // canonical baseline so subsequent runs do real three-way merges. If
301
+ // fresh output is identical, just seed the snapshot. If different, write
302
+ // the fresh content + seed snapshot — there's no marker policy left to
303
+ // refuse on, but this is the contract documented in the runbook (no
304
+ // marker check; users with hand-written files should never have the
305
+ // codegen output path colliding with them).
306
+ if (current === content) {
307
+ advanceSnapshot(genStateDir, relPath, current);
308
+ return { path, status: "unchanged" };
309
+ }
310
+ writeFileSync(path, content);
311
+ advanceSnapshot(genStateDir, relPath, content);
312
+ return { path, status: "overwrite" };
313
+ }
314
+
315
+ // 4. Snapshot exists — real three-way merge.
28
316
  const current = readFileSync(path, "utf-8");
29
- if (!current.includes(GENERATED_HEADER)) {
30
- return { path, status: "refused" };
317
+
318
+ // Fast path: nothing changed.
319
+ if (current === content && snapshot.text === content) {
320
+ return { path, status: "unchanged" };
31
321
  }
32
322
 
33
- if (strategy === "skip-existing") {
34
- return { path, status: "skipped" };
323
+ const baseTmp = writeTmpfile(snapshot.text);
324
+ const freshTmp = writeTmpfile(content);
325
+
326
+ const outcome = runGitMergeFile(path, baseTmp, freshTmp);
327
+
328
+ if (outcome.exitCode === 0) {
329
+ // Clean merge — advance the canonical snapshot to fresh.
330
+ advanceSnapshot(genStateDir, relPath, content);
331
+ // Distinguish "user had no changes vs canonical" from "merge integrated
332
+ // edits". The fresh equals snapshot case happened above (fast path) — so
333
+ // if outcome.mergedContent equals fresh we report a plain overwrite,
334
+ // otherwise it's a merge that pulled in user edits.
335
+ if (outcome.mergedContent === content) {
336
+ return { path, status: "overwrite" };
337
+ }
338
+ return { path, status: "merged" };
35
339
  }
36
340
 
37
- writeFileSync(path, content);
38
- return { path, status: "overwrite" };
341
+ // Conflict — do NOT advance the snapshot. The output now contains diff3
342
+ // markers from git merge-file.
343
+ return {
344
+ path,
345
+ status: "conflict",
346
+ conflictHint:
347
+ "merge conflict — resolve `<<<<<<<` markers and re-run `meta gen` to " +
348
+ "advance the canonical state.",
349
+ };
39
350
  }