@mettlecast/domain-cli 0.2.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 (301) hide show
  1. package/CHANGELOG.md +18 -0
  2. package/README.md +133 -0
  3. package/dist/builder/build-registry.d.ts +20 -0
  4. package/dist/builder/build-registry.js +178 -0
  5. package/dist/builder/build-types.d.ts +10 -0
  6. package/dist/builder/build-types.js +32 -0
  7. package/dist/builder/load-domain-module-config.d.ts +12 -0
  8. package/dist/builder/load-domain-module-config.js +34 -0
  9. package/dist/builder/load-module.d.ts +26 -0
  10. package/dist/builder/load-module.js +114 -0
  11. package/dist/builder/zod-to-json.d.ts +10 -0
  12. package/dist/builder/zod-to-json.js +15 -0
  13. package/dist/cli.d.ts +2 -0
  14. package/dist/cli.js +338 -0
  15. package/dist/commands/add-api.d.ts +32 -0
  16. package/dist/commands/add-api.js +106 -0
  17. package/dist/commands/add-component.d.ts +15 -0
  18. package/dist/commands/add-component.js +78 -0
  19. package/dist/commands/add-domain.d.ts +21 -0
  20. package/dist/commands/add-domain.js +71 -0
  21. package/dist/commands/add-flow.d.ts +14 -0
  22. package/dist/commands/add-flow.js +108 -0
  23. package/dist/commands/add-hook.d.ts +15 -0
  24. package/dist/commands/add-hook.js +65 -0
  25. package/dist/commands/add-migration.d.ts +26 -0
  26. package/dist/commands/add-migration.js +93 -0
  27. package/dist/commands/add-module.d.ts +7 -0
  28. package/dist/commands/add-module.js +261 -0
  29. package/dist/commands/add-page.d.ts +13 -0
  30. package/dist/commands/add-page.js +170 -0
  31. package/dist/commands/add-seed-page.d.ts +5 -0
  32. package/dist/commands/add-seed-page.js +251 -0
  33. package/dist/commands/add-subscriber.d.ts +30 -0
  34. package/dist/commands/add-subscriber.js +87 -0
  35. package/dist/commands/add-test.d.ts +22 -0
  36. package/dist/commands/add-test.js +285 -0
  37. package/dist/commands/audit.d.ts +39 -0
  38. package/dist/commands/audit.js +171 -0
  39. package/dist/commands/build-catalog.d.ts +68 -0
  40. package/dist/commands/build-catalog.js +105 -0
  41. package/dist/commands/build-flows.d.ts +26 -0
  42. package/dist/commands/build-flows.js +174 -0
  43. package/dist/commands/build.d.ts +17 -0
  44. package/dist/commands/build.js +39 -0
  45. package/dist/commands/check-hashes.d.ts +38 -0
  46. package/dist/commands/check-hashes.js +97 -0
  47. package/dist/commands/create-project.d.ts +5 -0
  48. package/dist/commands/create-project.js +272 -0
  49. package/dist/commands/dev.d.ts +15 -0
  50. package/dist/commands/dev.js +27 -0
  51. package/dist/commands/doctor.d.ts +48 -0
  52. package/dist/commands/doctor.js +1301 -0
  53. package/dist/commands/explain.d.ts +34 -0
  54. package/dist/commands/explain.js +167 -0
  55. package/dist/commands/power-tune.d.ts +1 -0
  56. package/dist/commands/power-tune.js +87 -0
  57. package/dist/commands/reseed-page.d.ts +6 -0
  58. package/dist/commands/reseed-page.js +297 -0
  59. package/dist/commands/show-dns.d.ts +15 -0
  60. package/dist/commands/show-dns.js +101 -0
  61. package/dist/commands/show.d.ts +46 -0
  62. package/dist/commands/show.js +135 -0
  63. package/dist/commands/test.d.ts +18 -0
  64. package/dist/commands/test.js +56 -0
  65. package/dist/commands/upgrade-backend.d.ts +9 -0
  66. package/dist/commands/upgrade-backend.js +46 -0
  67. package/dist/commands/upgrade-event.d.ts +22 -0
  68. package/dist/commands/upgrade-event.js +111 -0
  69. package/dist/commands/upgrade-frontend.d.ts +5 -0
  70. package/dist/commands/upgrade-frontend.js +99 -0
  71. package/dist/commands/upgrade.d.ts +7 -0
  72. package/dist/commands/upgrade.js +495 -0
  73. package/dist/commands/validate.d.ts +30 -0
  74. package/dist/commands/validate.js +148 -0
  75. package/dist/runtime-stubs/hydrate-local-ctx.d.ts +49 -0
  76. package/dist/runtime-stubs/hydrate-local-ctx.js +45 -0
  77. package/dist/runtime-stubs/load-secrets.d.ts +11 -0
  78. package/dist/runtime-stubs/load-secrets.js +37 -0
  79. package/dist/server/api-server.d.ts +21 -0
  80. package/dist/server/api-server.js +14 -0
  81. package/dist/server/mount-routes.d.ts +19 -0
  82. package/dist/server/mount-routes.js +42 -0
  83. package/dist/templates/api-skeleton.d.ts +18 -0
  84. package/dist/templates/api-skeleton.js +69 -0
  85. package/dist/templates/claude-md.d.ts +4 -0
  86. package/dist/templates/claude-md.js +7 -0
  87. package/dist/templates/dashboard-pages/index.d.ts +101 -0
  88. package/dist/templates/dashboard-pages/index.js +22 -0
  89. package/dist/templates/domain-config.d.ts +10 -0
  90. package/dist/templates/domain-config.js +19 -0
  91. package/dist/templates/events-skeleton.d.ts +9 -0
  92. package/dist/templates/events-skeleton.js +23 -0
  93. package/dist/templates/patterns/api/create-with-event.d.ts +5 -0
  94. package/dist/templates/patterns/api/create-with-event.js +69 -0
  95. package/dist/templates/patterns/api/idempotent-mutation.d.ts +5 -0
  96. package/dist/templates/patterns/api/idempotent-mutation.js +99 -0
  97. package/dist/templates/patterns/api/paginated-list.d.ts +5 -0
  98. package/dist/templates/patterns/api/paginated-list.js +71 -0
  99. package/dist/templates/patterns/api/simple-crud.d.ts +6 -0
  100. package/dist/templates/patterns/api/simple-crud.js +95 -0
  101. package/dist/templates/patterns/api/system-admin.d.ts +5 -0
  102. package/dist/templates/patterns/api/system-admin.js +98 -0
  103. package/dist/templates/patterns/api/webhook-receiver-style.d.ts +5 -0
  104. package/dist/templates/patterns/api/webhook-receiver-style.js +125 -0
  105. package/dist/templates/patterns/component/index.d.ts +25 -0
  106. package/dist/templates/patterns/component/index.js +814 -0
  107. package/dist/templates/patterns/flow/autonomous-remediation.d.ts +5 -0
  108. package/dist/templates/patterns/flow/autonomous-remediation.js +98 -0
  109. package/dist/templates/patterns/flow/fan-out-reaction.d.ts +5 -0
  110. package/dist/templates/patterns/flow/fan-out-reaction.js +53 -0
  111. package/dist/templates/patterns/flow/human-in-loop.d.ts +5 -0
  112. package/dist/templates/patterns/flow/human-in-loop.js +90 -0
  113. package/dist/templates/patterns/flow/multi-step-orchestration.d.ts +5 -0
  114. package/dist/templates/patterns/flow/multi-step-orchestration.js +67 -0
  115. package/dist/templates/patterns/hook/index.d.ts +7 -0
  116. package/dist/templates/patterns/hook/index.js +378 -0
  117. package/dist/templates/patterns/migration/column-add.d.ts +5 -0
  118. package/dist/templates/patterns/migration/column-add.js +52 -0
  119. package/dist/templates/patterns/migration/event-store.d.ts +6 -0
  120. package/dist/templates/patterns/migration/event-store.js +97 -0
  121. package/dist/templates/patterns/migration/index.d.ts +5 -0
  122. package/dist/templates/patterns/migration/index.js +52 -0
  123. package/dist/templates/patterns/migration/rls-policy.d.ts +5 -0
  124. package/dist/templates/patterns/migration/rls-policy.js +78 -0
  125. package/dist/templates/patterns/migration/tenant-scoped-table.d.ts +6 -0
  126. package/dist/templates/patterns/migration/tenant-scoped-table.js +81 -0
  127. package/dist/templates/patterns/page/dashboard.d.ts +4 -0
  128. package/dist/templates/patterns/page/dashboard.js +164 -0
  129. package/dist/templates/patterns/page/detail.d.ts +4 -0
  130. package/dist/templates/patterns/page/detail.js +162 -0
  131. package/dist/templates/patterns/page/form.d.ts +4 -0
  132. package/dist/templates/patterns/page/form.js +192 -0
  133. package/dist/templates/patterns/page/index.d.ts +8 -0
  134. package/dist/templates/patterns/page/index.js +14 -0
  135. package/dist/templates/patterns/page/list.d.ts +4 -0
  136. package/dist/templates/patterns/page/list.js +138 -0
  137. package/dist/templates/patterns/page/settings.d.ts +4 -0
  138. package/dist/templates/patterns/page/settings.js +318 -0
  139. package/dist/templates/patterns/page/wizard.d.ts +4 -0
  140. package/dist/templates/patterns/page/wizard.js +293 -0
  141. package/dist/templates/patterns/subscriber/audit-relay.d.ts +5 -0
  142. package/dist/templates/patterns/subscriber/audit-relay.js +51 -0
  143. package/dist/templates/patterns/subscriber/cascade-deletion.d.ts +5 -0
  144. package/dist/templates/patterns/subscriber/cascade-deletion.js +60 -0
  145. package/dist/templates/patterns/subscriber/single-step-projection.d.ts +5 -0
  146. package/dist/templates/patterns/subscriber/single-step-projection.js +36 -0
  147. package/dist/templates/readme.d.ts +4 -0
  148. package/dist/templates/readme.js +7 -0
  149. package/dist/templates/subscriber-skeleton.d.ts +11 -0
  150. package/dist/templates/subscriber-skeleton.js +23 -0
  151. package/dist/utils/checksum.d.ts +18 -0
  152. package/dist/utils/checksum.js +39 -0
  153. package/dist/utils/file-helpers.d.ts +35 -0
  154. package/dist/utils/file-helpers.js +59 -0
  155. package/dist/utils/header-inject.d.ts +15 -0
  156. package/dist/utils/header-inject.js +93 -0
  157. package/dist/utils/install-file.d.ts +17 -0
  158. package/dist/utils/install-file.js +78 -0
  159. package/dist/utils/logger.d.ts +12 -0
  160. package/dist/utils/logger.js +24 -0
  161. package/dist/utils/manifest.d.ts +28 -0
  162. package/dist/utils/manifest.js +93 -0
  163. package/dist/utils/s3-fetch.d.ts +25 -0
  164. package/dist/utils/s3-fetch.js +52 -0
  165. package/dist/utils/scaffold-config.d.ts +95 -0
  166. package/dist/utils/scaffold-config.js +53 -0
  167. package/dist/utils/token-substitution.d.ts +35 -0
  168. package/dist/utils/token-substitution.js +52 -0
  169. package/dist/utils/zod-extractor.d.ts +10 -0
  170. package/dist/utils/zod-extractor.js +28 -0
  171. package/package.json +43 -0
  172. package/src/__tests__/build-registry.test.ts +115 -0
  173. package/src/__tests__/build-types.test.ts +100 -0
  174. package/src/__tests__/builder/walkDomainDir.test.ts +140 -0
  175. package/src/__tests__/commands/add-domain.test.ts +174 -0
  176. package/src/__tests__/commands/add-flow.test.ts +69 -0
  177. package/src/__tests__/commands/add-module.test.ts +207 -0
  178. package/src/__tests__/commands/build-flows.test.ts +154 -0
  179. package/src/__tests__/commands/check-hashes.test.ts +142 -0
  180. package/src/__tests__/commands/create-project.test.ts +712 -0
  181. package/src/__tests__/commands/upgrade.test.ts +762 -0
  182. package/src/__tests__/doctor.test.ts +291 -0
  183. package/src/__tests__/hydrate-local-ctx.test.ts +71 -0
  184. package/src/__tests__/load-domain-module-config.test.ts +10 -0
  185. package/src/__tests__/mount-routes.test.ts +100 -0
  186. package/src/__tests__/scaffold-src/part-a-layout.test.ts +46 -0
  187. package/src/__tests__/scripts/package-scaffold.test.ts +45 -0
  188. package/src/__tests__/utils/checksum.test.ts +90 -0
  189. package/src/__tests__/utils/header-inject.test.ts +89 -0
  190. package/src/__tests__/utils/install-file.test.ts +207 -0
  191. package/src/__tests__/utils/manifest.test.ts +229 -0
  192. package/src/__tests__/utils/token-substitution.test.ts +134 -0
  193. package/src/__tests__/validate.test.ts +18 -0
  194. package/src/builder/build-registry.ts +237 -0
  195. package/src/builder/build-types.ts +36 -0
  196. package/src/builder/load-domain-module-config.ts +43 -0
  197. package/src/builder/load-module.ts +133 -0
  198. package/src/builder/zod-to-json.ts +16 -0
  199. package/src/cli.ts +387 -0
  200. package/src/commands/add-api.ts +145 -0
  201. package/src/commands/add-component.ts +116 -0
  202. package/src/commands/add-domain.ts +100 -0
  203. package/src/commands/add-flow.ts +136 -0
  204. package/src/commands/add-hook.ts +100 -0
  205. package/src/commands/add-migration.ts +129 -0
  206. package/src/commands/add-module.ts +347 -0
  207. package/src/commands/add-page.ts +242 -0
  208. package/src/commands/add-seed-page.ts +338 -0
  209. package/src/commands/add-subscriber.ts +123 -0
  210. package/src/commands/add-test.ts +328 -0
  211. package/src/commands/audit.ts +217 -0
  212. package/src/commands/build-catalog.ts +181 -0
  213. package/src/commands/build-flows.ts +198 -0
  214. package/src/commands/build.ts +59 -0
  215. package/src/commands/check-hashes.ts +150 -0
  216. package/src/commands/create-project.ts +367 -0
  217. package/src/commands/dev.ts +47 -0
  218. package/src/commands/doctor.ts +1362 -0
  219. package/src/commands/explain.ts +209 -0
  220. package/src/commands/power-tune.ts +112 -0
  221. package/src/commands/reseed-page.ts +410 -0
  222. package/src/commands/show-dns.ts +139 -0
  223. package/src/commands/show.ts +179 -0
  224. package/src/commands/test.ts +91 -0
  225. package/src/commands/upgrade-backend.ts +72 -0
  226. package/src/commands/upgrade-event.ts +175 -0
  227. package/src/commands/upgrade-frontend.ts +135 -0
  228. package/src/commands/upgrade.ts +668 -0
  229. package/src/commands/validate.ts +208 -0
  230. package/src/runtime-stubs/hydrate-local-ctx.ts +102 -0
  231. package/src/runtime-stubs/load-secrets.ts +40 -0
  232. package/src/server/api-server.ts +34 -0
  233. package/src/server/mount-routes.ts +68 -0
  234. package/src/templates/api-skeleton.ts +72 -0
  235. package/src/templates/claude-md.ts +7 -0
  236. package/src/templates/dashboard-pages/account/api-keys.tsx +107 -0
  237. package/src/templates/dashboard-pages/account/audit-log.tsx +60 -0
  238. package/src/templates/dashboard-pages/account/index.ts +5 -0
  239. package/src/templates/dashboard-pages/account/members.tsx +107 -0
  240. package/src/templates/dashboard-pages/account/profile.tsx +53 -0
  241. package/src/templates/dashboard-pages/account/workspace-settings.tsx +64 -0
  242. package/src/templates/dashboard-pages/auth/accept-invitation.tsx +62 -0
  243. package/src/templates/dashboard-pages/auth/choose-org.tsx +66 -0
  244. package/src/templates/dashboard-pages/auth/forgot-password.tsx +69 -0
  245. package/src/templates/dashboard-pages/auth/index.ts +10 -0
  246. package/src/templates/dashboard-pages/auth/login.tsx +75 -0
  247. package/src/templates/dashboard-pages/auth/mfa-setup.tsx +56 -0
  248. package/src/templates/dashboard-pages/auth/mfa-verify.tsx +49 -0
  249. package/src/templates/dashboard-pages/auth/reset-password.tsx +64 -0
  250. package/src/templates/dashboard-pages/auth/sign-out.tsx +20 -0
  251. package/src/templates/dashboard-pages/auth/signup.tsx +71 -0
  252. package/src/templates/dashboard-pages/auth/verify-email.tsx +53 -0
  253. package/src/templates/dashboard-pages/index.ts +22 -0
  254. package/src/templates/dashboard-pages/shell/dashboard-home.tsx +41 -0
  255. package/src/templates/dashboard-pages/shell/forbidden.tsx +46 -0
  256. package/src/templates/dashboard-pages/shell/index.ts +5 -0
  257. package/src/templates/dashboard-pages/shell/maintenance.tsx +27 -0
  258. package/src/templates/dashboard-pages/shell/not-found.tsx +34 -0
  259. package/src/templates/dashboard-pages/shell/server-error.tsx +44 -0
  260. package/src/templates/domain-config.ts +20 -0
  261. package/src/templates/events-skeleton.ts +24 -0
  262. package/src/templates/patterns/api/create-with-event.ts +72 -0
  263. package/src/templates/patterns/api/idempotent-mutation.ts +102 -0
  264. package/src/templates/patterns/api/paginated-list.ts +74 -0
  265. package/src/templates/patterns/api/simple-crud.ts +100 -0
  266. package/src/templates/patterns/api/system-admin.ts +101 -0
  267. package/src/templates/patterns/api/webhook-receiver-style.ts +128 -0
  268. package/src/templates/patterns/component/index.ts +833 -0
  269. package/src/templates/patterns/flow/autonomous-remediation.ts +101 -0
  270. package/src/templates/patterns/flow/fan-out-reaction.ts +56 -0
  271. package/src/templates/patterns/flow/human-in-loop.ts +93 -0
  272. package/src/templates/patterns/flow/multi-step-orchestration.ts +70 -0
  273. package/src/templates/patterns/hook/index.ts +382 -0
  274. package/src/templates/patterns/migration/column-add.ts +54 -0
  275. package/src/templates/patterns/migration/event-store.ts +99 -0
  276. package/src/templates/patterns/migration/index.ts +54 -0
  277. package/src/templates/patterns/migration/rls-policy.ts +80 -0
  278. package/src/templates/patterns/migration/tenant-scoped-table.ts +83 -0
  279. package/src/templates/patterns/page/dashboard.ts +164 -0
  280. package/src/templates/patterns/page/detail.ts +162 -0
  281. package/src/templates/patterns/page/form.ts +192 -0
  282. package/src/templates/patterns/page/index.ts +17 -0
  283. package/src/templates/patterns/page/list.ts +138 -0
  284. package/src/templates/patterns/page/settings.ts +318 -0
  285. package/src/templates/patterns/page/wizard.ts +293 -0
  286. package/src/templates/patterns/subscriber/audit-relay.ts +54 -0
  287. package/src/templates/patterns/subscriber/cascade-deletion.ts +63 -0
  288. package/src/templates/patterns/subscriber/single-step-projection.ts +39 -0
  289. package/src/templates/readme.ts +7 -0
  290. package/src/templates/subscriber-skeleton.ts +28 -0
  291. package/src/utils/checksum.ts +43 -0
  292. package/src/utils/file-helpers.ts +91 -0
  293. package/src/utils/header-inject.ts +126 -0
  294. package/src/utils/install-file.ts +99 -0
  295. package/src/utils/logger.ts +26 -0
  296. package/src/utils/manifest.ts +137 -0
  297. package/src/utils/s3-fetch.ts +91 -0
  298. package/src/utils/scaffold-config.ts +172 -0
  299. package/src/utils/token-substitution.ts +80 -0
  300. package/src/utils/zod-extractor.ts +31 -0
  301. package/tsconfig.json +13 -0
@@ -0,0 +1,668 @@
1
+ import { createGunzip } from 'node:zlib';
2
+ import { Readable } from 'node:stream';
3
+ import { mkdir, writeFile, unlink } from 'node:fs/promises';
4
+ import { join, resolve, dirname } from 'node:path';
5
+ import { execSync } from 'node:child_process';
6
+ import { cliLogger } from '../utils/logger.js';
7
+ import {
8
+ fetchVersionsJson,
9
+ fetchModulesJson,
10
+ fetchModuleTarball,
11
+ fetchScaffoldFile,
12
+ type S3ModuleEntry,
13
+ } from '../utils/s3-fetch.js';
14
+ import { computeChecksumString } from '../utils/checksum.js';
15
+ import { applyTokens, buildTokenContext } from '../utils/token-substitution.js';
16
+ import { injectHeader } from '../utils/header-inject.js';
17
+ import {
18
+ readManifest,
19
+ writeManifest,
20
+ upsertManifestFile,
21
+ removeManifestFile,
22
+ inferPolicyFromPath,
23
+ type TibManifest,
24
+ type ManifestFileEntry,
25
+ } from '../utils/manifest.js';
26
+ import { installScaffoldFile } from '../utils/install-file.js';
27
+ import { readScaffoldConfig, writeScaffoldConfig, type ModuleId } from '../utils/scaffold-config.js';
28
+
29
+ const SCAFFOLD_BUCKET = 'mc-scaffold';
30
+
31
+ // ── Tarball types ──────────────────────────────────────────────────────────────
32
+
33
+ interface TarEntry {
34
+ path: string;
35
+ content: Buffer;
36
+ }
37
+
38
+ interface TarballManifestEntry {
39
+ path: string;
40
+ sha256: string;
41
+ isTemplate: boolean;
42
+ installedAs?: string;
43
+ policy?: 'owned' | 'tracked' | 'seed';
44
+ }
45
+
46
+ // ── Upgrade result tracking ────────────────────────────────────────────────────
47
+
48
+ type FileStatus = 'added' | 'updated' | 'conflict' | 'deleted' | 'unchanged';
49
+
50
+ interface UpgradeFileResult {
51
+ path: string;
52
+ status: FileStatus;
53
+ module: string;
54
+ }
55
+
56
+ // ── Tarball parsing (same impl as create-project.ts) ──────────────────────────
57
+
58
+ async function parseTarball(buf: Buffer): Promise<TarEntry[]> {
59
+ const decompressed = await new Promise<Buffer>((res, rej) => {
60
+ const gunzip = createGunzip();
61
+ const chunks: Buffer[] = [];
62
+ const input = Readable.from(buf);
63
+ input.pipe(gunzip);
64
+ gunzip.on('data', (chunk: Buffer) =>
65
+ chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk as ArrayBuffer))
66
+ );
67
+ gunzip.on('end', () => res(Buffer.concat(chunks)));
68
+ gunzip.on('error', rej);
69
+ });
70
+
71
+ const entries: TarEntry[] = [];
72
+ let offset = 0;
73
+
74
+ while (offset + 512 <= decompressed.length) {
75
+ const header = decompressed.slice(offset, offset + 512);
76
+ if (header.every((b) => b === 0)) break;
77
+
78
+ let name = header.slice(0, 100).toString('utf-8').replace(/\0.*/, '');
79
+ const prefix = header.slice(345, 500).toString('utf-8').replace(/\0.*/, '');
80
+ if (prefix) name = `${prefix}/${name}`;
81
+
82
+ const sizeStr = header.slice(124, 136).toString('utf-8').replace(/\0.*/, '').trim();
83
+ const size = parseInt(sizeStr, 8) || 0;
84
+ const typeFlag = header[156];
85
+ const isRegularFile = typeFlag === 0x30 || typeFlag === 0 || typeFlag === undefined;
86
+
87
+ offset += 512;
88
+
89
+ if (isRegularFile && name && size > 0) {
90
+ const content = decompressed.slice(offset, offset + size);
91
+ entries.push({ path: name, content });
92
+ }
93
+
94
+ offset += Math.ceil(size / 512) * 512;
95
+ }
96
+
97
+ return entries;
98
+ }
99
+
100
+ function getTarEntry(entries: TarEntry[], targetPath: string): TarEntry | undefined {
101
+ return entries.find((e) => {
102
+ const normalized = e.path.replace(/^\.\//, '').replace(/^[^/]+\//, '');
103
+ return normalized === targetPath || e.path === targetPath || e.path.endsWith(`/${targetPath}`);
104
+ });
105
+ }
106
+
107
+ /**
108
+ * Check if a file path is a seed file (user-owned, not auto-upgraded).
109
+ * Seed files include: pages/auth/*, pages/account/*, pages/shell/*, pages/_errors/*, layouts/*, styles/brand.css
110
+ */
111
+ function isSeedFile(filePath: string): boolean {
112
+ const seedPatterns = [
113
+ /^frontend\/src\/pages\/auth\//,
114
+ /^frontend\/src\/pages\/account\//,
115
+ /^frontend\/src\/pages\/shell\//,
116
+ /^frontend\/src\/pages\/_errors\//,
117
+ /^frontend\/src\/layouts\//,
118
+ /^frontend\/src\/styles\/brand\.css$/,
119
+ ];
120
+ return seedPatterns.some((pattern) => pattern.test(filePath));
121
+ }
122
+
123
+ // ── Topological sort ───────────────────────────────────────────────────────────
124
+
125
+ function topoSort(modules: S3ModuleEntry[], selected: Set<string>): S3ModuleEntry[] {
126
+ const byId = new Map(modules.map((m) => [m.id, m]));
127
+ const result: S3ModuleEntry[] = [];
128
+ const visited = new Set<string>();
129
+
130
+ function visit(id: string): void {
131
+ if (visited.has(id)) return;
132
+ visited.add(id);
133
+ const mod = byId.get(id);
134
+ if (!mod) return;
135
+ for (const dep of mod.dependencies) {
136
+ if (selected.has(dep)) visit(dep);
137
+ }
138
+ result.push(mod);
139
+ }
140
+
141
+ for (const id of ['core', 'backend-lambda']) {
142
+ if (selected.has(id)) visit(id);
143
+ }
144
+ for (const id of selected) visit(id);
145
+
146
+ return result;
147
+ }
148
+
149
+ // ── GitHub helpers ─────────────────────────────────────────────────────────────
150
+
151
+ function detectGitRemote(projectDir: string): { owner: string; repo: string } | null {
152
+ try {
153
+ const url = execSync('git remote get-url origin', {
154
+ cwd: projectDir,
155
+ encoding: 'utf8',
156
+ stdio: ['pipe', 'pipe', 'pipe'],
157
+ }).trim();
158
+
159
+ // SSH: git@github.com:owner/repo.git
160
+ const sshMatch = url.match(/git@github\.com:([^/]+)\/([^.]+?)(?:\.git)?$/);
161
+ if (sshMatch) return { owner: sshMatch[1], repo: sshMatch[2] };
162
+
163
+ // HTTPS: https://github.com/owner/repo.git
164
+ const httpsMatch = url.match(/github\.com\/([^/]+)\/([^/]+?)(?:\.git)?(?:\/)?$/);
165
+ if (httpsMatch) return { owner: httpsMatch[1], repo: httpsMatch[2] };
166
+
167
+ return null;
168
+ } catch {
169
+ return null;
170
+ }
171
+ }
172
+
173
+ async function createGitHubPR(
174
+ owner: string,
175
+ repo: string,
176
+ token: string,
177
+ branch: string,
178
+ title: string,
179
+ body: string,
180
+ labels?: string[]
181
+ ): Promise<{ url: string; number: number }> {
182
+ const url = `https://api.github.com/repos/${owner}/${repo}/pulls`;
183
+ const res = await fetch(url, {
184
+ method: 'POST',
185
+ headers: {
186
+ Authorization: `Bearer ${token}`,
187
+ Accept: 'application/vnd.github+json',
188
+ 'Content-Type': 'application/json',
189
+ 'X-GitHub-Api-Version': '2022-11-28',
190
+ },
191
+ body: JSON.stringify({
192
+ title,
193
+ body,
194
+ head: branch,
195
+ base: 'develop',
196
+ ...(labels && labels.length > 0 && { labels }),
197
+ }),
198
+ });
199
+
200
+ if (!res.ok) {
201
+ const err = await res.text();
202
+ throw new Error(`GitHub PR creation failed (${res.status}): ${err}`);
203
+ }
204
+
205
+ const data = (await res.json()) as { html_url: string; number: number };
206
+ return { url: data.html_url, number: data.number };
207
+ }
208
+
209
+ // ── PR body builder ────────────────────────────────────────────────────────────
210
+
211
+ function buildPrBody(
212
+ currentVersion: string,
213
+ targetVersion: string,
214
+ results: UpgradeFileResult[],
215
+ changelogUrl: string | null
216
+ ): string {
217
+ const added = results.filter((r) => r.status === 'added');
218
+ const updated = results.filter((r) => r.status === 'updated');
219
+ const deleted = results.filter((r) => r.status === 'deleted');
220
+ const conflicts = results.filter((r) => r.status === 'conflict');
221
+
222
+ const lines: string[] = [
223
+ `## TIB Scaffold Upgrade: ${currentVersion} → ${targetVersion}`,
224
+ '',
225
+ '### Summary',
226
+ `- **Added:** ${added.length} file(s)`,
227
+ `- **Updated:** ${updated.length} file(s)`,
228
+ `- **Deleted:** ${deleted.length} file(s)`,
229
+ `- **Conflicts (drift):** ${conflicts.length} file(s)`,
230
+ '',
231
+ ];
232
+
233
+ if (added.length > 0) {
234
+ lines.push('### Added files');
235
+ for (const r of added) lines.push(`- \`${r.path}\` _(${r.module})_`);
236
+ lines.push('');
237
+ }
238
+
239
+ if (updated.length > 0) {
240
+ lines.push('### Updated files');
241
+ for (const r of updated) lines.push(`- \`${r.path}\` _(${r.module})_`);
242
+ lines.push('');
243
+ }
244
+
245
+ if (deleted.length > 0) {
246
+ lines.push('### Deleted files');
247
+ for (const r of deleted) lines.push(`- \`${r.path}\` _(${r.module})_`);
248
+ lines.push('');
249
+ }
250
+
251
+ if (conflicts.length > 0) {
252
+ lines.push('### Drift warnings — manual review required');
253
+ lines.push(
254
+ 'The following files were locally modified after scaffold installation. ' +
255
+ 'New versions have been written to `{path}.tib-upgrade` — merge manually then remove the `.tib-upgrade` file.'
256
+ );
257
+ for (const r of conflicts) lines.push(`- \`${r.path}\` → \`${r.path}.tib-upgrade\``);
258
+ lines.push('');
259
+ }
260
+
261
+ if (changelogUrl) {
262
+ lines.push(`### Changelog`);
263
+ lines.push(`See full changelog: ${changelogUrl}`);
264
+ lines.push('');
265
+ }
266
+
267
+ lines.push('### Visual diff');
268
+ lines.push('');
269
+ lines.push('This PR has been automatically labelled `tib-frontend-upgrade`.');
270
+ lines.push('The Chromatic job will run and post a visual diff link here.');
271
+ lines.push('');
272
+ lines.push('**Before merging:** A reviewer must comment `visual diff reviewed` to acknowledge they have checked the Chromatic baseline diff.');
273
+ lines.push('');
274
+ lines.push('> Chromatic baseline link will appear in the Chromatic job output above once CI completes.');
275
+ lines.push('');
276
+
277
+ return lines.join('\n');
278
+ }
279
+
280
+ function buildFrontendComponentsPrBody(
281
+ currentVersion: string,
282
+ targetVersion: string,
283
+ results: UpgradeFileResult[],
284
+ changelogUrl: string | null
285
+ ): string {
286
+ const added = results.filter((r) => r.status === 'added');
287
+ const updated = results.filter((r) => r.status === 'updated');
288
+ const deleted = results.filter((r) => r.status === 'deleted');
289
+ const conflicts = results.filter((r) => r.status === 'conflict');
290
+
291
+ const lines: string[] = [
292
+ `## TIB Frontend Components Upgrade: ${currentVersion} → ${targetVersion}`,
293
+ '',
294
+ '### Summary',
295
+ `Upgrades scaffold-tracked frontend component files only (seed pages excluded).`,
296
+ '',
297
+ `- **Added:** ${added.length} file(s)`,
298
+ `- **Updated:** ${updated.length} file(s)`,
299
+ `- **Deleted:** ${deleted.length} file(s)`,
300
+ `- **Conflicts (drift):** ${conflicts.length} file(s)`,
301
+ '',
302
+ ];
303
+
304
+ if (added.length > 0) {
305
+ lines.push('### Added files');
306
+ for (const r of added) lines.push(`- \`${r.path}\` _(${r.module})_`);
307
+ lines.push('');
308
+ }
309
+
310
+ if (updated.length > 0) {
311
+ lines.push('### Updated files');
312
+ for (const r of updated) lines.push(`- \`${r.path}\` _(${r.module})_`);
313
+ lines.push('');
314
+ }
315
+
316
+ if (deleted.length > 0) {
317
+ lines.push('### Deleted files');
318
+ for (const r of deleted) lines.push(`- \`${r.path}\` _(${r.module})_`);
319
+ lines.push('');
320
+ }
321
+
322
+ if (conflicts.length > 0) {
323
+ lines.push('### Drift warnings — manual review required');
324
+ lines.push(
325
+ 'The following files were locally modified after scaffold installation. ' +
326
+ 'New versions have been written to `{path}.tib-upgrade` — merge manually then remove the `.tib-upgrade` file.'
327
+ );
328
+ for (const r of conflicts) lines.push(`- \`${r.path}\` → \`${r.path}.tib-upgrade\``);
329
+ lines.push('');
330
+ }
331
+
332
+ if (changelogUrl) {
333
+ lines.push(`### Visual diff`);
334
+ lines.push(`See Chromatic visual diff (when available): ${changelogUrl}`);
335
+ lines.push('');
336
+ lines.push(`> **Reviewer action required:** Comment \`visual diff reviewed\` on this PR after checking the Chromatic baseline diff. The \`require-visual-diff-review\` CI check will block merge until this comment is present.`);
337
+ lines.push('');
338
+ }
339
+
340
+ return lines.join('\n');
341
+ }
342
+
343
+ // ── Main export ────────────────────────────────────────────────────────────────
344
+
345
+ export interface UpgradeOptions {
346
+ dryRun: boolean;
347
+ projectDir: string;
348
+ githubToken?: string;
349
+ frontendComponents?: boolean;
350
+ }
351
+
352
+ export async function runUpgrade(
353
+ packageSpec: string | undefined,
354
+ opts: UpgradeOptions
355
+ ): Promise<void> {
356
+ const projectDir = resolve(opts.projectDir ?? process.cwd());
357
+
358
+ console.log(`\nTIB Upgrade${opts.dryRun ? ' (dry run)' : ''}\n`);
359
+ console.log(`Project: ${projectDir}\n`);
360
+
361
+ // 1. Read manifest + scaffold-config
362
+ const manifest = await readManifest(projectDir);
363
+ if (!manifest) {
364
+ throw new Error(
365
+ `.mc/manifest.json not found in ${projectDir}. Is this a TIB scaffold project?`
366
+ );
367
+ }
368
+
369
+ const scaffoldConfig = await readScaffoldConfig(projectDir);
370
+ const currentVersion = manifest.scaffoldVersion;
371
+
372
+ // 2. Resolve target version
373
+ const versionsJson = await fetchVersionsJson(
374
+ scaffoldConfig.scaffoldBucket ?? SCAFFOLD_BUCKET
375
+ );
376
+ const targetVersion = packageSpec ?? versionsJson.latest;
377
+
378
+ console.log(`Current version : ${currentVersion}`);
379
+ console.log(`Target version : ${targetVersion}\n`);
380
+
381
+ if (currentVersion === targetVersion) {
382
+ console.log('Already at target version — nothing to do.');
383
+ cliLogger.info({ currentVersion, targetVersion }, 'upgrade: already at target version');
384
+ return;
385
+ }
386
+
387
+ const bucket = scaffoldConfig.scaffoldBucket ?? SCAFFOLD_BUCKET;
388
+ const targetModulesJson = await fetchModulesJson(bucket, targetVersion);
389
+
390
+ // 3. Resolve enabled modules in topological order
391
+ let enabledSet = new Set(scaffoldConfig.enabledModules);
392
+
393
+ // If --frontend-components flag is set, scope to frontend module only
394
+ if (opts.frontendComponents) {
395
+ enabledSet = new Set(['frontend']);
396
+ }
397
+
398
+ const orderedModules = topoSort(targetModulesJson.modules, enabledSet);
399
+
400
+ // Build current version module map (for change detection)
401
+ let currentModulesJson: Awaited<ReturnType<typeof fetchModulesJson>> | null = null;
402
+ try {
403
+ currentModulesJson = await fetchModulesJson(bucket, currentVersion);
404
+ } catch {
405
+ // If current release is gone from S3, proceed without skipping unchanged modules
406
+ }
407
+ const currentModuleVersionMap = new Map<string, string>(
408
+ (currentModulesJson?.modules ?? []).map((m) => [m.id, m.version])
409
+ );
410
+
411
+ // 4. Get CLI version
412
+ let cliVersion = '0.0.0';
413
+ try {
414
+ const { createRequire } = await import('node:module');
415
+ const require = createRequire(import.meta.url);
416
+ const pkgJson = require('../../package.json') as { version: string };
417
+ cliVersion = pkgJson.version;
418
+ } catch {
419
+ // ignore
420
+ }
421
+
422
+ // 5. Build token context
423
+ const tokenCtx = buildTokenContext(
424
+ {
425
+ projectName: manifest.projectName,
426
+ awsRegion: manifest.awsRegion,
427
+ awsAccountId: scaffoldConfig.awsAccountId,
428
+ adminEmail: scaffoldConfig.adminEmail,
429
+ },
430
+ targetVersion,
431
+ cliVersion
432
+ );
433
+
434
+ // 6. Process each module
435
+ const allResults: UpgradeFileResult[] = [];
436
+ const updatedManifest: TibManifest = { ...manifest, files: [...manifest.files] };
437
+
438
+ // Track all file paths present in the target release (to detect deletions)
439
+ const targetFilePaths = new Set<string>();
440
+
441
+ for (const mod of orderedModules) {
442
+ const currentModVer = currentModuleVersionMap.get(mod.id);
443
+ if (currentModVer !== undefined && currentModVer === mod.version) {
444
+ // Module version unchanged — no file changes possible; still track paths
445
+ const currentModFiles = manifest.files.filter((f) => f.module === mod.id);
446
+ for (const f of currentModFiles) targetFilePaths.add(f.path);
447
+ cliLogger.debug({ moduleId: mod.id, version: mod.version }, 'upgrade: module unchanged, skipping');
448
+ continue;
449
+ }
450
+
451
+ console.log(` Processing module: ${mod.id}@${mod.version}...`);
452
+
453
+ const tarBuf = await fetchModuleTarball(bucket, targetVersion, mod.tarball, mod.sha256);
454
+ const tarEntries = await parseTarball(tarBuf);
455
+
456
+ const manifestEntry = getTarEntry(tarEntries, 'MANIFEST.json');
457
+ if (!manifestEntry) {
458
+ cliLogger.warn({ moduleId: mod.id }, 'upgrade: No MANIFEST.json in tarball — skipping module');
459
+ continue;
460
+ }
461
+
462
+ const tarManifest = JSON.parse(
463
+ manifestEntry.content.toString('utf-8')
464
+ ) as TarballManifestEntry[];
465
+
466
+ for (const fileEntry of tarManifest) {
467
+ const tarEntry = getTarEntry(tarEntries, fileEntry.path);
468
+ if (!tarEntry) {
469
+ cliLogger.warn({ moduleId: mod.id, path: fileEntry.path }, 'upgrade: file listed in MANIFEST.json not found in tarball');
470
+ continue;
471
+ }
472
+
473
+ // Resolve install path
474
+ let installPath = fileEntry.installedAs ?? fileEntry.path;
475
+ if (installPath.endsWith('.tpl')) installPath = installPath.slice(0, -4);
476
+
477
+ // When --frontend-components flag is set, skip seed files
478
+ if (opts.frontendComponents && isSeedFile(installPath)) {
479
+ cliLogger.debug({ moduleId: mod.id, path: installPath }, 'upgrade: skipping seed file (--frontend-components scoped)');
480
+ continue;
481
+ }
482
+
483
+ targetFilePaths.add(installPath);
484
+
485
+ // Process new content
486
+ let newContent = tarEntry.content.toString('utf-8');
487
+ if (fileEntry.isTemplate) {
488
+ newContent = applyTokens(newContent, tokenCtx);
489
+ }
490
+ newContent = injectHeader(newContent, installPath, mod.id, mod.version);
491
+
492
+ // Determine policy: use fileEntry.policy if present, else infer from path
493
+ const policy = fileEntry.policy ?? inferPolicyFromPath(installPath);
494
+
495
+ // Look up current manifest entry for this file
496
+ const currentEntry: ManifestFileEntry | undefined = updatedManifest.files.find(
497
+ (f) => f.path === installPath
498
+ );
499
+
500
+ const diskPath = join(projectDir, installPath);
501
+
502
+ // Install file using policy-based dispatch
503
+ const installResult = await installScaffoldFile(diskPath, newContent, policy, currentEntry, {
504
+ dryRun: opts.dryRun,
505
+ });
506
+
507
+ // Handle result
508
+ if (installResult.status === 'skipped') {
509
+ // Skipped files are not tracked in results (e.g., seed file with --frontend-components)
510
+ continue;
511
+ }
512
+
513
+ // Add to results
514
+ allResults.push({ path: installPath, status: installResult.status, module: mod.id });
515
+
516
+ // Update manifest if file was not skipped
517
+ const newChecksum = computeChecksumString(newContent);
518
+ upsertManifestFile(updatedManifest, {
519
+ path: installPath,
520
+ module: mod.id,
521
+ moduleVersion: mod.version,
522
+ sha256: newChecksum,
523
+ wasTemplate: fileEntry.isTemplate,
524
+ installedAt: new Date().toISOString(),
525
+ policy,
526
+ });
527
+ }
528
+ }
529
+
530
+ // 7. Handle deleted files (in current manifest but not in target release)
531
+ const currentManagedFiles = manifest.files.filter((f) => enabledSet.has(f.module as ModuleId));
532
+ for (const f of currentManagedFiles) {
533
+ if (!targetFilePaths.has(f.path)) {
534
+ const diskPath = join(projectDir, f.path);
535
+ if (!opts.dryRun) {
536
+ try {
537
+ await unlink(diskPath);
538
+ } catch (err: unknown) {
539
+ if ((err as NodeJS.ErrnoException).code !== 'ENOENT') throw err;
540
+ }
541
+ }
542
+ removeManifestFile(updatedManifest, f.path);
543
+ allResults.push({ path: f.path, status: 'deleted', module: f.module });
544
+ }
545
+ }
546
+
547
+ // 8. Print upgrade report
548
+ const added = allResults.filter((r) => r.status === 'added');
549
+ const updated = allResults.filter((r) => r.status === 'updated');
550
+ const deleted = allResults.filter((r) => r.status === 'deleted');
551
+ const conflicts = allResults.filter((r) => r.status === 'conflict');
552
+
553
+ console.log('\nUpgrade report:');
554
+ console.log(` Added : ${added.length}`);
555
+ console.log(` Updated : ${updated.length}`);
556
+ console.log(` Deleted : ${deleted.length}`);
557
+ console.log(` Conflicts (drift): ${conflicts.length}`);
558
+
559
+ if (conflicts.length > 0) {
560
+ console.log('\nDrift warnings:');
561
+ for (const r of conflicts) {
562
+ console.log(` ${r.path} — new version written to ${r.path}.tib-upgrade`);
563
+ }
564
+ }
565
+
566
+ if (opts.dryRun) {
567
+ console.log('\nDry run complete — no files were written.\n');
568
+ return;
569
+ }
570
+
571
+ // 9. Update manifest + scaffold-config
572
+ updatedManifest.scaffoldVersion = targetVersion;
573
+ await writeManifest(projectDir, updatedManifest);
574
+
575
+ const updatedConfig = { ...scaffoldConfig, scaffoldVersion: targetVersion };
576
+ await writeScaffoldConfig(projectDir, updatedConfig);
577
+
578
+ // 10. Commit on upgrade branch
579
+ const branchName = `tib-upgrade/${targetVersion}`;
580
+ try {
581
+ execSync(`git -C "${projectDir}" checkout -b "${branchName}"`, {
582
+ stdio: ['pipe', 'pipe', 'pipe'],
583
+ });
584
+ } catch {
585
+ // Branch may already exist
586
+ execSync(`git -C "${projectDir}" checkout "${branchName}"`, {
587
+ stdio: ['pipe', 'pipe', 'pipe'],
588
+ });
589
+ }
590
+
591
+ execSync(`git -C "${projectDir}" add -A`, { stdio: 'pipe' });
592
+
593
+ let hasChanges = false;
594
+ try {
595
+ const status = execSync(`git -C "${projectDir}" status --porcelain`, {
596
+ encoding: 'utf8',
597
+ stdio: ['pipe', 'pipe', 'pipe'],
598
+ }).trim();
599
+ hasChanges = status.length > 0;
600
+ } catch {
601
+ // ignore
602
+ }
603
+
604
+ if (hasChanges) {
605
+ execSync(
606
+ `git -C "${projectDir}" commit -m "chore: tib scaffold upgrade ${currentVersion} -> ${targetVersion}"`,
607
+ { stdio: 'pipe' }
608
+ );
609
+
610
+ try {
611
+ execSync(`git -C "${projectDir}" push --set-upstream origin "${branchName}"`, {
612
+ stdio: 'pipe',
613
+ });
614
+ } catch {
615
+ cliLogger.warn({ branchName }, 'upgrade: git push failed — skipping PR creation');
616
+ console.log(`\nCommit created on branch: ${branchName}`);
617
+ console.log('Note: push failed — create the PR manually.\n');
618
+ return;
619
+ }
620
+
621
+ // 11. Create GitHub PR
622
+ const token =
623
+ opts.githubToken ?? process.env['GITHUB_TOKEN'];
624
+ const remote = detectGitRemote(projectDir);
625
+
626
+ if (!token) {
627
+ console.log(`\nBranch pushed: ${branchName}`);
628
+ console.log('Set GITHUB_TOKEN or pass --github-token to create a PR automatically.\n');
629
+ return;
630
+ }
631
+
632
+ if (!remote) {
633
+ console.log(`\nBranch pushed: ${branchName}`);
634
+ console.log('Could not detect GitHub owner/repo from git remote — create the PR manually.\n');
635
+ return;
636
+ }
637
+
638
+ const changelogUrl = await fetchScaffoldFile(bucket, targetVersion, 'CHANGELOG.md')
639
+ .then((c) => (c ? `https://${bucket}.s3.amazonaws.com/versions/${targetVersion}/CHANGELOG.md` : null))
640
+ .catch(() => null);
641
+
642
+ const prBody = opts.frontendComponents
643
+ ? buildFrontendComponentsPrBody(currentVersion, targetVersion, allResults, changelogUrl)
644
+ : buildPrBody(currentVersion, targetVersion, allResults, changelogUrl);
645
+
646
+ const prResult = await createGitHubPR(
647
+ remote.owner,
648
+ remote.repo,
649
+ token,
650
+ branchName,
651
+ opts.frontendComponents
652
+ ? `chore: tib scaffold frontend components upgrade ${currentVersion} → ${targetVersion}`
653
+ : `chore: tib scaffold upgrade ${currentVersion} → ${targetVersion}`,
654
+ prBody,
655
+ opts.frontendComponents ? ['tib-frontend-upgrade'] : undefined
656
+ );
657
+
658
+ console.log(`\nPR created: ${prResult.url}\n`);
659
+ cliLogger.info({ prUrl: prResult.url, targetVersion }, 'upgrade: PR created');
660
+ } else {
661
+ console.log('\nNo file changes — skipping commit and PR.\n');
662
+ }
663
+
664
+ cliLogger.info(
665
+ { currentVersion, targetVersion, added: added.length, updated: updated.length, deleted: deleted.length, conflicts: conflicts.length },
666
+ 'upgrade complete'
667
+ );
668
+ }