@astryxdesign/cli 0.6.0 → 0.6.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (219) hide show
  1. package/CHANGELOG.md +48 -1
  2. package/README.md +76 -67
  3. package/api/build/build.test.mjs +37 -0
  4. package/api/build/build.type.mjs +1 -1
  5. package/api/build/kit/kit.mjs +31 -1
  6. package/api/component/_adapter.mjs +14 -28
  7. package/api/component/integration-import-agreement.test.mjs +318 -0
  8. package/api/doctor/doctor.d.mts +32 -3
  9. package/api/doctor/doctor.doc.mjs +2 -1
  10. package/api/doctor/doctor.mjs +97 -4
  11. package/api/doctor/doctor.test.mjs +90 -1
  12. package/api/gap-report/gap-report-worker.d.mts +4 -0
  13. package/api/gap-report/gap-report-worker.mjs +73 -0
  14. package/api/gap-report/gap-report.d.mts +81 -0
  15. package/api/gap-report/gap-report.doc.d.mts +9 -0
  16. package/api/gap-report/gap-report.doc.mjs +127 -0
  17. package/api/gap-report/gap-report.mjs +707 -0
  18. package/api/gap-report/gap-report.test.mjs +1210 -0
  19. package/api/gap-report/gap-report.type.d.mts +88 -0
  20. package/api/gap-report/gap-report.type.mjs +69 -0
  21. package/api/index.d.mts +8 -1
  22. package/api/index.mjs +24 -1
  23. package/api/integration/add-contribution.d.mts +44 -0
  24. package/api/integration/add-contribution.mjs +1160 -0
  25. package/api/integration/add-contribution.test.mjs +733 -0
  26. package/api/integration/add-helpers.d.mts +80 -0
  27. package/api/integration/add-helpers.mjs +333 -0
  28. package/api/integration/add-helpers.test.mjs +161 -0
  29. package/api/integration/add-theme.d.mts +10 -0
  30. package/api/integration/add-theme.mjs +332 -0
  31. package/api/integration/add-theme.test.mjs +194 -0
  32. package/api/integration/integration-authoring.type.d.mts +55 -0
  33. package/api/integration/integration-authoring.type.mjs +76 -0
  34. package/api/integration/integration-block-exports.test.mjs +4 -0
  35. package/api/integration/integrationAdd.doc.d.mts +5 -0
  36. package/api/integration/integrationAdd.doc.mjs +100 -0
  37. package/api/integration/integrationAddAgentDoc.doc.d.mts +5 -0
  38. package/api/integration/integrationAddAgentDoc.doc.mjs +49 -0
  39. package/api/integration/integrationAddCodemod.doc.d.mts +5 -0
  40. package/api/integration/integrationAddCodemod.doc.mjs +55 -0
  41. package/api/integration/integrationAddComponent.doc.d.mts +5 -0
  42. package/api/integration/integrationAddComponent.doc.mjs +49 -0
  43. package/api/integration/integrationAddDoc.doc.d.mts +5 -0
  44. package/api/integration/integrationAddDoc.doc.mjs +59 -0
  45. package/api/integration/integrationAddTemplate.doc.d.mts +5 -0
  46. package/api/integration/integrationAddTemplate.doc.mjs +55 -0
  47. package/api/integration/integrationAddTheme.doc.d.mts +5 -0
  48. package/api/integration/integrationAddTheme.doc.mjs +85 -0
  49. package/api/integration/integrationPackCheck.doc.d.mts +5 -0
  50. package/api/integration/integrationPackCheck.doc.mjs +35 -0
  51. package/api/integration/pack-check.d.mts +27 -0
  52. package/api/integration/pack-check.mjs +795 -0
  53. package/api/integration/pack-check.test.mjs +569 -0
  54. package/api/integration/pack-check.type.d.mts +45 -0
  55. package/api/integration/pack-check.type.mjs +56 -0
  56. package/api/integration/public-api.test.mjs +21 -0
  57. package/api/integration/validate-integration.mjs +221 -11
  58. package/api/integration/validate-integration.test.mjs +189 -5
  59. package/api/integration/validateIntegration.doc.mjs +2 -2
  60. package/api/json/index.ts +1 -0
  61. package/api/search/search.mjs +19 -1
  62. package/api/theme/_adapter.d.mts +26 -28
  63. package/api/theme/_adapter.mjs +101 -38
  64. package/api/theme/add/add.d.mts +2 -1
  65. package/api/theme/add/add.mjs +56 -20
  66. package/api/theme/add/add.test.mjs +1 -0
  67. package/api/theme/build/build.d.mts +25 -0
  68. package/api/theme/build/build.mjs +101 -70
  69. package/api/theme/build/build.test.mjs +77 -44
  70. package/api/theme/integration-themes.test.mjs +183 -0
  71. package/api/theme/list/list.d.mts +10 -2
  72. package/api/theme/list/list.mjs +31 -10
  73. package/api/theme/list/list.test.mjs +102 -23
  74. package/api/theme/listThemes.doc.d.mts +1 -5
  75. package/api/theme/listThemes.doc.mjs +6 -13
  76. package/api/theme/targets/targets.test.mjs +22 -8
  77. package/api/theme/theme.d.mts +1 -1
  78. package/api/theme/theme.mjs +1 -1
  79. package/api/theme/theme.type.d.mts +9 -0
  80. package/api/theme/theme.type.mjs +3 -1
  81. package/api/theme/themeAdd.doc.d.mts +1 -4
  82. package/api/theme/themeAdd.doc.mjs +31 -31
  83. package/api/theme/themeBuild.doc.mjs +1 -1
  84. package/api/theme/themeList.doc.d.mts +1 -4
  85. package/api/theme/themeList.doc.mjs +7 -15
  86. package/api/theme/themeListAvailable.doc.d.mts +8 -0
  87. package/api/theme/themeListAvailable.doc.mjs +57 -0
  88. package/api/theme/themeTargets.doc.mjs +21 -7
  89. package/api/upgrade/_adapter.d.mts +2 -0
  90. package/api/upgrade/_adapter.mjs +1 -0
  91. package/api/upgrade/registry/registry.d.mts +40 -0
  92. package/api/upgrade/registry/registry.mjs +1154 -0
  93. package/api/upgrade/registry/registry.test.mjs +826 -0
  94. package/api/upgrade/run/run.mjs +49 -8
  95. package/api/upgrade/status/status.d.mts +6 -4
  96. package/api/upgrade/status/status.mjs +26 -8
  97. package/api/upgrade/upgrade.d.mts +2 -2
  98. package/api/upgrade/upgrade.doc.mjs +33 -9
  99. package/api/upgrade/upgrade.mjs +34 -7
  100. package/api/upgrade/upgrade.test.mjs +198 -8
  101. package/api/upgrade/upgrade.type.d.mts +90 -1
  102. package/api/upgrade/upgrade.type.mjs +51 -2
  103. package/assets/docs/cli-integrations.doc.mjs +152 -28
  104. package/assets/docs/getting-started.doc.mjs +1 -1
  105. package/assets/docs/{shadcn-compatibility.doc.mjs → shadcn-compatibility.doc.draft.mjs} +23 -13
  106. package/assets/docs/styling.doc.mjs +3 -3
  107. package/assets/docs/theme.doc.dense.mjs +2 -2
  108. package/assets/docs/theme.doc.mjs +23 -13
  109. package/assets/docs/theme.doc.zh.mjs +1 -1
  110. package/assets/templates/blocks/components/BaseTypeahead/BaseTypeaheadCustomSearch.doc.mjs +2 -1
  111. package/assets/templates/blocks/components/BaseTypeahead/BaseTypeaheadCustomSearch.tsx +38 -12
  112. package/assets/templates/blocks/components/BaseTypeahead/BaseTypeaheadShowcase.doc.mjs +15 -0
  113. package/assets/templates/blocks/components/BaseTypeahead/BaseTypeaheadShowcase.tsx +87 -0
  114. package/assets/templates/blocks/components/BottomSheet/BottomSheetSwitcherReviewFlow.doc.mjs +23 -0
  115. package/assets/templates/blocks/components/BottomSheet/BottomSheetSwitcherReviewFlow.tsx +75 -0
  116. package/assets/templates/blocks/components/BreadcrumbItem/BreadcrumbItemShowcase.tsx +5 -19
  117. package/assets/templates/blocks/components/Center/CenterHorizontal.doc.mjs +3 -2
  118. package/assets/templates/blocks/components/Center/CenterHorizontal.tsx +4 -5
  119. package/assets/templates/blocks/components/Toast/ToastAction.tsx +2 -1
  120. package/assets/templates/blocks/components/Toast/ToastDeduplication.tsx +2 -1
  121. package/assets/templates/blocks/components/Toast/ToastDismiss.tsx +2 -1
  122. package/assets/templates/blocks/components/Toast/ToastShowcase.tsx +2 -1
  123. package/assets/templates/blocks/components/Toast/ToastStacking.tsx +2 -1
  124. package/assets/templates/blocks/components/Toast/ToastTypes.tsx +2 -1
  125. package/assets/templates/pages/dashboard/template.doc.mjs +2 -2
  126. package/assets/templates/pages/dashboard-alert-rail/template.doc.mjs +3 -2
  127. package/assets/templates/pages/dashboard-cohort-funnel/template.doc.mjs +3 -2
  128. package/assets/templates/pages/dashboard-comparison/template.doc.mjs +3 -3
  129. package/assets/templates/pages/dashboard-composition/template.doc.mjs +2 -2
  130. package/assets/templates/pages/dashboard-progress/template.doc.mjs +2 -2
  131. package/assets/templates/pages/dashboard-scorecard/template.doc.mjs +2 -2
  132. package/assets/templates/themes/butter/butterTheme.ts +3 -3
  133. package/assets/templates/themes/neutral/neutralTheme.ts +2 -2
  134. package/assets/templates/themes/stone/stoneTheme.ts +3 -3
  135. package/assets/theme.template.ts +4 -7
  136. package/authoring/config/config.doc.mjs +9 -1
  137. package/authoring/config/parse.d.mts +2 -0
  138. package/authoring/config/parse.mjs +28 -3
  139. package/authoring/config/parse.test.mjs +25 -3
  140. package/authoring/config/type.ts +3 -0
  141. package/authoring/doctypes/_schema.d.mts +3 -0
  142. package/authoring/doctypes/_schema.mjs +6 -1
  143. package/authoring/doctypes/base/type.ts +6 -6
  144. package/authoring/doctypes/component/component.doc.mjs +6 -0
  145. package/authoring/doctypes/component/type.ts +2 -0
  146. package/authoring/gap-report/parse.d.mts +63 -0
  147. package/authoring/gap-report/parse.mjs +121 -0
  148. package/authoring/gap-report/parse.test.mjs +172 -0
  149. package/authoring/gap-report/type.ts +107 -0
  150. package/authoring/index.d.mts +1 -0
  151. package/authoring/index.d.ts +12 -0
  152. package/authoring/index.mjs +4 -0
  153. package/authoring/integration/integration.doc.mjs +14 -2
  154. package/authoring/integration/parse.test.mjs +9 -4
  155. package/authoring/integration/schema.d.mts +2 -0
  156. package/authoring/integration/schema.mjs +1 -0
  157. package/authoring/integration/type.ts +23 -6
  158. package/authoring/shadcn/receipt.d.mts +219 -0
  159. package/authoring/shadcn/receipt.mjs +248 -0
  160. package/authoring/shadcn/receipt.test.mjs +187 -0
  161. package/authoring/shadcn/source-variants.d.mts +28 -0
  162. package/authoring/shadcn/source-variants.mjs +176 -0
  163. package/authoring/shadcn/source-variants.test.mjs +120 -0
  164. package/clients/cli/commands/build-theme.mjs +54 -19
  165. package/clients/cli/commands/build-theme.variants.test.mjs +15 -12
  166. package/clients/cli/commands/component/index.mjs +1 -1
  167. package/clients/cli/commands/docs.test.mjs +1 -0
  168. package/clients/cli/commands/doctor-integration.doc.mjs +1 -1
  169. package/clients/cli/commands/gap-report.doc.mjs +73 -0
  170. package/clients/cli/commands/gap-report.mjs +114 -0
  171. package/clients/cli/commands/gap-report.test.mjs +198 -0
  172. package/clients/cli/commands/import-hint-correctness.test.mjs +88 -0
  173. package/clients/cli/commands/integration-add.doc.mjs +88 -0
  174. package/clients/cli/commands/integration-authoring.test.mjs +177 -0
  175. package/clients/cli/commands/integration-pack.doc.mjs +34 -0
  176. package/clients/cli/commands/integration-real-world.test.mjs +618 -0
  177. package/clients/cli/commands/integration.doc.mjs +28 -0
  178. package/clients/cli/commands/integration.mjs +153 -0
  179. package/clients/cli/commands/theme-add.doc.mjs +11 -6
  180. package/clients/cli/commands/theme-list.doc.mjs +21 -5
  181. package/clients/cli/commands/theme-targets.behavior.test.mjs +19 -2
  182. package/clients/cli/commands/theme.doc.mjs +2 -2
  183. package/clients/cli/commands/upgrade.doc.mjs +17 -4
  184. package/clients/cli/commands/upgrade.mjs +12 -1
  185. package/clients/cli/commands/upgrade.test.mjs +41 -0
  186. package/clients/cli/index.mjs +5 -0
  187. package/clients/cli/lib/component-format.mjs +42 -26
  188. package/clients/cli/lib/component-format.test.mjs +34 -3
  189. package/clients/cli/lib/manifest.mjs +12 -0
  190. package/foundation/config/project-themes.test.mjs +127 -0
  191. package/foundation/config/project.d.mts +23 -4
  192. package/foundation/config/project.mjs +96 -9
  193. package/foundation/config/project.test.mjs +132 -6
  194. package/foundation/discovery/component-discovery.d.mts +36 -0
  195. package/foundation/discovery/component-discovery.mjs +96 -0
  196. package/foundation/discovery/theme-discovery.d.mts +39 -0
  197. package/foundation/discovery/theme-discovery.mjs +650 -0
  198. package/foundation/discovery/theme-discovery.test.mjs +375 -0
  199. package/foundation/discovery/theming-targets.d.mts +16 -0
  200. package/foundation/discovery/theming-targets.mjs +39 -3
  201. package/foundation/discovery/theming-targets.test.mjs +139 -0
  202. package/foundation/integrations/autolink.d.mts +96 -0
  203. package/foundation/integrations/autolink.mjs +265 -0
  204. package/foundation/integrations/autolink.test.mjs +430 -0
  205. package/foundation/integrations/contribution-inventory.d.mts +152 -0
  206. package/foundation/integrations/contribution-inventory.mjs +497 -0
  207. package/foundation/integrations/contribution-inventory.test.mjs +361 -0
  208. package/foundation/integrations/integrations.d.mts +73 -9
  209. package/foundation/integrations/integrations.mjs +158 -8
  210. package/foundation/integrations/integrations.test.mjs +152 -29
  211. package/foundation/integrations/manifest-writer.d.mts +56 -0
  212. package/foundation/integrations/manifest-writer.mjs +328 -0
  213. package/foundation/integrations/manifest-writer.test.mjs +229 -0
  214. package/foundation/integrations/validate-contributions.mjs +81 -6
  215. package/foundation/response/error-codes.d.mts +4 -1
  216. package/foundation/response/error-codes.doc.mjs +16 -1
  217. package/foundation/response/error-codes.mjs +10 -1
  218. package/foundation/response/response-types.doc.mjs +23 -2
  219. package/package.json +8 -1
@@ -0,0 +1,1154 @@
1
+ // Copyright (c) Meta Platforms, Inc. and affiliates.
2
+
3
+ /**
4
+ * @file Safe reconciliation for source copied from the Astryx ShadCN registry.
5
+ * @input Adjacent install receipts, current project files, and current registry JSON.
6
+ * @output Dry-run/apply summaries, clean merges, and separate conflict artifacts.
7
+ * @position ShadCN composition lane inside the `upgrade` API.
8
+ */
9
+
10
+ import * as fs from 'node:fs';
11
+ import * as path from 'node:path';
12
+ import {randomUUID} from 'node:crypto';
13
+ import {mergeDiff3} from 'node-diff3';
14
+ import {
15
+ createShadcnPrecompiledDeclaration,
16
+ shadcnJavaScriptTarget,
17
+ shadcnPrecompiledDeclarationTarget,
18
+ shadcnJavaScriptSourcesEquivalent,
19
+ transformShadcnJavaScriptSource,
20
+ } from '../../../authoring/shadcn/source-variants.mjs';
21
+ import {
22
+ PUBLIC_SHADCN_REGISTRY_ORIGIN,
23
+ parseRegistryReceipt,
24
+ parseRegistryUpgradeItem,
25
+ registryContentHash,
26
+ registryReceiptTarget,
27
+ serializeRegistryReceipt,
28
+ } from '../../../authoring/shadcn/receipt.mjs';
29
+ import {
30
+ assertWithin,
31
+ PathSafetyError,
32
+ } from '../../../foundation/fs/path-safety.mjs';
33
+ import {ERROR_CODES} from '../../../foundation/response/error-codes.mjs';
34
+ import {AstryxError} from '../../error.mjs';
35
+ import {logger} from '../../logger.mjs';
36
+ import {detectInstalledTargetVersion} from '../_adapter.mjs';
37
+
38
+ const SKIP_DIRS = new Set([
39
+ '.cache',
40
+ '.git',
41
+ '.next',
42
+ '.pnpm',
43
+ '.turbo',
44
+ 'build',
45
+ 'coverage',
46
+ 'dist',
47
+ 'node_modules',
48
+ 'out',
49
+ ]);
50
+ const MAX_ITEM_BYTES = 16 * 1024 * 1024;
51
+ const FETCH_CONCURRENCY = 8;
52
+
53
+ /** @param {string} filePath @param {string} root */
54
+ function relativePath(filePath, root) {
55
+ return path.relative(root, filePath).split(path.sep).join('/');
56
+ }
57
+
58
+ /** @param {string} root */
59
+ export function discoverRegistryReceipts(root) {
60
+ /** @type {string[]} */
61
+ const receipts = [];
62
+ if (!fs.existsSync(root)) return receipts;
63
+
64
+ /** @param {string} dir */
65
+ function walk(dir) {
66
+ for (const entry of fs.readdirSync(dir, {withFileTypes: true})) {
67
+ if (SKIP_DIRS.has(entry.name)) continue;
68
+ const fullPath = path.join(dir, entry.name);
69
+ if (!entry.isDirectory()) continue;
70
+ if (entry.name === '.astryx') {
71
+ for (const receipt of fs.readdirSync(fullPath, {withFileTypes: true})) {
72
+ if (receipt.isFile() && receipt.name.endsWith('.json')) {
73
+ receipts.push(path.join(fullPath, receipt.name));
74
+ }
75
+ }
76
+ continue;
77
+ }
78
+ walk(fullPath);
79
+ }
80
+ }
81
+
82
+ walk(root);
83
+ return receipts.sort();
84
+ }
85
+
86
+ /** @param {string} filePath @param {string} content */
87
+ function atomicWrite(filePath, content) {
88
+ const temporary = `${filePath}.astryx-tmp-${randomUUID()}`;
89
+ const existing = fs.existsSync(filePath) ? fs.lstatSync(filePath) : null;
90
+ const mode = existing && !existing.isSymbolicLink() ? existing.mode : null;
91
+ try {
92
+ fs.writeFileSync(temporary, content, 'utf8');
93
+ if (mode != null) fs.chmodSync(temporary, mode);
94
+ fs.renameSync(temporary, filePath);
95
+ } finally {
96
+ fs.rmSync(temporary, {force: true});
97
+ }
98
+ }
99
+
100
+ /** @param {string} source */
101
+ function lines(source) {
102
+ return source.split('\n');
103
+ }
104
+
105
+ /** @param {string} source */
106
+ function normalizeLineEndings(source) {
107
+ return source.replace(/\r\n/g, '\n');
108
+ }
109
+
110
+ /** @param {string} source */
111
+ function preferredLineEnding(source) {
112
+ return source.includes('\r\n') ? '\r\n' : '\n';
113
+ }
114
+
115
+ /** @param {string} source @param {string} lineEnding */
116
+ function applyLineEnding(source, lineEnding) {
117
+ const normalized = normalizeLineEndings(source);
118
+ return lineEnding === '\n'
119
+ ? normalized
120
+ : normalized.replace(/\n/g, lineEnding);
121
+ }
122
+
123
+ /**
124
+ * @template T, U
125
+ * @param {T[]} values
126
+ * @param {number} limit
127
+ * @param {(value: T, index: number) => Promise<U>} mapper
128
+ * @returns {Promise<U[]>}
129
+ */
130
+ async function mapWithConcurrency(values, limit, mapper) {
131
+ /** @type {U[]} */
132
+ const results = new Array(values.length);
133
+ let nextIndex = 0;
134
+ async function worker() {
135
+ while (nextIndex < values.length) {
136
+ const index = nextIndex++;
137
+ results[index] = await mapper(values[index], index);
138
+ }
139
+ }
140
+ await Promise.all(
141
+ Array.from({length: Math.min(limit, values.length)}, () => worker()),
142
+ );
143
+ return results;
144
+ }
145
+
146
+ /** @param {Response} response @param {string} url */
147
+ async function readRegistryItemBody(response, url) {
148
+ const declaredLength = Number(response.headers.get('content-length'));
149
+ if (Number.isFinite(declaredLength) && declaredLength > MAX_ITEM_BYTES) {
150
+ throw new Error(`Registry item ${url} exceeds ${MAX_ITEM_BYTES} bytes`);
151
+ }
152
+ if (!response.body) {
153
+ const text = await response.text();
154
+ if (Buffer.byteLength(text, 'utf8') > MAX_ITEM_BYTES) {
155
+ throw new Error(`Registry item ${url} exceeds ${MAX_ITEM_BYTES} bytes`);
156
+ }
157
+ return text;
158
+ }
159
+
160
+ const reader = response.body.getReader();
161
+ const chunks = [];
162
+ let total = 0;
163
+ while (true) {
164
+ const {done, value} = await reader.read();
165
+ if (done) break;
166
+ total += value.byteLength;
167
+ if (total > MAX_ITEM_BYTES) {
168
+ await reader.cancel();
169
+ throw new Error(`Registry item ${url} exceeds ${MAX_ITEM_BYTES} bytes`);
170
+ }
171
+ chunks.push(Buffer.from(value));
172
+ }
173
+ return Buffer.concat(chunks, total).toString('utf8');
174
+ }
175
+
176
+ /**
177
+ * @param {string} current
178
+ * @param {string} installed
179
+ * @param {string} latest
180
+ * @param {{current: string, installed: string, latest: string}} labels
181
+ */
182
+ function threeWayMerge(current, installed, latest, labels) {
183
+ const result = mergeDiff3(lines(current), lines(installed), lines(latest), {
184
+ excludeFalseConflicts: true,
185
+ label: {
186
+ a: labels.current,
187
+ o: labels.installed,
188
+ b: labels.latest,
189
+ },
190
+ });
191
+ return {conflict: result.conflict, content: result.result.join('\n')};
192
+ }
193
+
194
+ /** @param {string} itemPath @param {string} registryOrigin */
195
+ function registryItemUrl(itemPath, registryOrigin) {
196
+ return new URL(
197
+ `${itemPath}.json`,
198
+ `${registryOrigin.replace(/\/$/, '')}/`,
199
+ ).toString();
200
+ }
201
+
202
+ /** @param {string} sourceVersion @param {string} expectedVersion */
203
+ function sourceVersionMatches(sourceVersion, expectedVersion) {
204
+ if (sourceVersion === expectedVersion) return true;
205
+ return (
206
+ sourceVersion === 'canary' &&
207
+ /(^|[.-])canary([.-]|$)/i.test(expectedVersion)
208
+ );
209
+ }
210
+
211
+ /**
212
+ * Flatten the canonical receipt file and each format-specific install variant.
213
+ * Version 1 receipts did not carry variants; derive the stock-ShadCN JavaScript
214
+ * form so early canary installs can repair themselves on their first upgrade.
215
+ * @param {ReturnType<typeof parseRegistryReceipt>} receipt
216
+ * @param {any} file
217
+ */
218
+ function receiptFileCandidates(receipt, file) {
219
+ const canonical = {...file, format: 'typescript'};
220
+ /** @type {Array<{format: 'javascript', target: string, registryTarget: string, sha256: string, content: string}>} */
221
+ let variants = receipt.schemaVersion === 2 ? file.variants : [];
222
+ if (receipt.schemaVersion === 1) {
223
+ const target = shadcnJavaScriptTarget(file.target);
224
+ const registryTarget = shadcnJavaScriptTarget(file.registryTarget);
225
+ if (target !== file.target || registryTarget !== file.registryTarget) {
226
+ try {
227
+ const content = transformShadcnJavaScriptSource(file.content);
228
+ variants = [
229
+ {
230
+ format: 'javascript',
231
+ target,
232
+ registryTarget,
233
+ sha256: registryContentHash(content),
234
+ content,
235
+ },
236
+ ];
237
+ } catch {
238
+ // A version 1 receipt may describe a non-code file. Its canonical form
239
+ // remains valid; it simply has no derivable JavaScript variant.
240
+ }
241
+ }
242
+ }
243
+ return [
244
+ canonical,
245
+ ...variants.map(variant => ({
246
+ ...variant,
247
+ id: file.id,
248
+ registryPath: file.registryPath,
249
+ })),
250
+ ];
251
+ }
252
+
253
+ /** @param {ReturnType<typeof parseRegistryReceipt>} receipt @param {any} file @param {string} format */
254
+ function receiptFileForFormat(receipt, file, format) {
255
+ return receiptFileCandidates(receipt, file).find(
256
+ candidate => candidate.format === format,
257
+ );
258
+ }
259
+
260
+ /**
261
+ * @param {string} itemPath
262
+ * @param {{fetchImpl: typeof fetch, registryOrigin: string, expectedVersion?: string}} options
263
+ */
264
+ async function fetchLatestReceipt(
265
+ itemPath,
266
+ {fetchImpl, registryOrigin, expectedVersion},
267
+ ) {
268
+ const url = registryItemUrl(itemPath, registryOrigin);
269
+ let response;
270
+ try {
271
+ response = await fetchImpl(url, {
272
+ headers: {accept: 'application/json'},
273
+ redirect: 'error',
274
+ signal: globalThis.AbortSignal.timeout(15_000),
275
+ });
276
+ } catch (error) {
277
+ throw new Error(
278
+ `Could not fetch ${url}: ${error instanceof Error ? error.message : String(error)}`,
279
+ {cause: error},
280
+ );
281
+ }
282
+ if (!response.ok) {
283
+ throw new Error(`Could not fetch ${url}: HTTP ${response.status}`);
284
+ }
285
+ const text = await readRegistryItemBody(response, url);
286
+
287
+ let parsed;
288
+ try {
289
+ parsed = parseRegistryUpgradeItem(JSON.parse(text));
290
+ } catch (error) {
291
+ throw new Error(
292
+ `Registry item ${url} is invalid: ${error instanceof Error ? error.message : String(error)}`,
293
+ {cause: error},
294
+ );
295
+ }
296
+
297
+ const receiptCandidates = [];
298
+ for (const file of parsed.files) {
299
+ if (file.type !== 'registry:file' || !file.path.endsWith('.json')) continue;
300
+ try {
301
+ receiptCandidates.push({
302
+ receipt: parseRegistryReceipt(JSON.parse(file.content)),
303
+ carrier: file,
304
+ });
305
+ } catch {
306
+ // Other JSON files are allowed; only a valid Astryx receipt counts.
307
+ }
308
+ }
309
+ if (receiptCandidates.length !== 1) {
310
+ throw new Error(
311
+ `Registry item ${url} must contain exactly one Astryx receipt; found ${receiptCandidates.length}`,
312
+ );
313
+ }
314
+ const {receipt, carrier} = receiptCandidates[0];
315
+ if (
316
+ expectedVersion &&
317
+ !sourceVersionMatches(receipt.source.version, expectedVersion)
318
+ ) {
319
+ throw new Error(
320
+ `Registry item ${url} targets Astryx ${receipt.source.version}, but the project has ${expectedVersion}. Update Astryx packages first or retry after the registry catches up.`,
321
+ );
322
+ }
323
+ const expectedItemType =
324
+ receipt.item.kind === 'page' ? 'registry:page' : 'registry:block';
325
+ if (parsed.name !== receipt.item.name || parsed.type !== expectedItemType) {
326
+ throw new Error(`Registry item ${url} identity does not match its receipt`);
327
+ }
328
+ const expectedReceiptTarget = registryReceiptTarget(
329
+ receipt.files[0].registryTarget,
330
+ receipt.item.name,
331
+ );
332
+ if (
333
+ carrier.path !== `registry/${receipt.item.name}/astryx-receipt.json` ||
334
+ carrier.target !== expectedReceiptTarget
335
+ ) {
336
+ throw new Error(`Registry item ${url} has a misplaced Astryx receipt`);
337
+ }
338
+ if (
339
+ receipt.item.path !== itemPath &&
340
+ !receipt.item.aliases.includes(itemPath)
341
+ ) {
342
+ throw new Error(
343
+ `Registry item ${url} no longer recognizes installed path ${itemPath}`,
344
+ );
345
+ }
346
+
347
+ const primaryFile = receipt.files.find(file => file.id === 'primary');
348
+ const typesFile = receipt.files.find(file => file.id === 'types');
349
+ const typesVariants =
350
+ receipt.schemaVersion === 2
351
+ ? receipt.files.find(file => file.id === 'types')?.variants
352
+ : undefined;
353
+ if (typesFile) {
354
+ let expectedTypesTarget;
355
+ let expectedTypesContent;
356
+ try {
357
+ expectedTypesTarget = shadcnPrecompiledDeclarationTarget(
358
+ primaryFile?.registryTarget ?? '',
359
+ );
360
+ expectedTypesContent = createShadcnPrecompiledDeclaration(
361
+ primaryFile?.registryTarget ?? '',
362
+ );
363
+ } catch {
364
+ expectedTypesTarget = null;
365
+ expectedTypesContent = null;
366
+ }
367
+ if (
368
+ primaryFile == null ||
369
+ typesFile.registryTarget !== expectedTypesTarget ||
370
+ typesFile.content !== expectedTypesContent ||
371
+ typesVariants?.length !== 0
372
+ ) {
373
+ throw new Error(
374
+ `Registry item ${url} has an invalid TypeScript declaration`,
375
+ );
376
+ }
377
+ }
378
+
379
+ for (const file of receipt.files) {
380
+ const source = parsed.files.find(
381
+ candidate => candidate.path === file.registryPath,
382
+ );
383
+ if (
384
+ !source ||
385
+ source.target !== file.registryTarget ||
386
+ source.content !== file.content
387
+ ) {
388
+ throw new Error(
389
+ `Registry item ${url} receipt does not match ${file.registryPath}`,
390
+ );
391
+ }
392
+ if (registryContentHash(file.content) !== file.sha256) {
393
+ throw new Error(
394
+ `Registry item ${url} receipt has a corrupt hash for ${file.registryPath}`,
395
+ );
396
+ }
397
+ for (const variant of receiptFileCandidates(receipt, file).slice(1)) {
398
+ if (
399
+ variant.target !== shadcnJavaScriptTarget(file.target) ||
400
+ variant.registryTarget !==
401
+ shadcnJavaScriptTarget(file.registryTarget) ||
402
+ variant.content !== transformShadcnJavaScriptSource(file.content) ||
403
+ registryContentHash(variant.content) !== variant.sha256
404
+ ) {
405
+ throw new Error(
406
+ `Registry item ${url} has an invalid ${variant.format} variant for ${file.registryPath}`,
407
+ );
408
+ }
409
+ }
410
+ }
411
+ return receipt;
412
+ }
413
+
414
+ /**
415
+ * @param {string} receiptPath
416
+ * @param {string} root
417
+ */
418
+ function loadInstalledReceipt(receiptPath, root) {
419
+ let receipt;
420
+ let receiptText;
421
+ try {
422
+ const receiptStat = fs.lstatSync(receiptPath);
423
+ if (receiptStat.isSymbolicLink()) {
424
+ throw new Error('receipt is a symbolic link');
425
+ }
426
+ if (receiptStat.size > MAX_ITEM_BYTES) {
427
+ throw new Error(`receipt exceeds ${MAX_ITEM_BYTES} bytes`);
428
+ }
429
+ receiptText = fs.readFileSync(receiptPath, 'utf8');
430
+ receipt = parseRegistryReceipt(JSON.parse(receiptText));
431
+ if (
432
+ path.basename(path.dirname(receiptPath)) !== '.astryx' ||
433
+ path.basename(receiptPath) !== `${receipt.item.name}.json`
434
+ ) {
435
+ throw new Error('receipt filename does not match its item identity');
436
+ }
437
+ } catch (error) {
438
+ throw new Error(
439
+ `Invalid receipt ${relativePath(receiptPath, root)}: ${error instanceof Error ? error.message : String(error)}`,
440
+ {cause: error},
441
+ );
442
+ }
443
+
444
+ const files = receipt.files.map(file => {
445
+ const candidates = receiptFileCandidates(receipt, file).map(candidate => {
446
+ if (registryContentHash(candidate.content) !== candidate.sha256) {
447
+ throw new Error(
448
+ `Invalid receipt ${relativePath(receiptPath, root)}: stored hash does not match ${file.registryPath} (${candidate.format})`,
449
+ );
450
+ }
451
+ let sourcePath;
452
+ try {
453
+ sourcePath = assertWithin(
454
+ path.resolve(path.dirname(receiptPath), candidate.target),
455
+ root,
456
+ {allowAbsolute: true, label: 'registry composition source'},
457
+ );
458
+ } catch (error) {
459
+ if (error instanceof PathSafetyError) {
460
+ throw new Error(
461
+ `Invalid receipt ${relativePath(receiptPath, root)}: ${error.message}`,
462
+ {cause: error},
463
+ );
464
+ }
465
+ throw error;
466
+ }
467
+ return {...candidate, sourcePath};
468
+ });
469
+ const existing = candidates.filter(candidate =>
470
+ fs.existsSync(candidate.sourcePath),
471
+ );
472
+ if (existing.length > 1) {
473
+ throw new Error(
474
+ `Invalid receipt ${relativePath(receiptPath, root)}: multiple install variants exist for ${file.registryPath}`,
475
+ );
476
+ }
477
+ return existing[0] ?? candidates[0];
478
+ });
479
+
480
+ return {receipt, files, receiptText};
481
+ }
482
+
483
+ /**
484
+ * @param {string} receiptPath
485
+ * @param {string} root
486
+ * @param {{fetchImpl: typeof fetch, registryOrigin: string, expectedVersion?: string}} options
487
+ */
488
+ async function planReceipt(receiptPath, root, options) {
489
+ let installed;
490
+ try {
491
+ installed = loadInstalledReceipt(receiptPath, root);
492
+ } catch (error) {
493
+ return {
494
+ receiptPath,
495
+ item: path.basename(receiptPath, '.json'),
496
+ action: 'invalid',
497
+ message: error instanceof Error ? error.message : String(error),
498
+ files: [],
499
+ };
500
+ }
501
+
502
+ const {
503
+ receipt: oldReceipt,
504
+ files: oldFiles,
505
+ receiptText: oldReceiptText,
506
+ } = installed;
507
+ let newReceipt;
508
+ try {
509
+ newReceipt = await fetchLatestReceipt(oldReceipt.item.path, options);
510
+ } catch (error) {
511
+ return {
512
+ receiptPath,
513
+ item: oldReceipt.item.name,
514
+ itemPath: oldReceipt.item.path,
515
+ action: 'fetch-error',
516
+ message: error instanceof Error ? error.message : String(error),
517
+ files: [],
518
+ };
519
+ }
520
+
521
+ if (
522
+ newReceipt.item.name !== oldReceipt.item.name ||
523
+ newReceipt.item.kind !== oldReceipt.item.kind
524
+ ) {
525
+ return {
526
+ receiptPath,
527
+ item: oldReceipt.item.name,
528
+ itemPath: oldReceipt.item.path,
529
+ action: 'conflict',
530
+ message: 'Latest item changed its stable name or kind',
531
+ files: [],
532
+ oldReceiptText,
533
+ };
534
+ }
535
+ const oldIds = oldReceipt.files.map(file => file.id).sort();
536
+ const newIds = newReceipt.files.map(file => file.id).sort();
537
+ const removedIds = oldIds.filter(id => !newIds.includes(id));
538
+ const addedIds = newIds.filter(id => !oldIds.includes(id));
539
+ const addsOnlyGeneratedTypes =
540
+ removedIds.length === 0 &&
541
+ addedIds.length === 1 &&
542
+ addedIds[0] === 'types' &&
543
+ oldReceipt.files.some(
544
+ file => file.id === 'primary' && /\.jsx?$/.test(file.registryTarget),
545
+ );
546
+ if (
547
+ JSON.stringify(oldIds) !== JSON.stringify(newIds) &&
548
+ !addsOnlyGeneratedTypes
549
+ ) {
550
+ return {
551
+ receiptPath,
552
+ item: oldReceipt.item.name,
553
+ itemPath: oldReceipt.item.path,
554
+ action: 'conflict',
555
+ message:
556
+ 'Latest item changed its copied source set; no files were written',
557
+ files: [],
558
+ oldReceiptText,
559
+ };
560
+ }
561
+
562
+ const plannedFiles = [];
563
+ if (addsOnlyGeneratedTypes) {
564
+ const newReceiptFile = newReceipt.files.find(file => file.id === 'types');
565
+ const newFile = newReceiptFile
566
+ ? receiptFileCandidates(newReceipt, newReceiptFile)[0]
567
+ : null;
568
+ if (newFile) {
569
+ let sourcePath;
570
+ try {
571
+ sourcePath = assertWithin(
572
+ path.resolve(path.dirname(receiptPath), newFile.target),
573
+ root,
574
+ {allowAbsolute: true, label: 'registry composition declaration'},
575
+ );
576
+ } catch (error) {
577
+ return {
578
+ receiptPath,
579
+ item: oldReceipt.item.name,
580
+ itemPath: oldReceipt.item.path,
581
+ action: 'invalid',
582
+ message: error instanceof Error ? error.message : String(error),
583
+ files: [],
584
+ oldReceiptText,
585
+ };
586
+ }
587
+ const displayPath = relativePath(sourcePath, root);
588
+ try {
589
+ if (!fs.existsSync(sourcePath)) {
590
+ plannedFiles.push({
591
+ id: newFile.id,
592
+ path: displayPath,
593
+ sourcePath,
594
+ action: 'create',
595
+ content: newFile.content,
596
+ });
597
+ } else if (fs.lstatSync(sourcePath).isSymbolicLink()) {
598
+ plannedFiles.push({
599
+ id: newFile.id,
600
+ path: displayPath,
601
+ sourcePath,
602
+ action: 'invalid',
603
+ message:
604
+ 'Generated declaration is a symbolic link; it will not be replaced',
605
+ });
606
+ } else {
607
+ const current = fs.readFileSync(sourcePath, 'utf8');
608
+ const currentHash = registryContentHash(current);
609
+ plannedFiles.push({
610
+ id: newFile.id,
611
+ path: displayPath,
612
+ sourcePath,
613
+ currentContent: current,
614
+ action: currentHash === newFile.sha256 ? 'current' : 'conflict',
615
+ message:
616
+ currentHash === newFile.sha256
617
+ ? undefined
618
+ : 'Generated declaration already exists with different content',
619
+ });
620
+ }
621
+ } catch (error) {
622
+ plannedFiles.push({
623
+ id: newFile.id,
624
+ path: displayPath,
625
+ sourcePath,
626
+ action: 'invalid',
627
+ message: error instanceof Error ? error.message : String(error),
628
+ });
629
+ }
630
+ }
631
+ }
632
+ for (const oldFile of oldFiles) {
633
+ const newReceiptFile = newReceipt.files.find(
634
+ file => file.id === oldFile.id,
635
+ );
636
+ const newFile = newReceiptFile
637
+ ? receiptFileForFormat(newReceipt, newReceiptFile, oldFile.format)
638
+ : null;
639
+ const displayPath = relativePath(oldFile.sourcePath, root);
640
+ if (!newReceiptFile) {
641
+ plannedFiles.push({
642
+ id: oldFile.id,
643
+ path: displayPath,
644
+ action: 'target-changed',
645
+ message: `Latest item removed source id ${oldFile.id}`,
646
+ });
647
+ continue;
648
+ }
649
+ if (!newFile) {
650
+ plannedFiles.push({
651
+ id: oldFile.id,
652
+ path: displayPath,
653
+ action: 'target-changed',
654
+ message: `Latest item removed the ${oldFile.format} install variant`,
655
+ });
656
+ continue;
657
+ }
658
+ if (
659
+ newFile.target !== oldFile.target ||
660
+ newFile.registryTarget !== oldFile.registryTarget ||
661
+ newFile.registryPath !== oldFile.registryPath
662
+ ) {
663
+ plannedFiles.push({
664
+ id: oldFile.id,
665
+ path: displayPath,
666
+ action: 'target-changed',
667
+ message: 'Latest item changed the copied source target',
668
+ });
669
+ continue;
670
+ }
671
+ if (!fs.existsSync(oldFile.sourcePath)) {
672
+ plannedFiles.push({
673
+ id: oldFile.id,
674
+ path: displayPath,
675
+ action: 'missing',
676
+ message: 'Copied source was deleted or moved; it will not be recreated',
677
+ });
678
+ continue;
679
+ }
680
+
681
+ let current;
682
+ try {
683
+ if (fs.lstatSync(oldFile.sourcePath).isSymbolicLink()) {
684
+ plannedFiles.push({
685
+ id: oldFile.id,
686
+ path: displayPath,
687
+ action: 'invalid',
688
+ message: 'Copied source is a symbolic link; it will not be replaced',
689
+ });
690
+ continue;
691
+ }
692
+ current = fs.readFileSync(oldFile.sourcePath, 'utf8');
693
+ } catch (error) {
694
+ plannedFiles.push({
695
+ id: oldFile.id,
696
+ path: displayPath,
697
+ action: 'invalid',
698
+ message: error instanceof Error ? error.message : String(error),
699
+ });
700
+ continue;
701
+ }
702
+
703
+ const lineEnding = preferredLineEnding(current);
704
+ const conflictPath = `${oldFile.sourcePath}.astryx-conflict`;
705
+ const currentCanonical = normalizeLineEndings(current);
706
+ const oldCanonical = normalizeLineEndings(oldFile.content);
707
+ const newCanonical = normalizeLineEndings(newFile.content);
708
+ const currentHash = registryContentHash(currentCanonical);
709
+ const oldHash = registryContentHash(oldCanonical);
710
+ const newHash = registryContentHash(newCanonical);
711
+ const currentMatchesOld =
712
+ currentHash === oldHash ||
713
+ (/\.jsx?$/.test(oldFile.target) &&
714
+ shadcnJavaScriptSourcesEquivalent(currentCanonical, oldCanonical));
715
+ if (oldHash === newHash) {
716
+ plannedFiles.push({
717
+ id: oldFile.id,
718
+ path: displayPath,
719
+ sourcePath: oldFile.sourcePath,
720
+ currentContent: current,
721
+ conflictPath,
722
+ action: currentMatchesOld ? 'current' : 'user-modified',
723
+ });
724
+ continue;
725
+ }
726
+ if (currentMatchesOld) {
727
+ plannedFiles.push({
728
+ id: oldFile.id,
729
+ path: displayPath,
730
+ sourcePath: oldFile.sourcePath,
731
+ currentContent: current,
732
+ conflictPath,
733
+ action: 'update',
734
+ content: applyLineEnding(newCanonical, lineEnding),
735
+ });
736
+ continue;
737
+ }
738
+ if (currentHash === newHash) {
739
+ plannedFiles.push({
740
+ id: oldFile.id,
741
+ path: displayPath,
742
+ sourcePath: oldFile.sourcePath,
743
+ currentContent: current,
744
+ conflictPath,
745
+ action: 'receipt-only',
746
+ });
747
+ continue;
748
+ }
749
+
750
+ const merged = threeWayMerge(currentCanonical, oldCanonical, newCanonical, {
751
+ current: 'current project',
752
+ installed: `installed ${oldReceipt.source.version}`,
753
+ latest: `latest ${newReceipt.source.version}`,
754
+ });
755
+ plannedFiles.push({
756
+ id: oldFile.id,
757
+ path: displayPath,
758
+ sourcePath: oldFile.sourcePath,
759
+ currentContent: current,
760
+ action: merged.conflict ? 'conflict' : 'merge',
761
+ content: applyLineEnding(merged.content, lineEnding),
762
+ conflictPath,
763
+ });
764
+ }
765
+
766
+ let action = 'current';
767
+ if (
768
+ plannedFiles.some(file =>
769
+ ['conflict', 'missing', 'invalid', 'target-changed'].includes(
770
+ file.action,
771
+ ),
772
+ )
773
+ ) {
774
+ action = 'conflict';
775
+ } else if (plannedFiles.some(file => file.action === 'merge')) {
776
+ action = 'merge';
777
+ } else if (
778
+ plannedFiles.some(file => ['update', 'create'].includes(file.action))
779
+ ) {
780
+ action = 'update';
781
+ } else if (
782
+ plannedFiles.some(file => file.action === 'receipt-only') ||
783
+ serializeRegistryReceipt(oldReceipt) !==
784
+ serializeRegistryReceipt(newReceipt)
785
+ ) {
786
+ action = 'receipt-only';
787
+ }
788
+
789
+ return {
790
+ receiptPath,
791
+ item: oldReceipt.item.name,
792
+ itemPath: oldReceipt.item.path,
793
+ action,
794
+ files: plannedFiles,
795
+ oldReceipt,
796
+ newReceipt,
797
+ oldReceiptText,
798
+ };
799
+ }
800
+
801
+ /**
802
+ * @param {ReturnType<typeof emptySummary>} summary
803
+ * @param {any} item
804
+ * @param {string} plannedAction
805
+ * @param {boolean} apply
806
+ */
807
+ function recordItem(summary, item, plannedAction, apply) {
808
+ summary.items.push(item);
809
+ if (['current', 'user-modified'].includes(plannedAction)) summary.current++;
810
+ else if (plannedAction === 'update') {
811
+ if (apply) summary.updated++;
812
+ else summary.wouldUpdate++;
813
+ } else if (plannedAction === 'merge') {
814
+ if (apply) summary.merged++;
815
+ else summary.wouldMerge++;
816
+ } else if (plannedAction === 'receipt-only') {
817
+ if (apply) summary.receiptsRefreshed++;
818
+ else summary.wouldRefreshReceipt++;
819
+ } else if (plannedAction === 'conflict') summary.conflicts++;
820
+ else if (plannedAction === 'invalid') summary.invalid++;
821
+ else if (plannedAction === 'fetch-error') summary.failed++;
822
+ }
823
+
824
+ /**
825
+ * @param {boolean} apply
826
+ * @returns {import('../upgrade.type.mjs').RegistryCompositionSummary}
827
+ */
828
+ function emptySummary(apply) {
829
+ return {
830
+ applied: apply,
831
+ ok: true,
832
+ found: 0,
833
+ current: 0,
834
+ wouldUpdate: 0,
835
+ updated: 0,
836
+ wouldMerge: 0,
837
+ merged: 0,
838
+ wouldRefreshReceipt: 0,
839
+ receiptsRefreshed: 0,
840
+ conflicts: 0,
841
+ missing: 0,
842
+ invalid: 0,
843
+ failed: 0,
844
+ items: [],
845
+ };
846
+ }
847
+
848
+ /** @param {string} action @param {boolean} apply */
849
+ function publicAction(action, apply) {
850
+ if (action === 'update') return apply ? 'updated' : 'would-update';
851
+ if (action === 'create') return apply ? 'created' : 'would-create';
852
+ if (action === 'merge') return apply ? 'merged' : 'would-merge';
853
+ if (action === 'receipt-only') {
854
+ return apply ? 'receipt-refreshed' : 'would-refresh-receipt';
855
+ }
856
+ return action;
857
+ }
858
+
859
+ /** @param {any} item @param {string} root @param {boolean} apply */
860
+ function publicItem(item, root, apply) {
861
+ return {
862
+ item: item.item,
863
+ path: item.itemPath,
864
+ action: publicAction(item.action, apply),
865
+ ...(item.message ? {message: item.message} : {}),
866
+ files: item.files.map(
867
+ /** @param {any} file */
868
+ file => ({
869
+ path: file.path,
870
+ action: publicAction(file.action, apply),
871
+ ...(file.message ? {message: file.message} : {}),
872
+ ...(file.action === 'conflict' && file.conflictPath
873
+ ? {conflictFile: relativePath(file.conflictPath, root)}
874
+ : {}),
875
+ }),
876
+ ),
877
+ };
878
+ }
879
+
880
+ /** @param {any} plan */
881
+ function applyPlan(plan) {
882
+ if (!['conflict', 'update', 'merge', 'receipt-only'].includes(plan.action)) {
883
+ return;
884
+ }
885
+ if (
886
+ plan.oldReceiptText != null &&
887
+ fs.readFileSync(plan.receiptPath, 'utf8') !== plan.oldReceiptText
888
+ ) {
889
+ throw new Error('Receipt changed while the upgrade was running');
890
+ }
891
+ for (const file of plan.files) {
892
+ if (file.action === 'create' && fs.existsSync(file.sourcePath)) {
893
+ throw new Error(`${file.path} appeared while the upgrade was running`);
894
+ }
895
+ if (
896
+ file.sourcePath &&
897
+ file.currentContent != null &&
898
+ fs.readFileSync(file.sourcePath, 'utf8') !== file.currentContent
899
+ ) {
900
+ throw new Error(`${file.path} changed while the upgrade was running`);
901
+ }
902
+ }
903
+
904
+ if (plan.action === 'conflict') {
905
+ for (const file of plan.files) {
906
+ if (
907
+ file.action === 'conflict' &&
908
+ file.conflictPath &&
909
+ file.content != null
910
+ ) {
911
+ atomicWrite(file.conflictPath, file.content);
912
+ }
913
+ }
914
+ return;
915
+ }
916
+
917
+ const writable = plan.files.filter(
918
+ /** @param {any} file */
919
+ file => ['update', 'merge', 'create'].includes(file.action),
920
+ );
921
+ const originals = writable
922
+ .filter(
923
+ /** @param {any} file */
924
+ file => file.action !== 'create',
925
+ )
926
+ .map(
927
+ /** @param {any} file */
928
+ file => ({
929
+ path: file.sourcePath,
930
+ content: fs.readFileSync(file.sourcePath, 'utf8'),
931
+ }),
932
+ );
933
+ /** @type {string[]} */
934
+ const created = [];
935
+ const oldReceiptText = fs.readFileSync(plan.receiptPath, 'utf8');
936
+ try {
937
+ for (const file of writable) {
938
+ atomicWrite(file.sourcePath, file.content);
939
+ if (file.action === 'create') created.push(file.sourcePath);
940
+ }
941
+ atomicWrite(plan.receiptPath, serializeRegistryReceipt(plan.newReceipt));
942
+ } catch (error) {
943
+ for (const createdPath of created) {
944
+ try {
945
+ fs.rmSync(createdPath, {force: true});
946
+ } catch {
947
+ // Preserve the first failure.
948
+ }
949
+ }
950
+ for (const original of originals) {
951
+ try {
952
+ atomicWrite(original.path, original.content);
953
+ } catch {
954
+ // Preserve the first failure; the caller reports the item as failed.
955
+ }
956
+ }
957
+ try {
958
+ atomicWrite(plan.receiptPath, oldReceiptText);
959
+ } catch {
960
+ // Preserve the first failure.
961
+ }
962
+ throw error;
963
+ }
964
+
965
+ for (const file of plan.files) {
966
+ if (file.conflictPath) fs.rmSync(file.conflictPath, {force: true});
967
+ }
968
+ }
969
+
970
+ /**
971
+ * @param {{apply?: boolean, path?: string}} options
972
+ * @param {{cwd?: string, fetchImpl?: typeof fetch, registryOrigin?: string, expectedVersion?: string, requireExpectedVersion?: boolean}} [ctx]
973
+ */
974
+ export async function reconcileRegistryCompositions(
975
+ options = {},
976
+ {
977
+ cwd = process.cwd(),
978
+ fetchImpl = globalThis.fetch,
979
+ registryOrigin = PUBLIC_SHADCN_REGISTRY_ORIGIN,
980
+ expectedVersion,
981
+ requireExpectedVersion = false,
982
+ } = {},
983
+ ) {
984
+ let root;
985
+ try {
986
+ root = assertWithin(options.path ?? './src', cwd, {
987
+ allowAbsolute: true,
988
+ label: 'source directory',
989
+ });
990
+ } catch (error) {
991
+ if (error instanceof PathSafetyError) {
992
+ throw new AstryxError(
993
+ error.message,
994
+ undefined,
995
+ ERROR_CODES.ERR_PATH_TRAVERSAL,
996
+ );
997
+ }
998
+ throw error;
999
+ }
1000
+
1001
+ const apply = options.apply ?? false;
1002
+ const receipts = discoverRegistryReceipts(root);
1003
+ const summary = emptySummary(apply);
1004
+ summary.found = receipts.length;
1005
+ if (receipts.length === 0) return {summary, writtenFiles: []};
1006
+ if (requireExpectedVersion && !expectedVersion) {
1007
+ throw new AstryxError(
1008
+ 'Could not find installed @astryxdesign/core. Install project dependencies before upgrading copied compositions.',
1009
+ undefined,
1010
+ ERROR_CODES.ERR_VERSION_DETECT,
1011
+ );
1012
+ }
1013
+
1014
+ const plans = await mapWithConcurrency(
1015
+ receipts,
1016
+ FETCH_CONCURRENCY,
1017
+ receiptPath =>
1018
+ planReceipt(receiptPath, root, {
1019
+ fetchImpl,
1020
+ registryOrigin,
1021
+ expectedVersion,
1022
+ }),
1023
+ );
1024
+
1025
+ /** @type {string[]} */
1026
+ const writtenFiles = [];
1027
+ for (const plan of plans) {
1028
+ for (const file of plan.files) {
1029
+ if (file.action === 'missing') summary.missing++;
1030
+ if (file.action === 'invalid' || file.action === 'target-changed') {
1031
+ summary.invalid++;
1032
+ }
1033
+ }
1034
+ recordItem(summary, publicItem(plan, root, apply), plan.action, apply);
1035
+ if (!apply) continue;
1036
+
1037
+ try {
1038
+ applyPlan(plan);
1039
+ if (['update', 'merge'].includes(plan.action)) {
1040
+ for (const file of plan.files) {
1041
+ if (
1042
+ file.sourcePath &&
1043
+ ['update', 'merge', 'create'].includes(file.action)
1044
+ ) {
1045
+ writtenFiles.push(file.sourcePath);
1046
+ }
1047
+ }
1048
+ }
1049
+ } catch (error) {
1050
+ if (plan.action === 'update') summary.updated--;
1051
+ else if (plan.action === 'merge') summary.merged--;
1052
+ else if (plan.action === 'receipt-only') summary.receiptsRefreshed--;
1053
+ summary.failed++;
1054
+ const item = summary.items.at(-1);
1055
+ if (item) {
1056
+ item.action = 'write-error';
1057
+ item.message = error instanceof Error ? error.message : String(error);
1058
+ }
1059
+ }
1060
+ }
1061
+
1062
+ summary.ok =
1063
+ summary.conflicts === 0 &&
1064
+ summary.missing === 0 &&
1065
+ summary.invalid === 0 &&
1066
+ summary.failed === 0;
1067
+ return {summary, writtenFiles};
1068
+ }
1069
+
1070
+ /** @param {import('../upgrade.type.mjs').RegistryCompositionSummary} summary */
1071
+ export function logRegistryCompositionSummary(summary) {
1072
+ if (summary.found === 0) return;
1073
+ logger.log(
1074
+ `${summary.found} ShadCN composition receipt${summary.found === 1 ? '' : 's'} checked.`,
1075
+ );
1076
+ const pending =
1077
+ summary.wouldUpdate + summary.wouldMerge + summary.wouldRefreshReceipt;
1078
+ if (!summary.applied && pending > 0) {
1079
+ logger.log(
1080
+ `${pending} update${pending === 1 ? '' : 's'} available (dry run).`,
1081
+ );
1082
+ }
1083
+ const changed = summary.updated + summary.merged;
1084
+ if (changed + summary.receiptsRefreshed > 0) {
1085
+ logger.log(
1086
+ `${changed} composition${changed === 1 ? '' : 's'} updated` +
1087
+ (summary.receiptsRefreshed > 0
1088
+ ? `; ${summary.receiptsRefreshed} receipt${summary.receiptsRefreshed === 1 ? '' : 's'} refreshed.`
1089
+ : '.'),
1090
+ );
1091
+ }
1092
+ if (
1093
+ summary.conflicts + summary.missing + summary.invalid + summary.failed >
1094
+ 0
1095
+ ) {
1096
+ logger.warn(
1097
+ `${summary.conflicts} conflict(s), ${summary.missing} missing file(s), ` +
1098
+ `${summary.invalid} invalid receipt(s), ${summary.failed} failed item(s).`,
1099
+ );
1100
+ for (const item of summary.items) {
1101
+ if (item.message) logger.warn(` ${item.item}: ${item.message}`);
1102
+ for (const file of item.files) {
1103
+ if (
1104
+ !['conflict', 'missing', 'invalid', 'target-changed'].includes(
1105
+ file.action,
1106
+ )
1107
+ ) {
1108
+ continue;
1109
+ }
1110
+ const detail = file.conflictFile
1111
+ ? ` Review ${file.conflictFile}.`
1112
+ : file.message
1113
+ ? ` ${file.message}.`
1114
+ : '';
1115
+ logger.warn(` ${file.path}: ${file.action}.${detail}`);
1116
+ }
1117
+ }
1118
+ }
1119
+ }
1120
+
1121
+ /**
1122
+ * Standalone `astryx upgrade --registry` leaf.
1123
+ * @param {{apply?: boolean, path?: string}} options
1124
+ * @param {{cwd?: string, fetchImpl?: typeof fetch, registryOrigin?: string, expectedVersion?: string, requireExpectedVersion?: boolean}} [ctx]
1125
+ * @returns {Promise<import('../upgrade.type.mjs').UpgradeRegistryResponse>}
1126
+ */
1127
+ export async function registryUpgrade(options = {}, ctx = {}) {
1128
+ const cwd = ctx.cwd ?? process.cwd();
1129
+ const installed = detectInstalledTargetVersion(cwd);
1130
+ const expectedVersion =
1131
+ ctx.expectedVersion ??
1132
+ (installed?.packageName === '@astryxdesign/core'
1133
+ ? installed.version
1134
+ : undefined);
1135
+ const {summary} = await reconcileRegistryCompositions(options, {
1136
+ ...ctx,
1137
+ cwd,
1138
+ expectedVersion,
1139
+ requireExpectedVersion: true,
1140
+ });
1141
+ if (summary.found === 0) {
1142
+ logger.log('No ShadCN composition receipts found.');
1143
+ } else {
1144
+ logRegistryCompositionSummary(summary);
1145
+ }
1146
+ logger.log(
1147
+ summary.ok
1148
+ ? (summary.applied
1149
+ ? 'Registry upgrade complete'
1150
+ : 'Registry dry run complete') + '\n'
1151
+ : 'Registry upgrade finished with unresolved items\n',
1152
+ );
1153
+ return {type: 'upgrade.registry', data: summary};
1154
+ }