@memberjunction/installer 0.0.1 → 5.5.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/InstallerEngine.d.ts +182 -0
  2. package/dist/InstallerEngine.d.ts.map +1 -0
  3. package/dist/InstallerEngine.js +571 -0
  4. package/dist/InstallerEngine.js.map +1 -0
  5. package/dist/adapters/FileSystemAdapter.d.ts +197 -0
  6. package/dist/adapters/FileSystemAdapter.d.ts.map +1 -0
  7. package/dist/adapters/FileSystemAdapter.js +355 -0
  8. package/dist/adapters/FileSystemAdapter.js.map +1 -0
  9. package/dist/adapters/GitHubReleaseProvider.d.ts +197 -0
  10. package/dist/adapters/GitHubReleaseProvider.d.ts.map +1 -0
  11. package/dist/adapters/GitHubReleaseProvider.js +348 -0
  12. package/dist/adapters/GitHubReleaseProvider.js.map +1 -0
  13. package/dist/adapters/ProcessRunner.d.ts +174 -0
  14. package/dist/adapters/ProcessRunner.d.ts.map +1 -0
  15. package/dist/adapters/ProcessRunner.js +264 -0
  16. package/dist/adapters/ProcessRunner.js.map +1 -0
  17. package/dist/adapters/SqlServerAdapter.d.ts +78 -0
  18. package/dist/adapters/SqlServerAdapter.d.ts.map +1 -0
  19. package/dist/adapters/SqlServerAdapter.js +120 -0
  20. package/dist/adapters/SqlServerAdapter.js.map +1 -0
  21. package/dist/errors/InstallerError.d.ts +92 -0
  22. package/dist/errors/InstallerError.d.ts.map +1 -0
  23. package/dist/errors/InstallerError.js +66 -0
  24. package/dist/errors/InstallerError.js.map +1 -0
  25. package/dist/events/InstallerEvents.d.ts +255 -0
  26. package/dist/events/InstallerEvents.d.ts.map +1 -0
  27. package/dist/events/InstallerEvents.js +96 -0
  28. package/dist/events/InstallerEvents.js.map +1 -0
  29. package/dist/index.d.ts +59 -0
  30. package/dist/index.d.ts.map +1 -0
  31. package/dist/index.js +63 -0
  32. package/dist/index.js.map +1 -0
  33. package/dist/models/Diagnostics.d.ts +121 -0
  34. package/dist/models/Diagnostics.d.ts.map +1 -0
  35. package/dist/models/Diagnostics.js +75 -0
  36. package/dist/models/Diagnostics.js.map +1 -0
  37. package/dist/models/InstallConfig.d.ts +139 -0
  38. package/dist/models/InstallConfig.d.ts.map +1 -0
  39. package/dist/models/InstallConfig.js +207 -0
  40. package/dist/models/InstallConfig.js.map +1 -0
  41. package/dist/models/InstallPlan.d.ts +189 -0
  42. package/dist/models/InstallPlan.d.ts.map +1 -0
  43. package/dist/models/InstallPlan.js +117 -0
  44. package/dist/models/InstallPlan.js.map +1 -0
  45. package/dist/models/InstallState.d.ts +173 -0
  46. package/dist/models/InstallState.d.ts.map +1 -0
  47. package/dist/models/InstallState.js +203 -0
  48. package/dist/models/InstallState.js.map +1 -0
  49. package/dist/models/VersionInfo.d.ts +53 -0
  50. package/dist/models/VersionInfo.d.ts.map +1 -0
  51. package/dist/models/VersionInfo.js +2 -0
  52. package/dist/models/VersionInfo.js.map +1 -0
  53. package/dist/phases/CodeGenPhase.d.ts +364 -0
  54. package/dist/phases/CodeGenPhase.d.ts.map +1 -0
  55. package/dist/phases/CodeGenPhase.js +1086 -0
  56. package/dist/phases/CodeGenPhase.js.map +1 -0
  57. package/dist/phases/ConfigurePhase.d.ts +86 -0
  58. package/dist/phases/ConfigurePhase.d.ts.map +1 -0
  59. package/dist/phases/ConfigurePhase.js +439 -0
  60. package/dist/phases/ConfigurePhase.js.map +1 -0
  61. package/dist/phases/DatabaseProvisionPhase.d.ts +82 -0
  62. package/dist/phases/DatabaseProvisionPhase.d.ts.map +1 -0
  63. package/dist/phases/DatabaseProvisionPhase.js +284 -0
  64. package/dist/phases/DatabaseProvisionPhase.js.map +1 -0
  65. package/dist/phases/DependencyPhase.d.ts +88 -0
  66. package/dist/phases/DependencyPhase.d.ts.map +1 -0
  67. package/dist/phases/DependencyPhase.js +237 -0
  68. package/dist/phases/DependencyPhase.js.map +1 -0
  69. package/dist/phases/MigratePhase.d.ts +70 -0
  70. package/dist/phases/MigratePhase.d.ts.map +1 -0
  71. package/dist/phases/MigratePhase.js +96 -0
  72. package/dist/phases/MigratePhase.js.map +1 -0
  73. package/dist/phases/PlatformCompatPhase.d.ts +193 -0
  74. package/dist/phases/PlatformCompatPhase.d.ts.map +1 -0
  75. package/dist/phases/PlatformCompatPhase.js +587 -0
  76. package/dist/phases/PlatformCompatPhase.js.map +1 -0
  77. package/dist/phases/PreflightPhase.d.ts +119 -0
  78. package/dist/phases/PreflightPhase.d.ts.map +1 -0
  79. package/dist/phases/PreflightPhase.js +394 -0
  80. package/dist/phases/PreflightPhase.js.map +1 -0
  81. package/dist/phases/ScaffoldPhase.d.ts +99 -0
  82. package/dist/phases/ScaffoldPhase.d.ts.map +1 -0
  83. package/dist/phases/ScaffoldPhase.js +235 -0
  84. package/dist/phases/ScaffoldPhase.js.map +1 -0
  85. package/dist/phases/SmokeTestPhase.d.ts +111 -0
  86. package/dist/phases/SmokeTestPhase.d.ts.map +1 -0
  87. package/dist/phases/SmokeTestPhase.js +426 -0
  88. package/dist/phases/SmokeTestPhase.js.map +1 -0
  89. package/package.json +26 -7
  90. package/README.md +0 -45
@@ -0,0 +1,203 @@
1
+ /**
2
+ * Checkpoint state for the MJ installer, persisted to `.mj-install-state.json`.
3
+ *
4
+ * Enables resume of interrupted installs. After each phase completes (or fails),
5
+ * the engine calls {@link InstallState.Save} to write the current state to disk.
6
+ * On the next run, {@link InstallState.Load} reads the state file and
7
+ * {@link InstallerEngine.Run} skips already-completed phases.
8
+ *
9
+ * The state file is also used by the {@link ScaffoldPhase} to detect whether the
10
+ * target directory contains installer-owned artifacts (so it doesn't trigger the
11
+ * "directory is not empty" prompt for its own state file).
12
+ *
13
+ * @module models/InstallState
14
+ *
15
+ * @example
16
+ * ```typescript
17
+ * // Create fresh state
18
+ * const state = new InstallState('/path/to/install', 'v5.1.0');
19
+ * state.MarkCompleted('preflight');
20
+ * await state.Save();
21
+ *
22
+ * // Resume from existing state
23
+ * const resumed = await InstallState.Load('/path/to/install');
24
+ * if (resumed) {
25
+ * const nextPhase = resumed.FirstIncompletePhase(ALL_PHASES);
26
+ * console.log(`Resuming from: ${nextPhase}`);
27
+ * }
28
+ * ```
29
+ */
30
+ import fs from 'node:fs/promises';
31
+ import path from 'node:path';
32
+ /** Filename of the checkpoint state file, written to the install target directory. */
33
+ const STATE_FILENAME = '.mj-install-state.json';
34
+ /**
35
+ * Checkpoint state manager for the MJ installer.
36
+ *
37
+ * Tracks per-phase completion status and persists it to a JSON file in
38
+ * the install target directory. The engine writes checkpoint state after
39
+ * each phase so that interrupted installs can be resumed from the last
40
+ * completed phase.
41
+ *
42
+ * @example
43
+ * ```typescript
44
+ * const state = new InstallState('/path/to/install', 'v5.1.0');
45
+ * state.MarkCompleted('preflight');
46
+ * state.MarkCompleted('scaffold');
47
+ * await state.Save();
48
+ *
49
+ * // Later, resume:
50
+ * const loaded = await InstallState.Load('/path/to/install');
51
+ * console.log(loaded?.GetPhaseStatus('preflight')); // 'completed'
52
+ * console.log(loaded?.GetPhaseStatus('configure')); // 'pending'
53
+ * ```
54
+ */
55
+ export class InstallState {
56
+ /**
57
+ * Create a new checkpoint state for a fresh install.
58
+ *
59
+ * @param dir - Target directory where the state file will be written.
60
+ * @param tag - Git tag of the version being installed (e.g., `"v5.1.0"`).
61
+ */
62
+ constructor(dir, tag) {
63
+ this.filePath = path.join(dir, STATE_FILENAME);
64
+ this.data = {
65
+ Tag: tag,
66
+ StartedAt: new Date().toISOString(),
67
+ Phases: {},
68
+ };
69
+ }
70
+ /** Git tag of the version being installed. */
71
+ get Tag() {
72
+ return this.data.Tag;
73
+ }
74
+ /** ISO 8601 timestamp when the install was started. */
75
+ get StartedAt() {
76
+ return this.data.StartedAt;
77
+ }
78
+ /**
79
+ * Load checkpoint state from disk.
80
+ *
81
+ * @param dir - Directory containing the `.mj-install-state.json` file.
82
+ * @returns The loaded state, or `null` if the file doesn't exist or is malformed.
83
+ */
84
+ static async Load(dir) {
85
+ const filePath = path.join(dir, STATE_FILENAME);
86
+ try {
87
+ const raw = await fs.readFile(filePath, 'utf-8');
88
+ const parsed = JSON.parse(raw);
89
+ const state = new InstallState(dir, parsed.Tag);
90
+ state.data = parsed;
91
+ return state;
92
+ }
93
+ catch {
94
+ return null;
95
+ }
96
+ }
97
+ /**
98
+ * Check whether a checkpoint state file exists at the given directory.
99
+ *
100
+ * @param dir - Directory to check.
101
+ * @returns `true` if `.mj-install-state.json` exists and is accessible.
102
+ */
103
+ static async Exists(dir) {
104
+ try {
105
+ await fs.access(path.join(dir, STATE_FILENAME));
106
+ return true;
107
+ }
108
+ catch {
109
+ return false;
110
+ }
111
+ }
112
+ /**
113
+ * Get the current status of a phase.
114
+ *
115
+ * @param phase - Phase identifier to query.
116
+ * @returns The phase's status, defaulting to `'pending'` if not yet recorded.
117
+ */
118
+ GetPhaseStatus(phase) {
119
+ return this.data.Phases[phase]?.Status ?? 'pending';
120
+ }
121
+ /**
122
+ * Mark a phase as successfully completed.
123
+ *
124
+ * @param phase - Phase identifier to mark as completed.
125
+ */
126
+ MarkCompleted(phase) {
127
+ this.data.Phases[phase] = {
128
+ Status: 'completed',
129
+ CompletedAt: new Date().toISOString(),
130
+ };
131
+ }
132
+ /**
133
+ * Mark a phase as failed with an error message.
134
+ *
135
+ * @param phase - Phase identifier to mark as failed.
136
+ * @param error - Error message describing the failure.
137
+ */
138
+ MarkFailed(phase, error) {
139
+ this.data.Phases[phase] = {
140
+ Status: 'failed',
141
+ FailedAt: new Date().toISOString(),
142
+ Error: error,
143
+ };
144
+ }
145
+ /**
146
+ * Mark a phase as skipped (excluded by plan flags).
147
+ *
148
+ * @param phase - Phase identifier to mark as skipped.
149
+ */
150
+ MarkSkipped(phase) {
151
+ this.data.Phases[phase] = {
152
+ Status: 'skipped',
153
+ };
154
+ }
155
+ /**
156
+ * Find the first phase that is neither completed nor skipped.
157
+ * Used by the engine to determine the resume point after loading checkpoint state.
158
+ *
159
+ * @param orderedPhases - Ordered list of all phase identifiers.
160
+ * @returns The first incomplete phase ID, or `null` if all phases are done.
161
+ */
162
+ FirstIncompletePhase(orderedPhases) {
163
+ for (const phase of orderedPhases) {
164
+ const status = this.GetPhaseStatus(phase);
165
+ if (status !== 'completed' && status !== 'skipped') {
166
+ return phase;
167
+ }
168
+ }
169
+ return null;
170
+ }
171
+ /**
172
+ * Persist the current state to disk as `.mj-install-state.json`.
173
+ * Called by the engine after each phase completes, fails, or is skipped.
174
+ *
175
+ * @throws Error if the file cannot be written (e.g., permission denied).
176
+ */
177
+ async Save() {
178
+ const json = JSON.stringify(this.data, null, 2);
179
+ await fs.writeFile(this.filePath, json, 'utf-8');
180
+ }
181
+ /**
182
+ * Delete the checkpoint state file from disk.
183
+ * Silently succeeds if the file doesn't exist.
184
+ */
185
+ async Delete() {
186
+ try {
187
+ await fs.unlink(this.filePath);
188
+ }
189
+ catch {
190
+ // file may not exist — that's fine
191
+ }
192
+ }
193
+ /**
194
+ * Return a deep clone of the internal state data for serialization
195
+ * or inspection without exposing the mutable internal reference.
196
+ *
197
+ * @returns A deep copy of the {@link InstallStateData}.
198
+ */
199
+ ToJSON() {
200
+ return structuredClone(this.data);
201
+ }
202
+ }
203
+ //# sourceMappingURL=InstallState.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"InstallState.js","sourceRoot":"","sources":["../../src/models/InstallState.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4BG;AAEH,OAAO,EAAE,MAAM,kBAAkB,CAAC;AAClC,OAAO,IAAI,MAAM,WAAW,CAAC;AA2C7B,sFAAsF;AACtF,MAAM,cAAc,GAAG,wBAAwB,CAAC;AAEhD;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,MAAM,OAAO,YAAY;IAOvB;;;;;OAKG;IACH,YAAY,GAAW,EAAE,GAAW;QAClC,IAAI,CAAC,QAAQ,GAAG,IAAI,CAAC,IAAI,CAAC,GAAG,EAAE,cAAc,CAAC,CAAC;QAC/C,IAAI,CAAC,IAAI,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EAAE,CAAC,MAAM,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;QACjC,CAAC;QAAC,MAAM,CAAC;YACP,mCAAmC;QACrC,CAAC;IACH,CAAC;IAED;;;;;OAKG;IACH,MAAM;QACJ,OAAO,eAAe,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;IACpC,CAAC;CACF"}
@@ -0,0 +1,53 @@
1
+ /**
2
+ * Information about a single MemberJunction release version.
3
+ *
4
+ * Populated by {@link GitHubReleaseProvider} from either formal GitHub
5
+ * Releases or git tags. Used by {@link ScaffoldPhase} to resolve the
6
+ * download target and by {@link InstallerEngine.ListVersions} to populate
7
+ * the interactive version picker.
8
+ *
9
+ * @module models/VersionInfo
10
+ *
11
+ * @example
12
+ * ```typescript
13
+ * const provider = new GitHubReleaseProvider();
14
+ * const versions: VersionInfo[] = await provider.ListReleases();
15
+ * const latest = versions[0];
16
+ * console.log(`${latest.Tag} — ${latest.Name} (${latest.ReleaseDate.toLocaleDateString()})`);
17
+ * ```
18
+ */
19
+ export interface VersionInfo {
20
+ /**
21
+ * Git tag associated with this release (e.g., `"v5.1.0"`).
22
+ * Used as the primary identifier for version selection and checkpoint state.
23
+ */
24
+ Tag: string;
25
+ /**
26
+ * Human-readable display name for the release.
27
+ * Falls back to the tag name if no formal release title is set on GitHub.
28
+ */
29
+ Name: string;
30
+ /**
31
+ * Date when the release was published on GitHub.
32
+ * For tag-based fallback versions, this is the commit date of the tagged commit.
33
+ */
34
+ ReleaseDate: Date;
35
+ /**
36
+ * Whether this release is marked as a prerelease on GitHub.
37
+ * Prereleases are excluded from {@link GitHubReleaseProvider.ListReleases}
38
+ * unless `includePrerelease` is `true`.
39
+ */
40
+ Prerelease: boolean;
41
+ /**
42
+ * Direct URL to the release ZIP archive for download.
43
+ * Prefers an uploaded `.zip` asset if available; otherwise uses the
44
+ * GitHub-generated `zipball_url` (source code archive).
45
+ */
46
+ DownloadUrl: string;
47
+ /**
48
+ * Short excerpt from the release notes (first 500 characters), if available.
49
+ * `undefined` for tag-based fallback versions that have no release notes.
50
+ */
51
+ Notes?: string;
52
+ }
53
+ //# sourceMappingURL=VersionInfo.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"VersionInfo.d.ts","sourceRoot":"","sources":["../../src/models/VersionInfo.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;GAiBG;AACH,MAAM,WAAW,WAAW;IAC1B;;;OAGG;IACH,GAAG,EAAE,MAAM,CAAC;IAEZ;;;OAGG;IACH,IAAI,EAAE,MAAM,CAAC;IAEb;;;OAGG;IACH,WAAW,EAAE,IAAI,CAAC;IAElB;;;;OAIG;IACH,UAAU,EAAE,OAAO,CAAC;IAEpB;;;;OAIG;IACH,WAAW,EAAE,MAAM,CAAC;IAEpB;;;OAGG;IACH,KAAK,CAAC,EAAE,MAAM,CAAC;CAChB"}
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=VersionInfo.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"VersionInfo.js","sourceRoot":"","sources":["../../src/models/VersionInfo.ts"],"names":[],"mappings":""}
@@ -0,0 +1,364 @@
1
+ /**
2
+ * Phase H — CodeGen + Validation
3
+ *
4
+ * Runs `mj codegen` to generate TypeScript entity classes, action classes,
5
+ * SQL objects, and Angular form components from database schema and metadata.
6
+ * Validates that required artifacts are produced and applies post-codegen
7
+ * fixups to ensure class registration manifests and known-issue patches
8
+ * are current.
9
+ *
10
+ * **Artifact verification** is two-tier:
11
+ * - `mj_generatedentities` in `node_modules/` — **critical** (blocks install if missing).
12
+ * - `packages/GeneratedEntities` — **secondary** (warns if missing, does not block).
13
+ *
14
+ * **Retry strategy**: If codegen fails on the first attempt (common when AFTER
15
+ * commands leave stale `dist/` from a partial build), the phase runs a full
16
+ * `npm run build` to restore consistency, then retries codegen once. Timeouts
17
+ * are not retried (they indicate deeper connectivity or performance issues).
18
+ *
19
+ * **Post-codegen pipeline** (4 steps after successful codegen):
20
+ * 1. Force-rebuild codegen output packages (`.d.ts` exports must reflect new classes).
21
+ * 2. Regenerate class registration manifest `.ts` files via `npm run mj:manifest`.
22
+ * 3. Force-rebuild manifest packages (compile freshly generated `.ts` to `.js`).
23
+ * 4. Apply known-issue source patches and rebuild affected packages.
24
+ *
25
+ * **Fast mode** (`--fast`): Quick-checks manifest files for stale entity names
26
+ * and compares source/dist timestamps. If everything looks current, Steps 1-3
27
+ * are skipped entirely (saving ~2-3 minutes). Step 4 always runs.
28
+ *
29
+ * @module phases/CodeGenPhase
30
+ * @see DependencyPhase — must complete before codegen (packages must be built).
31
+ * @see MigratePhase — must complete before codegen (schema must be current).
32
+ * @see SmokeTestPhase — runs after codegen to verify the generated code works.
33
+ */
34
+ import type { InstallerEventEmitter } from '../events/InstallerEvents.js';
35
+ /**
36
+ * Input context for the codegen phase.
37
+ *
38
+ * @see CodeGenPhase.Run
39
+ */
40
+ export interface CodeGenContext {
41
+ /** Absolute path to the repo root (where `npx mj codegen` is executed). */
42
+ Dir: string;
43
+ /** Event emitter for progress, warn, and log events. */
44
+ Emitter: InstallerEventEmitter;
45
+ /**
46
+ * Fast mode: skip post-codegen Steps 1-3 (force-rebuild + manifest regen +
47
+ * manifest rebuild) if manifest files already look correct. Step 4
48
+ * (known-issue patches) always runs regardless of this flag.
49
+ */
50
+ Fast?: boolean;
51
+ }
52
+ /**
53
+ * Result of the codegen phase.
54
+ *
55
+ * @see CodeGenPhase.Run
56
+ */
57
+ export interface CodeGenResult {
58
+ /** Whether codegen completed successfully (exited 0 and critical artifacts exist). */
59
+ Success: boolean;
60
+ /** Whether **all** artifacts were verified (both critical and secondary). */
61
+ ArtifactsVerified: boolean;
62
+ /** Whether a full rebuild + retry was needed to produce artifacts. */
63
+ RetryUsed: boolean;
64
+ }
65
+ /**
66
+ * A known issue that can be detected and patched in source files of the
67
+ * installed repo. Each patch targets a specific file and applies a
68
+ * deterministic text transformation.
69
+ */
70
+ export interface KnownIssuePatch {
71
+ /** Unique identifier for this patch */
72
+ Id: string;
73
+ /** Human-readable description of the issue and fix */
74
+ Description: string;
75
+ /** File to patch, relative to the repo root */
76
+ RelativePath: string;
77
+ /** Package directory (relative to repo root) that needs rebuilding after the patch */
78
+ PackageRelativeDir: string;
79
+ /** Returns true if the file content contains the known issue (needs patching) */
80
+ NeedsPatch: (content: string) => boolean;
81
+ /** Apply the patch and return the new file content */
82
+ Apply: (content: string) => string;
83
+ }
84
+ /** Result of a known-issue diagnostic check (used by mj doctor) */
85
+ export interface KnownIssueDiagnostic {
86
+ /** Patch ID */
87
+ Id: string;
88
+ /** Whether the issue was found, already fixed, or couldn't be checked */
89
+ Status: 'needs_patch' | 'ok' | 'skipped';
90
+ /** Description of the issue */
91
+ Description: string;
92
+ /** File path relative to repo root */
93
+ RelativePath: string;
94
+ }
95
+ /**
96
+ * Phase H — Runs MJ CodeGen, verifies artifacts, and applies post-codegen fixups.
97
+ *
98
+ * This is the most complex phase in the install pipeline. After code generation
99
+ * succeeds, it runs a 4-step post-codegen pipeline to ensure class registration
100
+ * manifests are current and known source-level issues are patched.
101
+ *
102
+ * @example
103
+ * ```typescript
104
+ * const codeGen = new CodeGenPhase();
105
+ * const result = await codeGen.Run({
106
+ * Dir: '/path/to/install',
107
+ * Emitter: emitter,
108
+ * Fast: false,
109
+ * });
110
+ * if (result.RetryUsed) {
111
+ * console.log('CodeGen needed a rebuild + retry');
112
+ * }
113
+ * ```
114
+ */
115
+ export declare class CodeGenPhase {
116
+ private processRunner;
117
+ private fileSystem;
118
+ /**
119
+ * Execute the codegen phase: run `mj codegen`, verify artifacts, retry if needed,
120
+ * then run the post-codegen pipeline (manifest regen + known-issue patches).
121
+ *
122
+ * @param context - Codegen input with directory, emitter, and fast-mode flag.
123
+ * @returns Codegen result with success status, artifact verification, and retry flag.
124
+ * @throws {InstallerError} With code `CODEGEN_TIMEOUT` if codegen exceeds 10 minutes.
125
+ * @throws {InstallerError} With code `CODEGEN_FAILED` if codegen fails after rebuild + retry.
126
+ */
127
+ Run(context: CodeGenContext): Promise<CodeGenResult>;
128
+ /**
129
+ * Runs codegen and verifies artifacts. Returns a result object instead of
130
+ * throwing, so the caller can decide whether to retry.
131
+ * Only timeouts throw immediately (not recoverable by rebuild).
132
+ */
133
+ private attemptCodeGen;
134
+ /**
135
+ * Execute `npx mj codegen` and return structured results.
136
+ *
137
+ * Detects AFTER command failures in the codegen output — these indicate that
138
+ * post-generation build steps failed, leaving `dist/` directories with stale
139
+ * compiled `.js` that references generated `.ts` files which were never compiled.
140
+ *
141
+ * @param dir - Repo root directory.
142
+ * @param emitter - Event emitter for progress reporting.
143
+ * @returns Structured result with success flag, AFTER-command failure detection, and error summary.
144
+ * @throws {InstallerError} With code `CODEGEN_TIMEOUT` if the process exceeds 10 minutes.
145
+ */
146
+ private runCodeGen;
147
+ /**
148
+ * Save CodeGen AFTER command output to a log file for diagnostics.
149
+ *
150
+ * Non-critical — failures to write the log are silently ignored.
151
+ *
152
+ * @param dir - Repo root directory.
153
+ * @param stdout - Full stdout from the codegen process.
154
+ * @param stderr - Full stderr from the codegen process.
155
+ * @param emitter - Event emitter for verbose logging.
156
+ */
157
+ private saveAfterLog;
158
+ /**
159
+ * Verify that codegen produced the expected artifacts.
160
+ *
161
+ * Two-tier check:
162
+ * - **Critical**: `node_modules/mj_generatedentities` must exist (MJAPI can't start without it).
163
+ * - **Secondary**: `packages/GeneratedEntities` is expected but absence is only a warning.
164
+ *
165
+ * @param dir - Repo root directory.
166
+ * @param emitter - Event emitter for diagnostic logging.
167
+ * @returns Object indicating whether critical and all artifacts passed verification.
168
+ */
169
+ private verifyArtifacts;
170
+ /**
171
+ * Packages that contain generated code managed by CodeGen. Build failures in
172
+ * only these packages are tolerated — codegen will regenerate the stale code.
173
+ */
174
+ private static readonly CODEGEN_MANAGED_PACKAGES;
175
+ /**
176
+ * Full workspace rebuild to restore consistency before retrying codegen.
177
+ *
178
+ * Runs `npm run build` at the repo root. Tolerates build failures in
179
+ * codegen-managed packages (they contain stale generated code that the
180
+ * retry will regenerate). Non-codegen build failures are hard errors.
181
+ *
182
+ * @param dir - Repo root directory.
183
+ * @param emitter - Event emitter for progress and warning reporting.
184
+ * @throws {InstallerError} With code `CODEGEN_FAILED` on timeout or non-codegen build failures.
185
+ */
186
+ private rebuildPackages;
187
+ /**
188
+ * Known stale entity import patterns to check for in manifest files.
189
+ * These are entity class names that were renamed with the "MJ" prefix
190
+ * in 5.0.0+ but may still appear in stale pre-built manifests from
191
+ * release zips that were not fully compiled after renaming.
192
+ */
193
+ private static readonly STALE_ENTITY_PATTERNS;
194
+ /**
195
+ * Manifest source files that should be regenerated after codegen.
196
+ * Paths are relative to the repo root.
197
+ */
198
+ private static readonly MANIFEST_SOURCE_PATHS;
199
+ /**
200
+ * After codegen succeeds, ensure class registration manifests and their
201
+ * compiled output are up-to-date, and apply known source-level fixes.
202
+ *
203
+ * The flow:
204
+ * 1. Force-rebuild codegen output packages so their .d.ts exports reflect
205
+ * the latest generated entity class names.
206
+ * 2. Regenerate manifest .ts files using `npm run mj:manifest` (which reads
207
+ * .d.ts to verify exported classes).
208
+ * 3. Force-rebuild the manifest packages so the compiled .js matches
209
+ * the freshly generated .ts source.
210
+ * 4. Apply known-issue source patches (e.g. null-safety fixes for fresh
211
+ * installs) and rebuild affected packages.
212
+ */
213
+ private regenerateManifestsAndRebuild;
214
+ /**
215
+ * Codegen output packages whose source vs dist timestamps must match
216
+ * for fast mode to skip the rebuild. If codegen regenerated the source
217
+ * (entity_subclasses.ts) but the compiled output (entity_subclasses.d.ts)
218
+ * is older, Steps 1-3 are needed.
219
+ */
220
+ private static readonly CODEGEN_TIMESTAMP_CHECKS;
221
+ /**
222
+ * Quick-check whether the full post-codegen rebuild cycle (Steps 1-3)
223
+ * can be safely skipped.
224
+ *
225
+ * Returns true only if:
226
+ * 1. No codegen output source files are newer than their compiled dist
227
+ * (meaning codegen didn't regenerate them, or they've already been rebuilt).
228
+ * 2. No manifest files contain known stale entity names.
229
+ *
230
+ * If either condition fails, the full rebuild cycle is required.
231
+ */
232
+ private quickCheckManifests;
233
+ /**
234
+ * Force-rebuild ALL packages whose source is generated by codegen.
235
+ * This ensures their compiled .d.ts exports and .js modules are current.
236
+ *
237
+ * Four packages have codegen-generated source in src/generated/:
238
+ * - @memberjunction/core-entities (entity_subclasses.ts)
239
+ * - mj_generatedentities (entity_subclasses.ts)
240
+ * - @memberjunction/core-actions (action_subclasses.ts)
241
+ * - mj_generatedactions (action_subclasses.ts)
242
+ *
243
+ * The manifest generator walks the dependency tree and imports from these
244
+ * packages. If their dist/ is stale (e.g. index.js imports a generated
245
+ * module that was regenerated but never compiled), manifest generation
246
+ * fails with ERR_MODULE_NOT_FOUND.
247
+ */
248
+ private forceRebuildCodegenOutputPackages;
249
+ /**
250
+ * Manifest packages and their build commands/directories.
251
+ * We build each package individually (bypassing turbo) because turbo's
252
+ * `--filter` resolves the full transitive dependency graph, which includes
253
+ * ng-core-entity-forms. That package contains stale generated entity forms
254
+ * (codegen just regenerated its source but hasn't compiled it yet), so it
255
+ * fails to build and turbo skips all packages that depend on it — including
256
+ * the very bootstrap packages we need to rebuild.
257
+ *
258
+ * Building directly with each package's own build command (tsc, ng-packagr)
259
+ * only requires the .d.ts files from direct TypeScript imports, which
260
+ * already exist from prior builds. This cleanly sidesteps the turbo issue.
261
+ */
262
+ private static readonly MANIFEST_PACKAGE_BUILDS;
263
+ /**
264
+ * Force-rebuild ONLY the packages that contain class registration manifests.
265
+ * Builds each package individually using its own build command, bypassing
266
+ * turbo to avoid the ng-core-entity-forms transitive dependency failure.
267
+ */
268
+ private forceRebuildManifestPackages;
269
+ /**
270
+ * Regenerate class registration manifest `.ts` files by running `npm run mj:manifest`.
271
+ *
272
+ * The manifest generator scans source for `@RegisterClass` decorators, verifies
273
+ * them against `.d.ts` exports (from Step 1), and emits updated manifest files
274
+ * with static import paths that prevent tree-shaking.
275
+ *
276
+ * @param dir - Repo root directory.
277
+ * @param emitter - Event emitter for progress and warning reporting.
278
+ * @returns `true` if manifest regeneration succeeded, `false` if it failed or timed out.
279
+ */
280
+ private regenerateManifests;
281
+ /**
282
+ * Diagnostic: read each manifest .ts file and check for known stale entity
283
+ * import names. Emits warnings with detailed info to help troubleshoot
284
+ * persistent stale-manifest issues.
285
+ */
286
+ private verifyManifestContent;
287
+ /**
288
+ * When `mj codegen manifest` fails, this method directly patches the
289
+ * manifest .ts files by adding the "MJ" prefix to entity class names
290
+ * that are missing it.
291
+ *
292
+ * The 5.0/5.1 entity rename added an "MJ" prefix to all core entity classes
293
+ * (e.g. AIActionEntity → MJAIActionEntity). The pre-built manifest .ts files
294
+ * from the release zip may still reference the old names.
295
+ *
296
+ * Strategy: read entity_subclasses.ts (regenerated by codegen) to build an
297
+ * exact old→new rename map. Only names that have a corresponding MJ-prefixed
298
+ * class in entity_subclasses.ts are renamed. This avoids touching server
299
+ * entity classes (e.g. ApplicationEntityServerEntity) or extended classes
300
+ * (e.g. EntityEntityExtended) that legitimately don't have the MJ prefix.
301
+ */
302
+ private patchStaleManifestImports;
303
+ /**
304
+ * Read entity_subclasses.ts source and build a map of old→new entity class
305
+ * names. For each `export class MJFooEntity`, we add FooEntity → MJFooEntity.
306
+ *
307
+ * Tries the source .ts first (most up-to-date after codegen), then falls
308
+ * back to the compiled .d.ts.
309
+ */
310
+ private buildEntityRenameMap;
311
+ /**
312
+ * Patch a single manifest .ts file using the entity rename map.
313
+ * Only renames class names that have a known MJ-prefixed counterpart
314
+ * in entity_subclasses.ts.
315
+ */
316
+ private patchSingleManifest;
317
+ /**
318
+ * Registry of known issues that affect fresh installs. Each entry describes
319
+ * a source-level bug (typically null-safety issues in code that assumes
320
+ * non-empty datasets) and how to patch it.
321
+ *
322
+ * When a new issue is discovered during fresh-install testing, add an entry
323
+ * here rather than modifying the source package — this keeps the fix
324
+ * localized to the installer and avoids touching upstream code.
325
+ */
326
+ private static readonly KNOWN_ISSUE_PATCHES;
327
+ /**
328
+ * Step 4 of post-codegen fixup: apply known source-level patches to the
329
+ * fresh install's files and rebuild any affected packages.
330
+ *
331
+ * This handles issues like null-safety bugs that only manifest on fresh
332
+ * installs (empty datasets, missing metadata, etc.) without requiring
333
+ * changes to the upstream source packages.
334
+ */
335
+ private applyKnownIssuePatches;
336
+ /**
337
+ * Rebuild a single package by running `npm run build` in its directory.
338
+ */
339
+ private rebuildSinglePackage;
340
+ /**
341
+ * Run known-issue diagnostic checks against the target directory.
342
+ * Used by `mj doctor` to detect issues that the installer would
343
+ * automatically patch during a fresh install.
344
+ *
345
+ * Returns an array of diagnostic results — one per known issue that
346
+ * was detected (or confirmed absent) in the target directory.
347
+ */
348
+ RunKnownIssueChecks(dir: string, emitter: InstallerEventEmitter): Promise<KnownIssueDiagnostic[]>;
349
+ /**
350
+ * Extract failed package names from turbo's output.
351
+ * Turbo outputs lines like: "Failed: @memberjunction/ng-core-entity-forms#build"
352
+ * Note: the "Failed:" summary goes to stdout, not stderr.
353
+ */
354
+ private extractFailedTurboPackages;
355
+ /**
356
+ * Extract the last N lines from a string (for truncated error output).
357
+ *
358
+ * @param text - The full text to extract from.
359
+ * @param n - Number of trailing lines to keep.
360
+ * @returns The last `n` lines joined with newlines.
361
+ */
362
+ private lastNLines;
363
+ }
364
+ //# sourceMappingURL=CodeGenPhase.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"CodeGenPhase.d.ts","sourceRoot":"","sources":["../../src/phases/CodeGenPhase.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAgCG;AAGH,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,8BAA8B,CAAC;AAK1E;;;;GAIG;AACH,MAAM,WAAW,cAAc;IAC7B,2EAA2E;IAC3E,GAAG,EAAE,MAAM,CAAC;IACZ,wDAAwD;IACxD,OAAO,EAAE,qBAAqB,CAAC;IAC/B;;;;OAIG;IACH,IAAI,CAAC,EAAE,OAAO,CAAC;CAChB;AAED;;;;GAIG;AACH,MAAM,WAAW,aAAa;IAC5B,sFAAsF;IACtF,O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