@astryxdesign/cli 0.6.5-canary.f261d2f → 0.6.5-canary.f27f749

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 (76) hide show
  1. package/README.md +14 -13
  2. package/api/error.d.mts +22 -0
  3. package/api/error.mjs +42 -0
  4. package/api/integration/add-contribution.d.mts +2 -1
  5. package/api/integration/add-contribution.mjs +7 -3
  6. package/api/integration/add-theme.mjs +243 -22
  7. package/api/integration/add-theme.test.mjs +213 -0
  8. package/api/integration/authoring-checks.mjs +10 -7
  9. package/api/integration/authoring-checks.type.d.mts +8 -0
  10. package/api/integration/authoring-checks.type.mjs +7 -3
  11. package/api/integration/integration-authoring.type.d.mts +4 -1
  12. package/api/integration/integration-authoring.type.mjs +6 -1
  13. package/api/integration/integrationAdd.doc.mjs +6 -0
  14. package/api/integration/integrationAddTheme.doc.mjs +10 -0
  15. package/api/integration/integrationComponentConflicts.doc.mjs +1 -1
  16. package/api/integration/integrationDocConflicts.doc.mjs +1 -1
  17. package/api/integration/integrationTemplateConflicts.doc.mjs +1 -1
  18. package/api/integration/validate-integration.d.mts +4 -2
  19. package/api/integration/validate-integration.mjs +7 -2
  20. package/api/integration/validate-integration.test.mjs +55 -0
  21. package/api/integration/validate-integration.type.d.mts +5 -0
  22. package/api/integration/validate-integration.type.mjs +5 -1
  23. package/api/integration/validateIntegration.doc.mjs +1 -1
  24. package/api/layout/expand/expand.mjs +12 -7
  25. package/api/layout/expand/expand.receipt.test.mjs +74 -0
  26. package/api/layout/layout.type.d.mts +1 -0
  27. package/api/layout/layout.type.mjs +1 -0
  28. package/api/layout/layoutExpand.doc.mjs +1 -1
  29. package/api/swizzle/copy/copy.mjs +66 -3
  30. package/api/swizzle/swizzle.doc.mjs +4 -0
  31. package/api/template/copy/copy.mjs +14 -8
  32. package/api/template/copy/copy.receipt.test.mjs +77 -0
  33. package/api/template/show/show.mjs +15 -4
  34. package/api/template/show/show.test.mjs +76 -0
  35. package/api/template/template.d.mts +1 -1
  36. package/api/template/template.doc.mjs +6 -2
  37. package/api/template/template.mjs +1 -0
  38. package/api/template/template.type.d.mts +2 -0
  39. package/api/template/template.type.mjs +2 -0
  40. package/api/theme/build/build.d.mts +24 -0
  41. package/api/theme/build/build.mjs +235 -8
  42. package/api/theme/build/build.project-core.test.mjs +165 -0
  43. package/api/upgrade/run/run.mjs +20 -3
  44. package/api/upgrade/run/run.test.mjs +45 -1
  45. package/api/upgrade/upgrade.doc.mjs +1 -1
  46. package/api/upgrade/upgrade.type.d.mts +1 -0
  47. package/api/upgrade/upgrade.type.mjs +1 -0
  48. package/assets/docs/icons.doc.mjs +1 -0
  49. package/assets/templates/themes/butter/icons.tsx +2 -0
  50. package/assets/templates/themes/chocolate/icons.tsx +2 -0
  51. package/assets/templates/themes/gothic/icons.tsx +2 -0
  52. package/assets/templates/themes/matcha/icons.tsx +2 -0
  53. package/assets/templates/themes/neutral/icons.tsx +2 -0
  54. package/assets/templates/themes/stone/icons.tsx +2 -0
  55. package/assets/templates/themes/y2k/icons.tsx +2 -0
  56. package/clients/cli/commands/doctor.mjs +4 -4
  57. package/clients/cli/commands/integration-add.doc.mjs +10 -0
  58. package/clients/cli/commands/integration-authoring.test.mjs +12 -2
  59. package/clients/cli/commands/integration.mjs +3 -1
  60. package/clients/cli/commands/layout-expand.doc.mjs +3 -1
  61. package/clients/cli/commands/layout.expand-receipt.test.mjs +94 -0
  62. package/clients/cli/commands/layout.mjs +16 -0
  63. package/clients/cli/commands/template.copy-receipt.test.mjs +60 -0
  64. package/clients/cli/commands/template.mjs +19 -5
  65. package/clients/cli/commands/template.show-media.test.mjs +62 -0
  66. package/clients/cli/commands/upgrade.ascii-output.test.mjs +14 -0
  67. package/clients/cli/commands/write-failure.test.mjs +175 -0
  68. package/clients/cli/lib/manifest.mjs +44 -165
  69. package/clients/cli/lib/manifest.test.mjs +98 -7
  70. package/foundation/discovery/template-adapter.d.mts +13 -0
  71. package/foundation/discovery/template-adapter.fixture-refs.test.mjs +37 -1
  72. package/foundation/discovery/template-adapter.mjs +16 -1
  73. package/foundation/doc-compiler/doc-loads.test.mjs +2 -2
  74. package/foundation/response/response-types.doc.d.mts +5 -5
  75. package/foundation/response/response-types.doc.mjs +13 -13
  76. package/package.json +9 -9
package/README.md CHANGED
@@ -303,11 +303,12 @@ Shape:
303
303
  ```
304
304
 
305
305
  The manifest is **derived from Commander metadata** (commands, arguments, options)
306
- so it can't drift from the real command definitions. The two facts Commander
307
- doesn't track (`--json` support and emitted response types) are layered on from
308
- the `JSON_SUPPORTED` allowlist and a small declarative `RESPONSE_TYPES` map in
309
- `src/lib/manifest.mjs`, guarded by a drift test (`manifest.test.mjs`) so adding a
310
- command without describing it fails CI.
306
+ so it can't drift from the real command definitions. The facts Commander doesn't
307
+ track come from each command's docs: examples from its CommandDoc, and emitted
308
+ response types from the returns of the FunctionDoc it wraps (plus the few
309
+ envelopes the CLI layer builds itself). `--json` support comes from the
310
+ `JSON_SUPPORTED` allowlist. Drift tests (`manifest.test.mjs`) fail CI when a
311
+ command is added without describing it.
311
312
 
312
313
  **Backwards-compat:** the bare `astryx --json` envelope keeps `type: "help"` and its
313
314
  original shallow fields (`name`, `version`, `commands` as a `string[]` of names,
@@ -450,9 +451,9 @@ Every response has a `type` discriminant. The full set is below (generated from
450
451
  | `gap-report.categories` | The fixed gap category values and human-readable labels. |
451
452
  | `gap-report.file` | An aggregate receipt: overall status, the selected package, issuesUrl (or null), deliveries in handler order, each {handlerType: project \| integration \| fallback, handler, audience, status, url, message}, and filedCount/routedOnlyCount totals. |
452
453
  | `template.list` | The effective discovered TemplateListEntry[] for pages and blocks. A winning replacement entry includes optional `replaces`, naming the Core id omitted from the default list. |
453
- | `template.show` | The resolved template's raw source plus its description, kind, and the component names it composes. |
454
+ | `template.show` | The resolved template's source, exactly as a copy writes it, plus its description, kind, the component names it composes, and demoMediaReplaced (how many Astryx demo media references were replaced with placeholders for you to swap for your own media). |
454
455
  | `template.skeleton` | A layout skeleton (structural tags with spatial annotations) plus the template's description and the components it composes. |
455
- | `template.copy` | A scaffold receipt: template id, output directory, written file name, and file count. |
456
+ | `template.copy` | A scaffold receipt: template id, output directory, written file name, file count, and demoMediaReplaced (how many Astryx demo media references were replaced with placeholders for you to swap for your own media). |
456
457
  | `template.cdn` | A write receipt for the no-build-step CDN starter page: the path (relative to cwd), the Astryx version every CDN URL was pinned to, whether it was written, and the reason it was not. `exists` when a file was already there, which is a success. |
457
458
  | `hook.list` | The hook catalog grouped by category: `detail` (the level: names \| compact \| full) and `components`, the grouped map of hook names, brief entries, or a full HookDoc per entry. |
458
459
  | `hook.detail` | One hook's full authored HookDoc. |
@@ -468,18 +469,18 @@ Every response has a `type` discriminant. The full set is below (generated from
468
469
  | `upgrade.list` | Every available codemod, oldest→newest, as {name, title, version, optional}; returned for --list without running anything. |
469
470
  | `upgrade.registry` | The copied-composition receipt for --registry: applied, ok, the counts (found, current, wouldUpdate, updated, wouldMerge, merged, wouldRefreshReceipt, receiptsRefreshed, conflicts, missing, invalid, failed), and items. |
470
471
  | `upgrade.status` | A short-circuit outcome with no codemods run (up_to_date, no_codemods, or config_fixable), each carrying the agent-docs summary. |
471
- | `upgrade.run` | The run receipt: from/to versions, codemod count, integrations processed, the agent-docs summary, and (apply mode) filesChanged, transformsApplied, and per-codemod errors. |
472
+ | `upgrade.run` | The run receipt: from/to versions, codemod count, integrations processed, the agent-docs summary, sourcePathFound (false when the resolved source directory does not exist, so no source file was read), and (apply mode) filesChanged, transformsApplied, and per-codemod errors. |
472
473
  | `manifest` | The CLI capability manifest: name, version, apiVersion, description, globalOptions, commands (each name, description, arguments, options, json, aliases?, responseTypes?, examples?, exitCodes? as [{code, when}], subcommands?), jsonSupported, and the flat responseTypes index. |
473
474
  | `help` | Help, in one of two shapes. A bare `astryx --json` returns the root manifest: name, version, commands (the command names), jsonSupported, and manifest (the full payload `astryx manifest --json` returns). `--help --json` on any command, or `astryx help [command] --json`, returns that command's help: command, description, usage, options (each flags, description, and defaultValue and choices when set), and subcommands (each name and description). data.manifest marks the first shape; data.usage marks the second. |
474
475
  | `version` | The CLI version, for `astryx --version --json`: {version}. |
475
476
  | `doctor` | The health-check report: `checks` (each with id, label, status: pass \| warn \| fail \| info, a message, and an optional fix, always present on warn and fail) plus a `summary` of counts per status. |
476
477
  | `integration.add` | A contribution-writer receipt: kind, name, optional root {path, created}, integration-manifest path, every affected project-relative path, written, and dryRun. |
477
478
  | `integration.pack-check` | The packed-package check: name, version, packable, tarball {filename, fileCount, size, unpackedSize} or null, inventory {manifest, roots [{kind, path, expectedFiles, missingFiles, complete}], expectedFiles, packedFiles}, contributions {local, packed}, each null or {themes [{slug, exportName}], components, templates [{id, type, name}], codemods [{version, id}], docs, agentDocsAppend}, and issues [{code, severity, message}]. |
478
- | `integration.validate` | The validation result: the package name and version (both null when no local manifest is found) plus issues, an AstryxIntegrationIssue[] of {code, severity: warning \| error, message}. |
479
- | `integration.template-conflicts` | The integration identity, structural issues, and non-blocking Core template-id conflicts as {id, severity: warning, integrationPackage, integrationType, integrationName, coreMatches, message, command}. |
480
- | `integration.component-conflicts` | The integration identity, structural issues, and non-blocking conflicts where an integration component name is also owned by Core; each conflict includes the exact package-qualified command. |
481
- | `integration.doc-conflicts` | The integration identity, structural issues, and Core doc overlaps. Each finding includes `severity` (`info` \| `error`) and `relationship` (`replaces` \| `extends` \| `accidental`). |
482
- | `layout.expand` | The expansion: parsed form, generated TSX code, componentsUsed, states (count of useState hooks scaffolded), todos, blocksReferenced (each {name, mode}), warnings, and written (the output path, or null when nothing was written). |
479
+ | `integration.validate` | The validation result: validated (false when no integration manifest was found, so nothing was checked and the empty issues list proves nothing), the package name and version (both null when validated is false) plus issues, an AstryxIntegrationIssue[] of {code, severity: warning \| error, message}. |
480
+ | `integration.template-conflicts` | validated (false when no integration manifest was found, so nothing was inspected), the integration identity, structural issues, and non-blocking Core template-id conflicts as {id, severity: warning, integrationPackage, integrationType, integrationName, coreMatches, message, command}. |
481
+ | `integration.component-conflicts` | validated (false when no integration manifest was found, so nothing was inspected), the integration identity, structural issues, and non-blocking conflicts where an integration component name is also owned by Core; each conflict includes the exact package-qualified command. |
482
+ | `integration.doc-conflicts` | validated (false when no integration manifest was found, so nothing was inspected), the integration identity, structural issues, and Core doc overlaps. Each finding includes `severity` (`info` \| `error`) and `relationship` (`replaces` \| `extends` \| `accidental`). |
483
+ | `layout.expand` | The expansion: parsed form, generated TSX code, componentsUsed, states (count of useState hooks scaffolded), todos, blocksReferenced (each {name, mode}), warnings, written (the output path, or null when nothing was written), and demoMediaReplaced (count of demo media placeholders). |
483
484
  | `layout.check` | The validation result: a valid flag, the detected form, errors (each with line/col, message, formatted text, and suggestions), warnings, and the expression re-printed in both canonical surfaces (compact and outline). |
484
485
  | `layout.grammar` | The XLE/XLO grammar cheatsheet: a text field with the full reference plus an aliases map (short name → canonical component) generated from this install's registry. |
485
486
 
package/api/error.d.mts CHANGED
@@ -1,6 +1,28 @@
1
1
  // @generated by scripts/sync-api-types.mjs from the JSDoc in api/**/*.mjs.
2
2
  // DO NOT EDIT — run `pnpm sync:api-types` to regenerate.
3
3
 
4
+ /**
5
+ * The error for a write that failed on the filesystem: no permission, a
6
+ * read-only mount, a full disk, a path component that is not a directory.
7
+ *
8
+ * A raw Node errno error reached the envelope as
9
+ * `{"error": "EACCES: permission denied, open '/home/you/p/readonly/x.tsx'",
10
+ * "code": "ERR_UNKNOWN"}` — the wrong code (ERR_WRITE_FAILED is in the frozen
11
+ * registry for exactly this) and an absolute host path in the message. This
12
+ * keeps the errno, which is the part that tells you what to fix, and reports
13
+ * the target the way every other Astryx message does: relative to the project.
14
+ *
15
+ * A caller that wrote files before the failure must undo them first and pass
16
+ * the ones it could not restore as `unrestored`, so the message never says
17
+ * nothing was written when something was.
18
+ *
19
+ * @param {string} target absolute path the write was aimed at
20
+ * @param {string} cwd project root, for the relative form
21
+ * @param {unknown} cause the error the filesystem call threw
22
+ * @param {string[]} [unrestored] absolute paths an undo could not put back
23
+ * @returns {AstryxError}
24
+ */
25
+ export function writeFailed(target: string, cwd: string, cause: unknown, unrestored?: string[]): AstryxError;
4
26
  export class AstryxError extends Error {
5
27
  /**
6
28
  * @param {string} message
package/api/error.mjs CHANGED
@@ -12,6 +12,7 @@
12
12
  */
13
13
 
14
14
  import {ERROR_CODES} from '../foundation/response/error-codes.mjs';
15
+ import * as path from 'node:path';
15
16
 
16
17
  export class AstryxError extends Error {
17
18
  /** @type {import('../foundation/response/base').Suggestion[] | undefined} */
@@ -36,3 +37,44 @@ export class AstryxError extends Error {
36
37
  if (Array.isArray(suggestions) && suggestions.length) this.suggestions = suggestions;
37
38
  }
38
39
  }
40
+
41
+ /**
42
+ * The error for a write that failed on the filesystem: no permission, a
43
+ * read-only mount, a full disk, a path component that is not a directory.
44
+ *
45
+ * A raw Node errno error reached the envelope as
46
+ * `{"error": "EACCES: permission denied, open '/home/you/p/readonly/x.tsx'",
47
+ * "code": "ERR_UNKNOWN"}` — the wrong code (ERR_WRITE_FAILED is in the frozen
48
+ * registry for exactly this) and an absolute host path in the message. This
49
+ * keeps the errno, which is the part that tells you what to fix, and reports
50
+ * the target the way every other Astryx message does: relative to the project.
51
+ *
52
+ * A caller that wrote files before the failure must undo them first and pass
53
+ * the ones it could not restore as `unrestored`, so the message never says
54
+ * nothing was written when something was.
55
+ *
56
+ * @param {string} target absolute path the write was aimed at
57
+ * @param {string} cwd project root, for the relative form
58
+ * @param {unknown} cause the error the filesystem call threw
59
+ * @param {string[]} [unrestored] absolute paths an undo could not put back
60
+ * @returns {AstryxError}
61
+ */
62
+ export function writeFailed(target, cwd, cause, unrestored = []) {
63
+ const rel = path.relative(cwd, target) || target;
64
+ const errno =
65
+ typeof (/** @type {any} */ (cause)?.code) === 'string'
66
+ ? /** @type {any} */ (cause).code
67
+ : null;
68
+ const why = errno === 'EACCES' || errno === 'EPERM' ? ' (no permission)' : '';
69
+ const outcome =
70
+ unrestored.length === 0
71
+ ? 'Nothing was written.'
72
+ : `Earlier writes could not all be undone: ${unrestored
73
+ .map(file => path.relative(cwd, file) || file)
74
+ .join(', ')}.`;
75
+ return new AstryxError(
76
+ `Could not write ${rel}${errno ? `: ${errno}` : ''}${why}. ${outcome}`,
77
+ undefined,
78
+ ERROR_CODES.ERR_WRITE_FAILED,
79
+ );
80
+ }
@@ -31,7 +31,7 @@ export function integrationAddAgentDoc(line: string, options?: import("./integra
31
31
  *
32
32
  * @param {'component'|'doc'|'template'|'codemod'|'agent-doc'|'theme'} kind
33
33
  * @param {string} name
34
- * @param {{cwd?: string, dryRun?: boolean, templateType?: 'page'|'block', to?: string, replaces?: string, extends?: string, parent?: string}} [options]
34
+ * @param {{cwd?: string, dryRun?: boolean, templateType?: 'page'|'block', to?: string, replaces?: string, extends?: string, parent?: string, from?: string}} [options]
35
35
  * @returns {Promise<import('./integration-authoring.type.mjs').IntegrationAddResponse>}
36
36
  */
37
37
  export function integrationAdd(kind: "component" | "doc" | "template" | "codemod" | "agent-doc" | "theme", name: string, options?: {
@@ -42,4 +42,5 @@ export function integrationAdd(kind: "component" | "doc" | "template" | "codemod
42
42
  replaces?: string;
43
43
  extends?: string;
44
44
  parent?: string;
45
+ from?: string;
45
46
  }): Promise<import("./integration-authoring.type.mjs").IntegrationAddResponse>;
@@ -1211,7 +1211,7 @@ const KIND_OPTIONS = {
1211
1211
  template: new Set(['cwd', 'dryRun', 'templateType']),
1212
1212
  codemod: new Set(['cwd', 'dryRun', 'to']),
1213
1213
  'agent-doc': new Set(['cwd', 'dryRun']),
1214
- theme: new Set(['cwd', 'dryRun']),
1214
+ theme: new Set(['cwd', 'dryRun', 'from']),
1215
1215
  };
1216
1216
 
1217
1217
  /**
@@ -1238,7 +1238,7 @@ function validateKindOptions(kind, options) {
1238
1238
  *
1239
1239
  * @param {'component'|'doc'|'template'|'codemod'|'agent-doc'|'theme'} kind
1240
1240
  * @param {string} name
1241
- * @param {{cwd?: string, dryRun?: boolean, templateType?: 'page'|'block', to?: string, replaces?: string, extends?: string, parent?: string}} [options]
1241
+ * @param {{cwd?: string, dryRun?: boolean, templateType?: 'page'|'block', to?: string, replaces?: string, extends?: string, parent?: string, from?: string}} [options]
1242
1242
  * @returns {Promise<import('./integration-authoring.type.mjs').IntegrationAddResponse>}
1243
1243
  */
1244
1244
  export async function integrationAdd(kind, name, options = {}) {
@@ -1270,6 +1270,10 @@ export async function integrationAdd(kind, name, options = {}) {
1270
1270
  case 'agent-doc':
1271
1271
  return integrationAddAgentDoc(name, options);
1272
1272
  case 'theme':
1273
- return integrationAddTheme(name, options);
1273
+ return integrationAddTheme(name, {
1274
+ cwd: options.cwd,
1275
+ dryRun: options.dryRun,
1276
+ from: options.from,
1277
+ });
1274
1278
  }
1275
1279
  }
@@ -4,6 +4,9 @@
4
4
  * @file `astryx integration add theme` — scaffold one strongly typed,
5
5
  * same-stem source/descriptor pair into an integration package and declare the
6
6
  * themes root on first use.
7
+ *
8
+ * `--from <base>` forks an existing theme's source files as the starting point
9
+ * instead of writing a blank `defineTheme` skeleton.
7
10
  */
8
11
 
9
12
  import * as fs from 'node:fs';
@@ -15,7 +18,10 @@ import {
15
18
  PathSafetyError,
16
19
  sanitizeName,
17
20
  } from '../../foundation/fs/path-safety.mjs';
18
- import {discoverThemeDirectory} from '../../foundation/discovery/theme-discovery.mjs';
21
+ import {
22
+ discoverBundledThemes,
23
+ discoverThemeDirectory,
24
+ } from '../../foundation/discovery/theme-discovery.mjs';
19
25
  import {
20
26
  findLocalIntegrationManifestOrNull,
21
27
  IntegrationRootConflictError,
@@ -29,6 +35,7 @@ import {
29
35
  themesCliProblem,
30
36
  withCliPeer,
31
37
  } from '../../foundation/integrations/cli-requirement.mjs';
38
+ import {stripCopyrightHeader} from '../../foundation/text/copyright-header.mjs';
32
39
  import {
33
40
  applyWrites,
34
41
  findPackageDir,
@@ -70,6 +77,7 @@ function themeIdentity(slug) {
70
77
  .join(' ');
71
78
  return {
72
79
  slug,
80
+ identifier,
73
81
  displayName,
74
82
  exportName: `${identifier}Theme`,
75
83
  entry: `${identifier}Theme.ts`,
@@ -93,6 +101,182 @@ function themeDescriptor(identity) {
93
101
  });
94
102
  }
95
103
 
104
+ // ── --from: resolve and fork a base theme ───────────────────────────
105
+
106
+ /**
107
+ * Resolve a theme slug to its discovered record, searching the bundled themes
108
+ * and the package's own themes root (when it has one).
109
+ * @param {string} slug
110
+ * @param {string} packageDir
111
+ * @param {string} owner
112
+ * @param {string | undefined} themesRoot resolved absolute themes root, if any
113
+ * @returns {import('../../foundation/discovery/theme-discovery.mjs').DiscoveredTheme}
114
+ */
115
+ function resolveBaseTheme(slug, packageDir, owner, themesRoot) {
116
+ const normalized = slug.toLowerCase();
117
+
118
+ /** @type {import('../../foundation/discovery/theme-discovery.mjs').DiscoveredTheme[]} */
119
+ let candidates = [];
120
+ try {
121
+ candidates = discoverBundledThemes();
122
+ } catch {
123
+ // Bundled themes unavailable — not fatal, package themes may suffice.
124
+ }
125
+
126
+ // Also check the package's own themes root.
127
+ if (themesRoot && fs.existsSync(themesRoot)) {
128
+ try {
129
+ candidates = [...candidates, ...discoverThemeDirectory(themesRoot, owner)];
130
+ } catch {
131
+ // A broken local root is not the caller's problem here.
132
+ }
133
+ }
134
+
135
+ const match = candidates.find(t => t.slug.toLowerCase() === normalized);
136
+ if (!match) {
137
+ throw new AstryxError(
138
+ `Unknown base theme "${slug}". Available themes: ${candidates.map(t => t.slug).join(', ') || '(none)'}.`,
139
+ candidates.map(t => ({
140
+ name: t.slug,
141
+ reason: t.bundled ? 'bundled theme' : `provided by ${t.package}`,
142
+ })),
143
+ ERROR_CODES.ERR_UNKNOWN_THEME,
144
+ );
145
+ }
146
+ return match;
147
+ }
148
+
149
+ /**
150
+ * Rename a file from the base theme's namespace to the new theme's namespace.
151
+ * Files whose name starts with the base identifier get the new identifier;
152
+ * others keep their name as-is.
153
+ * @param {string} file POSIX relative path inside the theme directory
154
+ * @param {string} baseIdentifier
155
+ * @param {string} newIdentifier
156
+ * @returns {string}
157
+ */
158
+ function renameThemeFile(file, baseIdentifier, newIdentifier) {
159
+ const basename = path.posix.basename(file);
160
+ const dir = path.posix.dirname(file);
161
+ if (!basename.startsWith(baseIdentifier)) return file;
162
+ const renamed = newIdentifier + basename.slice(baseIdentifier.length);
163
+ return dir === '.' ? renamed : `${dir}/${renamed}`;
164
+ }
165
+
166
+ /**
167
+ * Rewrite a source file's contents from the base theme's names to the new
168
+ * theme's names. This replaces:
169
+ * 1. Identifier prefixes (camelCase variables, import paths): baseIdentifier
170
+ * followed by an uppercase letter.
171
+ * 2. The theme slug in string literals: 'baseSlug' → 'newSlug' and
172
+ * 'astryx-baseSlug' → 'astryx-newSlug'.
173
+ * 3. CSS custom properties scoped to the theme: --astryx-theme-baseSlug-.
174
+ * @param {string} source
175
+ * @param {string} baseSlug
176
+ * @param {string} baseIdentifier
177
+ * @param {string} newSlug
178
+ * @param {string} newIdentifier
179
+ * @returns {string}
180
+ */
181
+ function rewriteThemeSource(
182
+ source,
183
+ baseSlug,
184
+ baseIdentifier,
185
+ newSlug,
186
+ newIdentifier,
187
+ ) {
188
+ let result = source;
189
+ // 1. Identifier prefixes: neutralPalettes → oceanPalettes, neutralTheme → oceanTheme
190
+ const identRe = new RegExp(`${escapeRegExp(baseIdentifier)}(?=[A-Z])`, 'gu');
191
+ result = result.replace(identRe, newIdentifier);
192
+ // 2. String-literal theme names
193
+ result = result.replace(
194
+ new RegExp(`'astryx-${escapeRegExp(baseSlug)}'`, 'gu'),
195
+ `'astryx-${newSlug}'`,
196
+ );
197
+ result = result.replace(
198
+ new RegExp(`'${escapeRegExp(baseSlug)}'`, 'gu'),
199
+ `'${newSlug}'`,
200
+ );
201
+ // 3. CSS custom properties scoped to the base theme
202
+ result = result.replace(
203
+ new RegExp(
204
+ `--astryx-theme-${escapeRegExp(baseSlug)}-`,
205
+ 'gu',
206
+ ),
207
+ `--astryx-theme-${newSlug}-`,
208
+ );
209
+ return result;
210
+ }
211
+
212
+ /** @param {string} s */
213
+ function escapeRegExp(s) {
214
+ return s.replace(/[.*+?^${}()|[\]\\]/gu, '\\$&');
215
+ }
216
+
217
+ /**
218
+ * Build the write plans for a forked theme.
219
+ * @param {import('../../foundation/discovery/theme-discovery.mjs').DiscoveredTheme} base
220
+ * @param {ReturnType<typeof themeIdentity>} identity new theme identity
221
+ * @param {string} themeDir absolute target directory
222
+ * @returns {import('./add-helpers.mjs').WritePlan[]}
223
+ */
224
+ function forkThemePlans(base, identity, themeDir) {
225
+ const baseIdentity = themeIdentity(base.slug);
226
+ /** @type {import('./add-helpers.mjs').WritePlan[]} */
227
+ const plans = [];
228
+
229
+ // Copy every file the base theme ships (entry first, then the rest), except
230
+ // the descriptor — we write a fresh one.
231
+ const filesToCopy = base.files.filter(
232
+ file => path.posix.basename(file) !== `${baseIdentity.exportName}.doc.mjs`,
233
+ );
234
+
235
+ for (const file of filesToCopy) {
236
+ const srcPath = path.join(base.sourceDir, file);
237
+ const newFileName = renameThemeFile(
238
+ file,
239
+ baseIdentity.identifier,
240
+ identity.identifier,
241
+ );
242
+ const destPath = assertWithin(newFileName, themeDir, {
243
+ label: `forked theme file "${newFileName}"`,
244
+ });
245
+
246
+ // Read source bytes; for text, strip copyright and rewrite identifiers.
247
+ const bytes = fs.readFileSync(srcPath);
248
+ const text = bytes.toString('utf-8');
249
+ const isText = Buffer.from(text, 'utf-8').equals(bytes);
250
+
251
+ /** @type {string | Buffer} */
252
+ let contents;
253
+ if (isText) {
254
+ contents = rewriteThemeSource(
255
+ stripCopyrightHeader(text),
256
+ base.slug,
257
+ baseIdentity.identifier,
258
+ identity.slug,
259
+ identity.identifier,
260
+ );
261
+ } else {
262
+ contents = bytes;
263
+ }
264
+ plans.push({path: destPath, contents, createOnly: true});
265
+ }
266
+
267
+ // Write a fresh descriptor — the fork is a new theme, not a derivative.
268
+ const descriptorPath = assertWithin(identity.descriptor, themeDir, {
269
+ label: 'theme descriptor file',
270
+ });
271
+ plans.push({
272
+ path: descriptorPath,
273
+ contents: themeDescriptor(identity),
274
+ createOnly: true,
275
+ });
276
+
277
+ return plans;
278
+ }
279
+
96
280
  /**
97
281
  * Read bytes back through the same discovery seam Project uses. A write is not
98
282
  * successful until the requested slug resolves.
@@ -130,7 +314,7 @@ async function verifyThemeContribution(packageDir, manifestFile, owner, slug) {
130
314
  * @returns {Promise<import('./integration-authoring.type.mjs').IntegrationAddResponse>}
131
315
  */
132
316
  export async function integrationAddTheme(name, options = {}) {
133
- const {cwd = process.cwd(), dryRun = false} = options;
317
+ const {cwd = process.cwd(), dryRun = false, from} = options;
134
318
  const packageDir = findPackageDir(cwd);
135
319
  const packageFile = path.join(packageDir, 'package.json');
136
320
  let pkg;
@@ -212,32 +396,64 @@ export async function integrationAddTheme(name, options = {}) {
212
396
  const themeDir = assertWithin(identity.slug, root, {
213
397
  label: 'theme directory',
214
398
  });
215
- const sourceFile = assertWithin(identity.entry, themeDir, {
216
- label: 'theme source file',
217
- });
218
- const descriptorFile = assertWithin(identity.descriptor, themeDir, {
219
- label: 'theme descriptor file',
220
- });
221
- // An existing folder is filled; only a file this would write is refused.
222
- for (const file of [sourceFile, descriptorFile]) {
223
- if (fs.existsSync(file)) {
399
+
400
+ // Resolve the base theme when --from is given, before writing anything.
401
+ /** @type {import('../../foundation/discovery/theme-discovery.mjs').DiscoveredTheme | undefined} */
402
+ let baseTheme;
403
+ if (from != null) {
404
+ if (from === name) {
224
405
  throw new AstryxError(
225
- `Refusing to overwrite existing file ${projectPath(path.relative(packageDir, file))}.`,
406
+ `Cannot fork theme "${from}" into itself.`,
226
407
  undefined,
227
- ERROR_CODES.ERR_FILE_EXISTS,
408
+ ERROR_CODES.ERR_INVALID_ARGUMENT,
228
409
  );
229
410
  }
411
+ baseTheme = resolveBaseTheme(from, packageDir, owner, root);
230
412
  }
231
413
 
232
414
  /** @type {import('./add-helpers.mjs').WritePlan[]} */
233
- const plans = [
234
- {path: sourceFile, contents: themeSource(identity), createOnly: true},
235
- {
236
- path: descriptorFile,
237
- contents: themeDescriptor(identity),
238
- createOnly: true,
239
- },
240
- ];
415
+ let plans;
416
+
417
+ if (baseTheme) {
418
+ // Fork: copy the base theme's files, renamed and rewritten.
419
+ plans = forkThemePlans(baseTheme, identity, themeDir);
420
+ // Check that no target file already exists.
421
+ for (const plan of plans) {
422
+ if (fs.existsSync(plan.path)) {
423
+ throw new AstryxError(
424
+ `Refusing to overwrite existing file ${projectPath(path.relative(packageDir, plan.path))}.`,
425
+ undefined,
426
+ ERROR_CODES.ERR_FILE_EXISTS,
427
+ );
428
+ }
429
+ }
430
+ } else {
431
+ // Blank scaffold.
432
+ const sourceFile = assertWithin(identity.entry, themeDir, {
433
+ label: 'theme source file',
434
+ });
435
+ const descriptorFile = assertWithin(identity.descriptor, themeDir, {
436
+ label: 'theme descriptor file',
437
+ });
438
+ for (const file of [sourceFile, descriptorFile]) {
439
+ if (fs.existsSync(file)) {
440
+ throw new AstryxError(
441
+ `Refusing to overwrite existing file ${projectPath(path.relative(packageDir, file))}.`,
442
+ undefined,
443
+ ERROR_CODES.ERR_FILE_EXISTS,
444
+ );
445
+ }
446
+ }
447
+ plans = [
448
+ {path: sourceFile, contents: themeSource(identity), createOnly: true},
449
+ {
450
+ path: descriptorFile,
451
+ contents: themeDescriptor(identity),
452
+ createOnly: true,
453
+ },
454
+ ];
455
+ }
456
+
241
457
  let packageUpdate = packageJsonUpdate(
242
458
  packageFile,
243
459
  rootPath,
@@ -309,7 +525,8 @@ export async function integrationAddTheme(name, options = {}) {
309
525
  writtenFiles.push(manifestPath);
310
526
  }
311
527
 
312
- return {
528
+ /** @type {import('./integration-authoring.type.mjs').IntegrationAddResponse} */
529
+ const response = {
313
530
  type: 'integration.add',
314
531
  data: {
315
532
  kind: 'theme',
@@ -321,4 +538,8 @@ export async function integrationAddTheme(name, options = {}) {
321
538
  dryRun,
322
539
  },
323
540
  };
541
+ if (from != null) {
542
+ response.data.from = from;
543
+ }
544
+ return response;
324
545
  }