@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,1160 @@
1
+ // Copyright (c) Meta Platforms, Inc. and affiliates.
2
+
3
+ /**
4
+ * @file `integrationAdd(kind, name, options)` — generate one valid
5
+ * contribution into an integration package.
6
+ *
7
+ * Dispatches component, doc, template, codemod, and agent-doc. Theme
8
+ * delegates to the existing `integrationAddTheme` (not modified here).
9
+ * Every root-based kind shares: first add creates the manifest; one shared
10
+ * writer; never creates `files`/`exports`; atomic staged writes; no clobber;
11
+ * dry-run receipt predicts real run; post-write verify through the real
12
+ * discovery/parser seam.
13
+ */
14
+
15
+ import * as fs from 'node:fs';
16
+ import * as path from 'node:path';
17
+ import jscodeshift from 'jscodeshift';
18
+ import {AstryxError} from '../error.mjs';
19
+ import {ERROR_CODES} from '../../foundation/response/error-codes.mjs';
20
+ import {
21
+ assertWithin,
22
+ PathSafetyError,
23
+ sanitizeName,
24
+ } from '../../foundation/fs/path-safety.mjs';
25
+ import {
26
+ findManifestObject,
27
+ unwrapManifestExpression,
28
+ patchIntegrationRoot,
29
+ findLocalIntegrationManifestOrNull,
30
+ IntegrationRootConflictError,
31
+ } from '../../foundation/integrations/manifest-writer.mjs';
32
+ import {
33
+ loadManifestObject,
34
+ loadManifest,
35
+ } from '../../foundation/integrations/integrations.mjs';
36
+ import {isValidSemver} from '../../foundation/env/semver.mjs';
37
+ import {assertContributionVisible} from '../../foundation/integrations/contribution-inventory.mjs';
38
+ import {parseAgentDocsField} from '../../authoring/integration/schema.mjs';
39
+ import {integrationAddTheme} from './add-theme.mjs';
40
+ import {
41
+ findPackageDir,
42
+ projectPath,
43
+ packageJsonUpdate,
44
+ packageJsonFilesUpdate,
45
+ applyWrites,
46
+ } from './add-helpers.mjs';
47
+
48
+ // ── Name grammars ───────────────────────────────────────────────────
49
+
50
+ const COMPONENT_NAME_RE = /^[A-Z][A-Za-z0-9]*$/;
51
+ const KEBAB_NAME_RE = /^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;
52
+ const TOPIC_NAME_RE = /^[\w-]+$/;
53
+
54
+ // ── Default roots (used when the manifest declares nothing) ─────────
55
+
56
+ const DEFAULT_ROOTS = {
57
+ components: './components',
58
+ templates: './templates',
59
+ docs: './docs',
60
+ codemods: './codemods',
61
+ };
62
+
63
+ // ── Shared manifest / package plumbing ──────────────────────────────
64
+
65
+ /**
66
+ * Read package identity + resolve the manifest path.
67
+ * @param {string} cwd
68
+ */
69
+ function resolvePackage(cwd) {
70
+ const packageDir = findPackageDir(cwd);
71
+ const packageFile = path.join(packageDir, 'package.json');
72
+ /** @type {any} */
73
+ let pkg;
74
+ try {
75
+ pkg = JSON.parse(fs.readFileSync(packageFile, 'utf-8'));
76
+ } catch (error) {
77
+ const message = error instanceof Error ? error.message : String(error);
78
+ throw new AstryxError(
79
+ `Cannot read package.json: ${message}`,
80
+ undefined,
81
+ ERROR_CODES.ERR_INVALID_ARGUMENT,
82
+ );
83
+ }
84
+ const owner = typeof pkg.name === 'string' ? pkg.name : '(local integration)';
85
+ const existingManifest = findLocalIntegrationManifestOrNull(packageDir);
86
+ const manifestFile =
87
+ existingManifest ?? path.join(packageDir, 'astryx.integration.mjs');
88
+ return {
89
+ packageDir,
90
+ packageFile,
91
+ pkg,
92
+ owner,
93
+ manifestFile,
94
+ manifestExists: existingManifest != null,
95
+ };
96
+ }
97
+
98
+ /**
99
+ * Load the current manifest's parsed object (or an empty object when no
100
+ * manifest exists yet).
101
+ * @param {string} manifestFile
102
+ * @param {boolean} manifestExists
103
+ * @returns {Promise<import('../../authoring/integration/type').AstryxIntegration>}
104
+ */
105
+ async function loadCurrentManifest(manifestFile, manifestExists) {
106
+ if (!manifestExists) return {};
107
+ return loadManifestObject(
108
+ manifestFile,
109
+ `Integration manifest ${path.basename(manifestFile)}`,
110
+ {fresh: true},
111
+ );
112
+ }
113
+
114
+ /**
115
+ * Build and return the common receipt shape.
116
+ * @param {import('./integration-authoring.type.mjs').IntegrationAddResponse['data']['kind']} kind
117
+ * @param {string} name
118
+ * @param {{path: string, created: boolean}|null} root
119
+ * @param {string} manifestPath
120
+ * @param {string[]} files
121
+ * @param {boolean} dryRun
122
+ * @returns {import('./integration-authoring.type.mjs').IntegrationAddResponse}
123
+ */
124
+ function receipt(kind, name, root, manifestPath, files, dryRun) {
125
+ return {
126
+ type: 'integration.add',
127
+ data: {
128
+ kind,
129
+ name,
130
+ root,
131
+ manifest: manifestPath,
132
+ files,
133
+ written: !dryRun,
134
+ dryRun,
135
+ },
136
+ };
137
+ }
138
+
139
+ // ── Helpers ─────────────────────────────────────────────────────────
140
+
141
+ /** @param {string} slug */
142
+ function kebabToPascal(slug) {
143
+ return slug.replace(/(^|-)([a-z0-9])/gu, (_, _sep, ch) => ch.toUpperCase());
144
+ }
145
+
146
+ /** @param {string} slug */
147
+ function kebabToTitle(slug) {
148
+ const words = slug.split(/[-_]+/u).filter(Boolean);
149
+ if (words.length === 0) return slug;
150
+ return words.map(word => word[0].toUpperCase() + word.slice(1)).join(' ');
151
+ }
152
+
153
+ // ── AST helper (for agent-doc manifest patching) ────────────────────
154
+
155
+ /** @param {any} prop @param {string} name */
156
+ function propNamed(prop, name) {
157
+ const key = prop?.key;
158
+ if (!key) return false;
159
+ return (
160
+ (key.type === 'Identifier' && key.name === name) ||
161
+ (key.type === 'StringLiteral' && key.value === name)
162
+ );
163
+ }
164
+
165
+ // ── Contribution: COMPONENT ─────────────────────────────────────────
166
+
167
+ /**
168
+ * @param {string} name PascalCase component name
169
+ * @param {{cwd?: string, dryRun?: boolean}} options
170
+ * @returns {Promise<import('./integration-authoring.type.mjs').IntegrationAddResponse>}
171
+ */
172
+ async function addComponent(name, options) {
173
+ const {cwd = process.cwd(), dryRun = false} = options;
174
+ if (!COMPONENT_NAME_RE.test(name)) {
175
+ throw new AstryxError(
176
+ `Invalid component name "${name}": use PascalCase starting with an uppercase letter (e.g. MyWidget).`,
177
+ undefined,
178
+ ERROR_CODES.ERR_INVALID_ARGUMENT,
179
+ );
180
+ }
181
+ try {
182
+ sanitizeName(name, {label: 'component name'});
183
+ } catch (error) {
184
+ if (error instanceof PathSafetyError) {
185
+ throw new AstryxError(
186
+ error.message,
187
+ undefined,
188
+ ERROR_CODES.ERR_INVALID_ARGUMENT,
189
+ );
190
+ }
191
+ throw error;
192
+ }
193
+
194
+ const {packageDir, packageFile, owner, manifestFile, manifestExists} =
195
+ resolvePackage(cwd);
196
+ const manifest = await loadCurrentManifest(manifestFile, manifestExists);
197
+ const rootPath = manifest.components ?? DEFAULT_ROOTS.components;
198
+ /** @type {string} */
199
+ let root;
200
+ try {
201
+ root = assertWithin(rootPath, packageDir, {label: 'components root'});
202
+ } catch (error) {
203
+ if (error instanceof PathSafetyError) {
204
+ throw new AstryxError(
205
+ error.message,
206
+ undefined,
207
+ ERROR_CODES.ERR_PATH_TRAVERSAL,
208
+ );
209
+ }
210
+ throw error;
211
+ }
212
+
213
+ // Pre-flight root patch
214
+ try {
215
+ await patchIntegrationRoot(packageDir, 'components', rootPath, {
216
+ dryRun: true,
217
+ createIfMissing: true,
218
+ });
219
+ } catch (error) {
220
+ if (error instanceof IntegrationRootConflictError) {
221
+ throw new AstryxError(
222
+ error.message,
223
+ undefined,
224
+ ERROR_CODES.ERR_INTEGRATION_ROOT_CONFLICT,
225
+ );
226
+ }
227
+ throw error;
228
+ }
229
+
230
+ // Target files
231
+ const docFile = assertWithin(`${name}.doc.mjs`, root, {
232
+ label: 'component doc',
233
+ });
234
+ const sourceFile = assertWithin(`${name}.tsx`, root, {
235
+ label: 'component source',
236
+ });
237
+ if (fs.existsSync(docFile)) {
238
+ throw new AstryxError(
239
+ `Refusing to overwrite existing file ${projectPath(path.relative(packageDir, docFile))}.`,
240
+ undefined,
241
+ ERROR_CODES.ERR_FILE_EXISTS,
242
+ );
243
+ }
244
+ if (fs.existsSync(sourceFile)) {
245
+ throw new AstryxError(
246
+ `Refusing to overwrite existing file ${projectPath(path.relative(packageDir, sourceFile))}.`,
247
+ undefined,
248
+ ERROR_CODES.ERR_FILE_EXISTS,
249
+ );
250
+ }
251
+
252
+ const sourcePath = projectPath(path.relative(packageDir, sourceFile));
253
+ const importSpecifier = `${owner}/${sourcePath}`;
254
+ const docContents = `export default {\n type: 'component',\n name: '${name}',\n import: ${JSON.stringify(importSpecifier)},\n description: '${name} component.',\n props: [],\n};\n`;
255
+ const sourceContents = `export function ${name}() {\n return <div>${name}</div>;\n}\n`;
256
+
257
+ /** @type {import('./add-helpers.mjs').WritePlan[]} */
258
+ const plans = [
259
+ {path: docFile, contents: docContents, createOnly: true},
260
+ {path: sourceFile, contents: sourceContents, createOnly: true},
261
+ ];
262
+ const pkgUpdate = packageJsonUpdate(
263
+ packageFile,
264
+ rootPath,
265
+ path.basename(manifestFile),
266
+ [{subpath: sourcePath, target: sourcePath}],
267
+ );
268
+ if (pkgUpdate != null) {
269
+ plans.push({
270
+ path: packageFile,
271
+ contents: pkgUpdate.contents,
272
+ createOnly: false,
273
+ expectedOriginal: pkgUpdate.expectedOriginal,
274
+ });
275
+ }
276
+
277
+ const writtenFiles = plans.map(p =>
278
+ projectPath(path.relative(packageDir, p.path)),
279
+ );
280
+ const manifestPath = projectPath(path.relative(packageDir, manifestFile));
281
+
282
+ /** @type {{path: string, created: boolean}} */
283
+ let rootReceipt = {path: rootPath, created: !manifest.components};
284
+ if (!dryRun) {
285
+ let rollback = () => {};
286
+ try {
287
+ rollback = applyWrites(plans);
288
+ rootReceipt = await patchIntegrationRoot(
289
+ packageDir,
290
+ 'components',
291
+ rootPath,
292
+ {
293
+ createIfMissing: true,
294
+ verify: async () => {
295
+ const m = await loadManifestObject(manifestFile, 'verify', {
296
+ fresh: true,
297
+ });
298
+ if (!m.components)
299
+ throw new Error('components root not visible after writing.');
300
+ const compsRoot = assertWithin(m.components, packageDir, {
301
+ label: 'components root',
302
+ });
303
+ await assertContributionVisible(
304
+ {name: owner, components: compsRoot},
305
+ 'component',
306
+ name,
307
+ );
308
+ },
309
+ },
310
+ );
311
+ } catch (error) {
312
+ rollback();
313
+ if (error instanceof IntegrationRootConflictError) {
314
+ throw new AstryxError(
315
+ error.message,
316
+ undefined,
317
+ ERROR_CODES.ERR_INTEGRATION_ROOT_CONFLICT,
318
+ );
319
+ }
320
+ if (error instanceof AstryxError) throw error;
321
+ throw new AstryxError(
322
+ `Failed to write component contribution: ${error instanceof Error ? error.message : String(error)}`,
323
+ undefined,
324
+ ERROR_CODES.ERR_WRITE_FAILED,
325
+ );
326
+ }
327
+ }
328
+ if (rootReceipt.created && !writtenFiles.includes(manifestPath)) {
329
+ writtenFiles.push(manifestPath);
330
+ }
331
+ return receipt(
332
+ 'component',
333
+ name,
334
+ rootReceipt,
335
+ manifestPath,
336
+ writtenFiles,
337
+ dryRun,
338
+ );
339
+ }
340
+
341
+ // ── Contribution: DOC TOPIC ─────────────────────────────────────────
342
+
343
+ /**
344
+ * @param {string} name topic name (must match [\w-]+)
345
+ * @param {{cwd?: string, dryRun?: boolean, replaces?: string, extends?: string}} options
346
+ * @returns {Promise<import('./integration-authoring.type.mjs').IntegrationAddResponse>}
347
+ */
348
+ async function addDoc(name, options) {
349
+ const {cwd = process.cwd(), dryRun = false} = options;
350
+ if (!TOPIC_NAME_RE.test(name)) {
351
+ throw new AstryxError(
352
+ `Invalid topic name "${name}": use letters, digits, _ and - only.`,
353
+ undefined,
354
+ ERROR_CODES.ERR_INVALID_ARGUMENT,
355
+ );
356
+ }
357
+ if (options.replaces != null && options.extends != null) {
358
+ throw new AstryxError(
359
+ 'A topic either replaces another or extends it, not both.',
360
+ undefined,
361
+ ERROR_CODES.ERR_INVALID_ARGUMENT,
362
+ );
363
+ }
364
+ for (const [option, value] of [
365
+ ['--replaces', options.replaces],
366
+ ['--extends', options.extends],
367
+ ]) {
368
+ if (value != null && !TOPIC_NAME_RE.test(value)) {
369
+ throw new AstryxError(
370
+ `${option} must name a topic using letters, digits, _ and - only.`,
371
+ undefined,
372
+ ERROR_CODES.ERR_INVALID_ARGUMENT,
373
+ );
374
+ }
375
+ }
376
+
377
+ const {packageDir, packageFile, owner, manifestFile, manifestExists} =
378
+ resolvePackage(cwd);
379
+ const manifest = await loadCurrentManifest(manifestFile, manifestExists);
380
+ const rootPath = manifest.docs ?? DEFAULT_ROOTS.docs;
381
+ /** @type {string} */
382
+ let root;
383
+ try {
384
+ root = assertWithin(rootPath, packageDir, {label: 'docs root'});
385
+ } catch (error) {
386
+ if (error instanceof PathSafetyError) {
387
+ throw new AstryxError(
388
+ error.message,
389
+ undefined,
390
+ ERROR_CODES.ERR_PATH_TRAVERSAL,
391
+ );
392
+ }
393
+ throw error;
394
+ }
395
+
396
+ try {
397
+ await patchIntegrationRoot(packageDir, 'docs', rootPath, {
398
+ dryRun: true,
399
+ createIfMissing: true,
400
+ });
401
+ } catch (error) {
402
+ if (error instanceof IntegrationRootConflictError) {
403
+ throw new AstryxError(
404
+ error.message,
405
+ undefined,
406
+ ERROR_CODES.ERR_INTEGRATION_ROOT_CONFLICT,
407
+ );
408
+ }
409
+ throw error;
410
+ }
411
+
412
+ const docFile = assertWithin(`${name}.doc.mjs`, root, {
413
+ label: 'doc topic file',
414
+ });
415
+ if (fs.existsSync(docFile)) {
416
+ throw new AstryxError(
417
+ `Refusing to overwrite existing file ${projectPath(path.relative(packageDir, docFile))}.`,
418
+ undefined,
419
+ ERROR_CODES.ERR_FILE_EXISTS,
420
+ );
421
+ }
422
+
423
+ const title = kebabToTitle(name);
424
+ const relationship = options.replaces
425
+ ? `\n replaces: '${options.replaces}',`
426
+ : options.extends
427
+ ? `\n extends: '${options.extends}',`
428
+ : '';
429
+ const docContents = `export default {\n type: 'generic',\n name: '${name}',\n title: '${title}',\n description: '${title} documentation.',${relationship}\n sections: [\n {\n title: 'Overview',\n content: [\n { type: 'prose', text: '${title} documentation.' },\n ],\n },\n ],\n};\n`;
430
+
431
+ /** @type {import('./add-helpers.mjs').WritePlan[]} */
432
+ const plans = [{path: docFile, contents: docContents, createOnly: true}];
433
+ const pkgUpdate = packageJsonUpdate(
434
+ packageFile,
435
+ rootPath,
436
+ path.basename(manifestFile),
437
+ );
438
+ if (pkgUpdate != null) {
439
+ plans.push({
440
+ path: packageFile,
441
+ contents: pkgUpdate.contents,
442
+ createOnly: false,
443
+ expectedOriginal: pkgUpdate.expectedOriginal,
444
+ });
445
+ }
446
+
447
+ const writtenFiles = plans.map(p =>
448
+ projectPath(path.relative(packageDir, p.path)),
449
+ );
450
+ const manifestPath = projectPath(path.relative(packageDir, manifestFile));
451
+
452
+ let rootReceipt = {path: rootPath, created: !manifest.docs};
453
+ if (!dryRun) {
454
+ let rollback = () => {};
455
+ try {
456
+ rollback = applyWrites(plans);
457
+ rootReceipt = await patchIntegrationRoot(packageDir, 'docs', rootPath, {
458
+ createIfMissing: true,
459
+ verify: async () => {
460
+ const m = await loadManifestObject(manifestFile, 'verify', {
461
+ fresh: true,
462
+ });
463
+ if (!m.docs) throw new Error('docs root not visible after writing.');
464
+ const docsRoot = assertWithin(m.docs, packageDir, {
465
+ label: 'docs root',
466
+ });
467
+ await assertContributionVisible(
468
+ {name: owner, docs: docsRoot},
469
+ 'doc',
470
+ name,
471
+ );
472
+ },
473
+ });
474
+ } catch (error) {
475
+ rollback();
476
+ if (error instanceof IntegrationRootConflictError) {
477
+ throw new AstryxError(
478
+ error.message,
479
+ undefined,
480
+ ERROR_CODES.ERR_INTEGRATION_ROOT_CONFLICT,
481
+ );
482
+ }
483
+ if (error instanceof AstryxError) throw error;
484
+ throw new AstryxError(
485
+ `Failed to write doc contribution: ${error instanceof Error ? error.message : String(error)}`,
486
+ undefined,
487
+ ERROR_CODES.ERR_WRITE_FAILED,
488
+ );
489
+ }
490
+ }
491
+ if (rootReceipt.created && !writtenFiles.includes(manifestPath)) {
492
+ writtenFiles.push(manifestPath);
493
+ }
494
+ return receipt('doc', name, rootReceipt, manifestPath, writtenFiles, dryRun);
495
+ }
496
+
497
+ // ── Contribution: TEMPLATE ──────────────────────────────────────────
498
+
499
+ /**
500
+ * @param {string} name template id (kebab-case)
501
+ * @param {{cwd?: string, dryRun?: boolean, templateType?: 'page'|'block'}} options
502
+ * @returns {Promise<import('./integration-authoring.type.mjs').IntegrationAddResponse>}
503
+ */
504
+ async function addTemplate(name, options) {
505
+ const {cwd = process.cwd(), dryRun = false, templateType = 'page'} = options;
506
+ if (!KEBAB_NAME_RE.test(name)) {
507
+ throw new AstryxError(
508
+ `Invalid template name "${name}": use lowercase kebab-case starting with a letter.`,
509
+ undefined,
510
+ ERROR_CODES.ERR_INVALID_ARGUMENT,
511
+ );
512
+ }
513
+ if (templateType !== 'page' && templateType !== 'block') {
514
+ throw new AstryxError(
515
+ `Invalid template type "${templateType}": must be "page" or "block".`,
516
+ undefined,
517
+ ERROR_CODES.ERR_INVALID_ARGUMENT,
518
+ );
519
+ }
520
+
521
+ const {packageDir, packageFile, owner, manifestFile, manifestExists} =
522
+ resolvePackage(cwd);
523
+ const manifest = await loadCurrentManifest(manifestFile, manifestExists);
524
+ const rootPath = manifest.templates ?? DEFAULT_ROOTS.templates;
525
+ /** @type {string} */
526
+ let root;
527
+ try {
528
+ root = assertWithin(rootPath, packageDir, {label: 'templates root'});
529
+ } catch (error) {
530
+ if (error instanceof PathSafetyError) {
531
+ throw new AstryxError(
532
+ error.message,
533
+ undefined,
534
+ ERROR_CODES.ERR_PATH_TRAVERSAL,
535
+ );
536
+ }
537
+ throw error;
538
+ }
539
+
540
+ try {
541
+ await patchIntegrationRoot(packageDir, 'templates', rootPath, {
542
+ dryRun: true,
543
+ createIfMissing: true,
544
+ });
545
+ } catch (error) {
546
+ if (error instanceof IntegrationRootConflictError) {
547
+ throw new AstryxError(
548
+ error.message,
549
+ undefined,
550
+ ERROR_CODES.ERR_INTEGRATION_ROOT_CONFLICT,
551
+ );
552
+ }
553
+ throw error;
554
+ }
555
+
556
+ const specFile = assertWithin(`${name}.template.mjs`, root, {
557
+ label: 'template spec',
558
+ });
559
+ const sourceFile = assertWithin(`${name}.tsx`, root, {
560
+ label: 'template source',
561
+ });
562
+ if (fs.existsSync(specFile)) {
563
+ throw new AstryxError(
564
+ `Refusing to overwrite existing file ${projectPath(path.relative(packageDir, specFile))}.`,
565
+ undefined,
566
+ ERROR_CODES.ERR_FILE_EXISTS,
567
+ );
568
+ }
569
+ if (fs.existsSync(sourceFile)) {
570
+ throw new AstryxError(
571
+ `Refusing to overwrite existing file ${projectPath(path.relative(packageDir, sourceFile))}.`,
572
+ undefined,
573
+ ERROR_CODES.ERR_FILE_EXISTS,
574
+ );
575
+ }
576
+
577
+ const pascalName = kebabToPascal(name);
578
+ const sourcePath = projectPath(path.relative(packageDir, sourceFile));
579
+ const specContents = `export default {\n type: '${templateType}',\n name: '${name}',\n description: '${kebabToTitle(name)} template.',\n};\n`;
580
+ const sourceContents = `export default function ${pascalName}() {\n return <div>${kebabToTitle(name)}</div>;\n}\n`;
581
+
582
+ /** @type {import('./add-helpers.mjs').WritePlan[]} */
583
+ const plans = [
584
+ {path: specFile, contents: specContents, createOnly: true},
585
+ {path: sourceFile, contents: sourceContents, createOnly: true},
586
+ ];
587
+ const pkgUpdate = packageJsonUpdate(
588
+ packageFile,
589
+ rootPath,
590
+ path.basename(manifestFile),
591
+ [{subpath: sourcePath, target: sourcePath}],
592
+ );
593
+ if (pkgUpdate != null) {
594
+ plans.push({
595
+ path: packageFile,
596
+ contents: pkgUpdate.contents,
597
+ createOnly: false,
598
+ expectedOriginal: pkgUpdate.expectedOriginal,
599
+ });
600
+ }
601
+
602
+ const writtenFiles = plans.map(p =>
603
+ projectPath(path.relative(packageDir, p.path)),
604
+ );
605
+ const manifestPath = projectPath(path.relative(packageDir, manifestFile));
606
+
607
+ let rootReceipt = {path: rootPath, created: !manifest.templates};
608
+ if (!dryRun) {
609
+ let rollback = () => {};
610
+ try {
611
+ rollback = applyWrites(plans);
612
+ rootReceipt = await patchIntegrationRoot(
613
+ packageDir,
614
+ 'templates',
615
+ rootPath,
616
+ {
617
+ createIfMissing: true,
618
+ verify: async () => {
619
+ const m = await loadManifestObject(manifestFile, 'verify', {
620
+ fresh: true,
621
+ });
622
+ if (!m.templates)
623
+ throw new Error('templates root not visible after writing.');
624
+ const tplRoot = assertWithin(m.templates, packageDir, {
625
+ label: 'templates root',
626
+ });
627
+ await assertContributionVisible(
628
+ {name: owner, templates: tplRoot},
629
+ 'template',
630
+ name,
631
+ );
632
+ },
633
+ },
634
+ );
635
+ } catch (error) {
636
+ rollback();
637
+ if (error instanceof IntegrationRootConflictError) {
638
+ throw new AstryxError(
639
+ error.message,
640
+ undefined,
641
+ ERROR_CODES.ERR_INTEGRATION_ROOT_CONFLICT,
642
+ );
643
+ }
644
+ if (error instanceof AstryxError) throw error;
645
+ throw new AstryxError(
646
+ `Failed to write template contribution: ${error instanceof Error ? error.message : String(error)}`,
647
+ undefined,
648
+ ERROR_CODES.ERR_WRITE_FAILED,
649
+ );
650
+ }
651
+ }
652
+ if (rootReceipt.created && !writtenFiles.includes(manifestPath)) {
653
+ writtenFiles.push(manifestPath);
654
+ }
655
+ return receipt(
656
+ 'template',
657
+ name,
658
+ rootReceipt,
659
+ manifestPath,
660
+ writtenFiles,
661
+ dryRun,
662
+ );
663
+ }
664
+
665
+ // ── Contribution: CODEMOD ───────────────────────────────────────────
666
+
667
+ /**
668
+ * @param {string} name codemod id (kebab-case)
669
+ * @param {{cwd?: string, dryRun?: boolean, to?: string}} options
670
+ * @returns {Promise<import('./integration-authoring.type.mjs').IntegrationAddResponse>}
671
+ */
672
+ async function addCodemod(name, options) {
673
+ const {cwd = process.cwd(), dryRun = false, to} = options;
674
+ if (!to || !isValidSemver(to)) {
675
+ throw new AstryxError(
676
+ `--to is required and must be an exact semver version (e.g. 1.0.0). Received: "${to ?? ''}"`,
677
+ undefined,
678
+ ERROR_CODES.ERR_INVALID_ARGUMENT,
679
+ );
680
+ }
681
+ if (!KEBAB_NAME_RE.test(name)) {
682
+ throw new AstryxError(
683
+ `Invalid codemod id "${name}": use lowercase kebab-case starting with a letter.`,
684
+ undefined,
685
+ ERROR_CODES.ERR_INVALID_ARGUMENT,
686
+ );
687
+ }
688
+
689
+ const {packageDir, packageFile, owner, manifestFile, manifestExists} =
690
+ resolvePackage(cwd);
691
+ const manifest = await loadCurrentManifest(manifestFile, manifestExists);
692
+ const rootPath = manifest.codemods ?? DEFAULT_ROOTS.codemods;
693
+ /** @type {string} */
694
+ let root;
695
+ try {
696
+ root = assertWithin(rootPath, packageDir, {label: 'codemods root'});
697
+ } catch (error) {
698
+ if (error instanceof PathSafetyError) {
699
+ throw new AstryxError(
700
+ error.message,
701
+ undefined,
702
+ ERROR_CODES.ERR_PATH_TRAVERSAL,
703
+ );
704
+ }
705
+ throw error;
706
+ }
707
+
708
+ try {
709
+ await patchIntegrationRoot(packageDir, 'codemods', rootPath, {
710
+ dryRun: true,
711
+ createIfMissing: true,
712
+ });
713
+ } catch (error) {
714
+ if (error instanceof IntegrationRootConflictError) {
715
+ throw new AstryxError(
716
+ error.message,
717
+ undefined,
718
+ ERROR_CODES.ERR_INTEGRATION_ROOT_CONFLICT,
719
+ );
720
+ }
721
+ throw error;
722
+ }
723
+
724
+ const versionDir = assertWithin(to, root, {label: 'codemod version dir'});
725
+ const codemodFile = assertWithin(`${name}.mjs`, versionDir, {
726
+ label: 'codemod file',
727
+ });
728
+ if (fs.existsSync(codemodFile)) {
729
+ throw new AstryxError(
730
+ `Refusing to overwrite existing file ${projectPath(path.relative(packageDir, codemodFile))}.`,
731
+ undefined,
732
+ ERROR_CODES.ERR_FILE_EXISTS,
733
+ );
734
+ }
735
+
736
+ const title = kebabToTitle(name);
737
+ const codemodContents = `export default {\n type: 'code',\n title: '${title}',\n transform(file, api) {\n // Replace this with your transform logic.\n return file.source;\n },\n};\n`;
738
+
739
+ /** @type {import('./add-helpers.mjs').WritePlan[]} */
740
+ const plans = [
741
+ {path: codemodFile, contents: codemodContents, createOnly: true},
742
+ ];
743
+ const pkgUpdate = packageJsonUpdate(
744
+ packageFile,
745
+ rootPath,
746
+ path.basename(manifestFile),
747
+ );
748
+ if (pkgUpdate != null) {
749
+ plans.push({
750
+ path: packageFile,
751
+ contents: pkgUpdate.contents,
752
+ createOnly: false,
753
+ expectedOriginal: pkgUpdate.expectedOriginal,
754
+ });
755
+ }
756
+
757
+ const writtenFiles = plans.map(p =>
758
+ projectPath(path.relative(packageDir, p.path)),
759
+ );
760
+ const manifestPath = projectPath(path.relative(packageDir, manifestFile));
761
+
762
+ let rootReceipt = {path: rootPath, created: !manifest.codemods};
763
+ if (!dryRun) {
764
+ let rollback = () => {};
765
+ try {
766
+ rollback = applyWrites(plans);
767
+ rootReceipt = await patchIntegrationRoot(
768
+ packageDir,
769
+ 'codemods',
770
+ rootPath,
771
+ {
772
+ createIfMissing: true,
773
+ verify: async () => {
774
+ const m = await loadManifestObject(manifestFile, 'verify', {
775
+ fresh: true,
776
+ });
777
+ if (!m.codemods)
778
+ throw new Error('codemods root not visible after writing.');
779
+ const codemodsRoot = assertWithin(m.codemods, packageDir, {
780
+ label: 'codemods root',
781
+ });
782
+ await assertContributionVisible(
783
+ {name: owner, codemods: codemodsRoot},
784
+ 'codemod',
785
+ name,
786
+ {version: to},
787
+ );
788
+ },
789
+ },
790
+ );
791
+ } catch (error) {
792
+ rollback();
793
+ if (error instanceof IntegrationRootConflictError) {
794
+ throw new AstryxError(
795
+ error.message,
796
+ undefined,
797
+ ERROR_CODES.ERR_INTEGRATION_ROOT_CONFLICT,
798
+ );
799
+ }
800
+ if (error instanceof AstryxError) throw error;
801
+ throw new AstryxError(
802
+ `Failed to write codemod contribution: ${error instanceof Error ? error.message : String(error)}`,
803
+ undefined,
804
+ ERROR_CODES.ERR_WRITE_FAILED,
805
+ );
806
+ }
807
+ }
808
+ if (rootReceipt.created && !writtenFiles.includes(manifestPath)) {
809
+ writtenFiles.push(manifestPath);
810
+ }
811
+ return receipt(
812
+ 'codemod',
813
+ name,
814
+ rootReceipt,
815
+ manifestPath,
816
+ writtenFiles,
817
+ dryRun,
818
+ );
819
+ }
820
+
821
+ // ── Contribution: AGENT-DOC ─────────────────────────────────────────
822
+
823
+ /**
824
+ * @param {string} line the literal agent-doc line
825
+ * @param {{cwd?: string, dryRun?: boolean}} options
826
+ * @returns {Promise<import('./integration-authoring.type.mjs').IntegrationAddResponse>}
827
+ */
828
+ async function addAgentDoc(line, options) {
829
+ const {cwd = process.cwd(), dryRun = false} = options;
830
+
831
+ // Validate against the real schema
832
+ try {
833
+ parseAgentDocsField({append: [line]}, 'agentDocs');
834
+ } catch (error) {
835
+ throw new AstryxError(
836
+ error instanceof Error ? error.message : String(error),
837
+ undefined,
838
+ ERROR_CODES.ERR_INVALID_ARGUMENT,
839
+ );
840
+ }
841
+
842
+ const {packageDir, packageFile, manifestFile, manifestExists, owner} =
843
+ resolvePackage(cwd);
844
+ const manifestPath = projectPath(path.relative(packageDir, manifestFile));
845
+
846
+ // Load current agentDocs.append. A bad existing value is author-owned data;
847
+ // refuse it rather than "repairing" it by silently replacing the lines.
848
+ /** @type {string[]} */
849
+ let currentAppend = [];
850
+ if (manifestExists) {
851
+ try {
852
+ const loaded = await loadManifest(
853
+ manifestFile,
854
+ `Integration manifest ${path.basename(manifestFile)}`,
855
+ {fresh: true},
856
+ );
857
+ if (loaded.agentDocsError) throw new Error(loaded.agentDocsError);
858
+ if (loaded.manifest.agentDocs?.append) {
859
+ currentAppend = [...loaded.manifest.agentDocs.append];
860
+ }
861
+ } catch (error) {
862
+ throw new AstryxError(
863
+ `Cannot update agentDocs: ${error instanceof Error ? error.message : String(error)}`,
864
+ undefined,
865
+ ERROR_CODES.ERR_INVALID_ARGUMENT,
866
+ );
867
+ }
868
+ }
869
+
870
+ // Converge: if line is already present, return idempotent receipt
871
+ if (currentAppend.includes(line)) {
872
+ return {
873
+ type: 'integration.add',
874
+ data: {
875
+ kind: 'agent-doc',
876
+ name: line,
877
+ root: null,
878
+ manifest: manifestPath,
879
+ files: [],
880
+ written: false,
881
+ dryRun,
882
+ },
883
+ };
884
+ }
885
+
886
+ // Compute and validate the new array
887
+ const newAppend = [...currentAppend, line];
888
+ try {
889
+ parseAgentDocsField({append: newAppend}, 'agentDocs');
890
+ } catch (error) {
891
+ throw new AstryxError(
892
+ `Cannot add agent-doc line: ${error instanceof Error ? error.message : String(error)}`,
893
+ undefined,
894
+ ERROR_CODES.ERR_INVALID_ARGUMENT,
895
+ );
896
+ }
897
+
898
+ // AST-patch the manifest
899
+ const source = manifestExists
900
+ ? fs.readFileSync(manifestFile, 'utf-8')
901
+ : 'export default {};\n';
902
+ const j = jscodeshift.withParser('tsx');
903
+ /** @type {ReturnType<ReturnType<typeof jscodeshift.withParser>>} */
904
+ let ast;
905
+ try {
906
+ ast = j(source);
907
+ } catch (error) {
908
+ const message = error instanceof Error ? error.message : String(error);
909
+ throw new AstryxError(
910
+ `Could not parse ${path.basename(manifestFile)}: ${message}`,
911
+ undefined,
912
+ ERROR_CODES.ERR_WRITE_FAILED,
913
+ );
914
+ }
915
+ const object = findManifestObject(j, ast);
916
+ if (!object) {
917
+ throw new AstryxError(
918
+ `Could not update ${path.basename(manifestFile)} safely: its default export is not a static object literal.`,
919
+ undefined,
920
+ ERROR_CODES.ERR_WRITE_FAILED,
921
+ );
922
+ }
923
+
924
+ const agentDocsProperties = object.properties.filter(
925
+ (/** @type {any} */ property) => propNamed(property, 'agentDocs'),
926
+ );
927
+ if (agentDocsProperties.length > 1) {
928
+ throw new AstryxError(
929
+ 'Cannot update agentDocs safely: the manifest declares it more than once.',
930
+ undefined,
931
+ ERROR_CODES.ERR_WRITE_FAILED,
932
+ );
933
+ }
934
+
935
+ if (agentDocsProperties.length === 1) {
936
+ const agentDocsProperty = /** @type {any} */ (agentDocsProperties[0]);
937
+ const agentDocsObject = unwrapManifestExpression(agentDocsProperty.value);
938
+ if (!j.ObjectExpression.check(agentDocsObject)) {
939
+ throw new AstryxError(
940
+ 'Cannot update agentDocs safely: it is not a static object literal.',
941
+ undefined,
942
+ ERROR_CODES.ERR_WRITE_FAILED,
943
+ );
944
+ }
945
+ const appendProperties = agentDocsObject.properties.filter(
946
+ (/** @type {any} */ property) => propNamed(property, 'append'),
947
+ );
948
+ if (appendProperties.length > 1) {
949
+ throw new AstryxError(
950
+ 'Cannot update agentDocs safely: append is declared more than once.',
951
+ undefined,
952
+ ERROR_CODES.ERR_WRITE_FAILED,
953
+ );
954
+ }
955
+ if (appendProperties.length === 1) {
956
+ const appendProperty = /** @type {any} */ (appendProperties[0]);
957
+ const appendArray = unwrapManifestExpression(appendProperty.value);
958
+ if (!j.ArrayExpression.check(appendArray)) {
959
+ throw new AstryxError(
960
+ 'Cannot update agentDocs safely: append is not a static array literal.',
961
+ undefined,
962
+ ERROR_CODES.ERR_WRITE_FAILED,
963
+ );
964
+ }
965
+ appendArray.elements.push(j.stringLiteral(line));
966
+ } else {
967
+ agentDocsObject.properties.push(
968
+ j.objectProperty(
969
+ j.identifier('append'),
970
+ j.arrayExpression([j.stringLiteral(line)]),
971
+ ),
972
+ );
973
+ }
974
+ } else {
975
+ if (currentAppend.length > 0) {
976
+ throw new AstryxError(
977
+ 'Cannot update agentDocs safely: it comes from a spread or computed property.',
978
+ undefined,
979
+ ERROR_CODES.ERR_WRITE_FAILED,
980
+ );
981
+ }
982
+ object.properties.push(
983
+ j.objectProperty(
984
+ j.identifier('agentDocs'),
985
+ j.objectExpression([
986
+ j.objectProperty(
987
+ j.identifier('append'),
988
+ j.arrayExpression([j.stringLiteral(line)]),
989
+ ),
990
+ ]),
991
+ ),
992
+ );
993
+ }
994
+
995
+ let next = ast.toSource({quote: 'single', reuseWhitespace: true});
996
+ if (source.endsWith('\n') && !next.endsWith('\n')) next += '\n';
997
+
998
+ /** @type {import('./add-helpers.mjs').WritePlan[]} */
999
+ const plans = [
1000
+ {
1001
+ path: manifestFile,
1002
+ contents: next,
1003
+ createOnly: !manifestExists,
1004
+ expectedOriginal: manifestExists ? Buffer.from(source) : undefined,
1005
+ },
1006
+ ];
1007
+ const packageUpdate = packageJsonFilesUpdate(packageFile, [manifestPath]);
1008
+ if (packageUpdate != null) {
1009
+ plans.push({
1010
+ path: packageFile,
1011
+ contents: packageUpdate.contents,
1012
+ createOnly: false,
1013
+ expectedOriginal: packageUpdate.expectedOriginal,
1014
+ });
1015
+ }
1016
+ const writtenFiles = plans.map(plan =>
1017
+ projectPath(path.relative(packageDir, plan.path)),
1018
+ );
1019
+ if (dryRun) {
1020
+ return receipt('agent-doc', line, null, manifestPath, writtenFiles, true);
1021
+ }
1022
+
1023
+ const rollback = applyWrites(plans);
1024
+
1025
+ // Verify through the real parser
1026
+ try {
1027
+ const verified = await loadManifest(manifestFile, 'verify', {fresh: true});
1028
+ await assertContributionVisible(
1029
+ {name: owner, agentDocs: verified.manifest.agentDocs},
1030
+ 'agent-doc',
1031
+ line,
1032
+ );
1033
+ if (verified.agentDocsError) {
1034
+ throw new Error(verified.agentDocsError);
1035
+ }
1036
+ } catch (error) {
1037
+ rollback();
1038
+ throw new AstryxError(
1039
+ `Post-write verification failed: ${error instanceof Error ? error.message : String(error)}`,
1040
+ undefined,
1041
+ ERROR_CODES.ERR_WRITE_FAILED,
1042
+ );
1043
+ }
1044
+
1045
+ return receipt('agent-doc', line, null, manifestPath, writtenFiles, false);
1046
+ }
1047
+
1048
+ // ── Public per-kind APIs ────────────────────────────────────────────
1049
+
1050
+ /**
1051
+ * @param {string} name
1052
+ * @param {import('./integration-authoring.type.mjs').IntegrationAddComponentOptions} [options]
1053
+ */
1054
+ export function integrationAddComponent(name, options = {}) {
1055
+ return addComponent(name, options);
1056
+ }
1057
+
1058
+ /**
1059
+ * @param {string} name
1060
+ * @param {import('./integration-authoring.type.mjs').IntegrationAddDocOptions} [options]
1061
+ */
1062
+ export function integrationAddDoc(name, options = {}) {
1063
+ return addDoc(name, options);
1064
+ }
1065
+
1066
+ /**
1067
+ * @param {string} name
1068
+ * @param {import('./integration-authoring.type.mjs').IntegrationAddTemplateOptions} [options]
1069
+ */
1070
+ export function integrationAddTemplate(name, options = {}) {
1071
+ const {type, ...shared} = options;
1072
+ return addTemplate(name, {...shared, templateType: type});
1073
+ }
1074
+
1075
+ /**
1076
+ * @param {string} name
1077
+ * @param {import('./integration-authoring.type.mjs').IntegrationAddCodemodOptions} options
1078
+ */
1079
+ export function integrationAddCodemod(name, options) {
1080
+ return addCodemod(name, options);
1081
+ }
1082
+
1083
+ /**
1084
+ * @param {string} line
1085
+ * @param {import('./integration-authoring.type.mjs').IntegrationAddAgentDocOptions} [options]
1086
+ */
1087
+ export function integrationAddAgentDoc(line, options = {}) {
1088
+ return addAgentDoc(line, options);
1089
+ }
1090
+
1091
+ // ── Public dispatcher ───────────────────────────────────────────────
1092
+
1093
+ const KIND_OPTIONS = {
1094
+ component: new Set(['cwd', 'dryRun']),
1095
+ doc: new Set(['cwd', 'dryRun', 'replaces', 'extends']),
1096
+ template: new Set(['cwd', 'dryRun', 'templateType']),
1097
+ codemod: new Set(['cwd', 'dryRun', 'to']),
1098
+ 'agent-doc': new Set(['cwd', 'dryRun']),
1099
+ theme: new Set(['cwd', 'dryRun']),
1100
+ };
1101
+
1102
+ /**
1103
+ * Refuse options that belong to another contribution kind. Ignoring one is a
1104
+ * silent success: the command exits zero while not doing what the caller asked.
1105
+ * @param {keyof typeof KIND_OPTIONS} kind
1106
+ * @param {Record<string, unknown>} options
1107
+ */
1108
+ function validateKindOptions(kind, options) {
1109
+ const allowed = KIND_OPTIONS[kind];
1110
+ for (const [key, value] of Object.entries(options)) {
1111
+ if (value !== undefined && !allowed.has(key)) {
1112
+ throw new AstryxError(
1113
+ `Option "${key}" does not apply to integration kind "${kind}".`,
1114
+ undefined,
1115
+ ERROR_CODES.ERR_INVALID_ARGUMENT,
1116
+ );
1117
+ }
1118
+ }
1119
+ }
1120
+
1121
+ /**
1122
+ * Add one contribution to the local integration package.
1123
+ *
1124
+ * @param {'component'|'doc'|'template'|'codemod'|'agent-doc'|'theme'} kind
1125
+ * @param {string} name
1126
+ * @param {{cwd?: string, dryRun?: boolean, templateType?: 'page'|'block', to?: string, replaces?: string, extends?: string}} [options]
1127
+ * @returns {Promise<import('./integration-authoring.type.mjs').IntegrationAddResponse>}
1128
+ */
1129
+ export async function integrationAdd(kind, name, options = {}) {
1130
+ if (!Object.prototype.hasOwnProperty.call(KIND_OPTIONS, kind)) {
1131
+ throw new AstryxError(
1132
+ `Unknown contribution kind "${kind}". Choose component, doc, template, codemod, agent-doc, or theme.`,
1133
+ undefined,
1134
+ ERROR_CODES.ERR_INVALID_ARGUMENT,
1135
+ );
1136
+ }
1137
+ validateKindOptions(kind, options);
1138
+ switch (kind) {
1139
+ case 'component':
1140
+ return integrationAddComponent(name, options);
1141
+ case 'doc':
1142
+ return integrationAddDoc(name, options);
1143
+ case 'template':
1144
+ return integrationAddTemplate(name, {
1145
+ cwd: options.cwd,
1146
+ dryRun: options.dryRun,
1147
+ type: options.templateType,
1148
+ });
1149
+ case 'codemod':
1150
+ return integrationAddCodemod(name, {
1151
+ cwd: options.cwd,
1152
+ dryRun: options.dryRun,
1153
+ to: /** @type {string} */ (options.to),
1154
+ });
1155
+ case 'agent-doc':
1156
+ return integrationAddAgentDoc(name, options);
1157
+ case 'theme':
1158
+ return integrationAddTheme(name, options);
1159
+ }
1160
+ }