@astryxdesign/cli 0.6.3-canary.f839b67 → 0.6.4-canary.06c8fa3

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 (189) hide show
  1. package/CHANGELOG.md +194 -0
  2. package/README.md +64 -66
  3. package/api/component/_adapter.d.mts +25 -0
  4. package/api/component/_adapter.mjs +59 -5
  5. package/api/component/component.d.mts +6 -3
  6. package/api/component/component.doc.mjs +23 -10
  7. package/api/component/component.mjs +249 -9
  8. package/api/component/component.type.d.mts +25 -0
  9. package/api/component/component.type.mjs +44 -0
  10. package/api/discover/_adapter.d.mts +114 -6
  11. package/api/discover/_adapter.mjs +372 -17
  12. package/api/discover/_adapter.test.mjs +215 -0
  13. package/api/discover/_catalog-view.d.mts +115 -0
  14. package/api/discover/_catalog-view.mjs +203 -0
  15. package/api/discover/_catalog-view.test.mjs +128 -0
  16. package/api/discover/detail/detail.d.mts +18 -6
  17. package/api/discover/detail/detail.mjs +67 -13
  18. package/api/discover/detail/detail.test.mjs +85 -0
  19. package/api/discover/detail/item/item.d.mts +26 -0
  20. package/api/discover/detail/item/item.mjs +78 -0
  21. package/api/discover/detail/item/item.test.mjs +73 -0
  22. package/api/discover/discover.d.mts +3 -9
  23. package/api/discover/discover.doc.mjs +61 -18
  24. package/api/discover/discover.mjs +220 -36
  25. package/api/discover/discover.test.mjs +11 -2
  26. package/api/discover/discover.type.d.mts +147 -8
  27. package/api/discover/discover.type.mjs +102 -12
  28. package/api/discover/list/list.d.mts +20 -6
  29. package/api/discover/list/list.mjs +45 -12
  30. package/api/discover/list/list.test.mjs +46 -0
  31. package/api/discover/search/search.d.mts +18 -16
  32. package/api/discover/search/search.mjs +102 -56
  33. package/api/discover/search/search.test.mjs +144 -10
  34. package/api/docs/_adapter.d.mts +49 -7
  35. package/api/docs/_adapter.mjs +284 -33
  36. package/api/docs/docs.doc.mjs +4 -3
  37. package/api/docs/docs.test.mjs +2 -0
  38. package/api/docs/docs.type.d.mts +21 -5
  39. package/api/docs/docs.type.mjs +21 -5
  40. package/api/docs/integration-tree.test.mjs +9 -1
  41. package/api/docs/reference-blocks.test.mjs +406 -0
  42. package/api/doctor/doctor.d.mts +8 -3
  43. package/api/doctor/doctor.mjs +95 -10
  44. package/api/doctor/doctor.test.mjs +122 -10
  45. package/api/index.d.mts +1 -2
  46. package/api/index.mjs +4 -4
  47. package/api/integration/add-helpers.d.mts +5 -2
  48. package/api/integration/add-helpers.mjs +36 -9
  49. package/api/integration/authoring-checks.mjs +14 -1
  50. package/api/integration/pack-check.lifecycle-output.test.mjs +105 -0
  51. package/api/integration/pack-check.mjs +28 -3
  52. package/api/json/index.ts +0 -1
  53. package/api/search/search.test.mjs +18 -0
  54. package/api/template/table-floating-bulk-actions.test.mjs +66 -0
  55. package/api/template/template-integration.test.mjs +1 -65
  56. package/api/template/template.mjs +1 -1
  57. package/api/theme/add/add.mjs +17 -25
  58. package/api/theme/add/add.rollback.test.mjs +158 -0
  59. package/api/theme/add/add.staging.test.mjs +40 -23
  60. package/api/theme/build/build.family.test.mjs +7 -12
  61. package/api/theme/build/build.mjs +8 -18
  62. package/api/theme/build/build.rollback.test.mjs +148 -0
  63. package/api/upgrade/run/files-changed.test.mjs +111 -0
  64. package/api/upgrade/run/run.mjs +6 -4
  65. package/api/upgrade/upgrade.type.mjs +2 -2
  66. package/assets/codemods/__tests__/registry.test.mjs +1 -0
  67. package/assets/codemods/__tests__/runner.test.mjs +3 -1
  68. package/assets/codemods/file-count.test.mjs +163 -0
  69. package/assets/codemods/integration-runner.mjs +3 -3
  70. package/assets/codemods/registry.mjs +1 -0
  71. package/assets/codemods/runner.mjs +5 -4
  72. package/assets/codemods/transforms/next/index.mjs +1 -19
  73. package/assets/codemods/transforms/v0.6.4/index.mjs +31 -0
  74. package/assets/docs/internationalization.doc.mjs +7 -5
  75. package/assets/docs/styling-libraries.doc.mjs +1 -1
  76. package/assets/docs/theme.doc.mjs +1 -1
  77. package/assets/docs/tree/component-lookups.doc.mjs +149 -0
  78. package/assets/docs/tree/integrations.doc.mjs +20 -1
  79. package/assets/templates/blocks/components/CheckboxList/CheckboxListSelectAllPattern.doc.mjs +1 -1
  80. package/assets/templates/blocks/components/CheckboxList/CheckboxListSelectAllPattern.tsx +1 -3
  81. package/assets/templates/blocks/components/InternationalizationProvider/InternationalizationProvider01ShippedLocale.tsx +1 -1
  82. package/assets/templates/blocks/components/Table/TableBulkActionsTable.doc.mjs +14 -0
  83. package/assets/templates/blocks/components/Table/TableBulkActionsTable.tsx +71 -0
  84. package/assets/templates/blocks/components/Table/TableFloatingBulkActionsTable.doc.mjs +19 -0
  85. package/assets/templates/blocks/components/Table/TableFloatingBulkActionsTable.tsx +139 -0
  86. package/authoring/config/config.doc.mjs +9 -1
  87. package/authoring/config/parse.d.mts +2 -0
  88. package/authoring/config/parse.mjs +19 -0
  89. package/authoring/config/parse.test.mjs +8 -0
  90. package/authoring/config/type.ts +13 -2
  91. package/authoring/discover/discover.doc.d.mts +13 -0
  92. package/authoring/discover/discover.doc.mjs +138 -0
  93. package/authoring/discover/parse.d.mts +24 -0
  94. package/authoring/discover/parse.mjs +128 -0
  95. package/authoring/discover/parse.test.mjs +124 -0
  96. package/authoring/discover/type.ts +87 -0
  97. package/authoring/doctypes/_schema.d.mts +72 -0
  98. package/authoring/doctypes/_schema.mjs +25 -1
  99. package/authoring/doctypes/command/command.doc.mjs +1 -1
  100. package/authoring/doctypes/command/type.ts +1 -1
  101. package/authoring/doctypes/load-contract.test.mjs +25 -0
  102. package/authoring/doctypes/reference/reference.doc.mjs +31 -4
  103. package/authoring/doctypes/reference/type.ts +20 -5
  104. package/authoring/index.d.mts +1 -0
  105. package/authoring/index.d.ts +10 -0
  106. package/authoring/index.mjs +1 -0
  107. package/clients/cli/command-result-coverage.test.mjs +7 -7
  108. package/clients/cli/commands/component/index.mjs +152 -55
  109. package/clients/cli/commands/component-batch.test.mjs +341 -0
  110. package/clients/cli/commands/component-ownership.test.mjs +89 -0
  111. package/clients/cli/commands/component.doc.mjs +23 -6
  112. package/clients/cli/commands/debug-result-summary.test.mjs +2 -2
  113. package/clients/cli/commands/discover.doc.mjs +53 -9
  114. package/clients/cli/commands/discover.mjs +393 -118
  115. package/clients/cli/commands/discover.sources.test.mjs +267 -0
  116. package/clients/cli/commands/docs.mjs +2 -2
  117. package/clients/cli/commands/docs.test.mjs +29 -0
  118. package/clients/cli/commands/doctor-integration-docs.doc.mjs +1 -1
  119. package/clients/cli/commands/text-json-parity.test.mjs +0 -17
  120. package/clients/cli/index.mjs +0 -4
  121. package/clients/cli/lib/exit-codes.test.mjs +1 -8
  122. package/clients/cli/lib/json-shim.mjs +24 -14
  123. package/clients/cli/lib/json-shim.test.mjs +6 -20
  124. package/clients/cli/lib/manifest.mjs +3 -8
  125. package/clients/cli/lib/manifest.test.mjs +5 -2
  126. package/clients/cli/lib/parse-error-format.test.mjs +81 -0
  127. package/foundation/discovery/authoring-self-docs.d.mts +12 -0
  128. package/foundation/discovery/authoring-self-docs.mjs +21 -8
  129. package/foundation/discovery/authoring-self-docs.test.mjs +7 -2
  130. package/foundation/discovery/docs-discovery.d.mts +4 -1
  131. package/foundation/discovery/docs-discovery.mjs +40 -6
  132. package/foundation/discovery/docs-discovery.test.mjs +40 -0
  133. package/foundation/discovery/template-adapter.mjs +1 -1
  134. package/foundation/doc-compiler/doc-loads.test.mjs +0 -12
  135. package/foundation/doc-compiler/lenses.d.mts +5 -3
  136. package/foundation/doc-compiler/lenses.mjs +48 -3
  137. package/foundation/doc-compiler/links.d.mts +30 -3
  138. package/foundation/doc-compiler/links.mjs +46 -5
  139. package/foundation/doc-compiler/links.test.mjs +53 -0
  140. package/foundation/doc-compiler/tree.test.mjs +9 -1
  141. package/foundation/integrations/cli-requirement.test.mjs +17 -42
  142. package/foundation/integrations/integrations.d.mts +14 -1
  143. package/foundation/integrations/integrations.mjs +41 -1
  144. package/foundation/integrations/integrations.test.mjs +31 -0
  145. package/foundation/response/batch.type.d.mts +33 -0
  146. package/foundation/response/batch.type.mjs +34 -0
  147. package/foundation/response/response-types.doc.mjs +15 -21
  148. package/foundation/response/response-types.doc.test.mjs +23 -0
  149. package/foundation/xle/browser.d.mts +3 -3
  150. package/foundation/xle/browser.mjs +3 -3
  151. package/foundation/xle/expand.mjs +2 -2
  152. package/foundation/xle/parse.mjs +1 -1
  153. package/foundation/xle/print.mjs +2 -2
  154. package/foundation/xle/splice.mjs +1 -1
  155. package/package.json +9 -9
  156. package/api/layout/_adapter.d.mts +0 -34
  157. package/api/layout/_adapter.mjs +0 -148
  158. package/api/layout/check/check.d.mts +0 -16
  159. package/api/layout/check/check.mjs +0 -40
  160. package/api/layout/expand/expand.d.mts +0 -22
  161. package/api/layout/expand/expand.mjs +0 -155
  162. package/api/layout/expand/expand.path-safety.test.mjs +0 -53
  163. package/api/layout/grammar/grammar.d.mts +0 -13
  164. package/api/layout/grammar/grammar.mjs +0 -87
  165. package/api/layout/layout.d.mts +0 -6
  166. package/api/layout/layout.mjs +0 -17
  167. package/api/layout/layout.test.mjs +0 -297
  168. package/api/layout/layout.type.d.mts +0 -89
  169. package/api/layout/layout.type.mjs +0 -103
  170. package/api/layout/layoutCheck.doc.d.mts +0 -11
  171. package/api/layout/layoutCheck.doc.mjs +0 -85
  172. package/api/layout/layoutExpand.doc.d.mts +0 -11
  173. package/api/layout/layoutExpand.doc.mjs +0 -107
  174. package/api/layout/layoutGrammar.doc.d.mts +0 -11
  175. package/api/layout/layoutGrammar.doc.mjs +0 -57
  176. package/clients/cli/commands/layout-check.doc.mjs +0 -65
  177. package/clients/cli/commands/layout-expand.doc.mjs +0 -83
  178. package/clients/cli/commands/layout-grammar.doc.mjs +0 -30
  179. package/clients/cli/commands/layout.doc.mjs +0 -34
  180. package/clients/cli/commands/layout.error-codes.test.mjs +0 -66
  181. package/clients/cli/commands/layout.exit-parity.test.mjs +0 -41
  182. package/clients/cli/commands/layout.mjs +0 -275
  183. package/clients/cli/commands/layout.path-help.test.mjs +0 -33
  184. package/clients/cli/commands/layout.stdin-cap.test.mjs +0 -47
  185. package/clients/cli/commands/layout.text-fields.test.mjs +0 -39
  186. /package/assets/codemods/transforms/{next → v0.6.4}/__tests__/migrate-native-picker-to-presentation.test.mjs +0 -0
  187. /package/assets/codemods/transforms/{next → v0.6.4}/__tests__/migrate-theme-catalog-to-descriptors.test.mjs +0 -0
  188. /package/assets/codemods/transforms/{next → v0.6.4}/migrate-native-picker-to-presentation.mjs +0 -0
  189. /package/assets/codemods/transforms/{next → v0.6.4}/migrate-theme-catalog-to-descriptors.mjs +0 -0
@@ -19,7 +19,6 @@ import {
19
19
  } from './template.mjs';
20
20
  import {search} from '../search/search.mjs';
21
21
  import {build} from '../build/build.mjs';
22
- import {layoutExpand} from '../layout/layout.mjs';
23
22
  import {runCli} from '../../test-utils/run-cli.mjs';
24
23
 
25
24
  let tmpDir;
@@ -518,53 +517,7 @@ describe('integration template discovery', () => {
518
517
  });
519
518
  });
520
519
 
521
- it('resolves a replacement block through the layout alias', async () => {
522
- const pkgDir = installWidgets(tmpDir);
523
- writeTemplate(pkgDir, 'acme-card-callout', {
524
- kind: 'block',
525
- source:
526
- 'export default function AcmeCardCallout() { return <span>Acme replacement block</span>; }\n',
527
- });
528
- declareReplaces(pkgDir, {
529
- 'acme-card-callout': 'CardCallout',
530
- });
531
-
532
- const accidental = path.join(tmpDir, 'node_modules', '@acme', 'extra');
533
- fs.mkdirSync(path.join(accidental, 'templates'), {recursive: true});
534
- fs.writeFileSync(
535
- path.join(accidental, 'package.json'),
536
- JSON.stringify({name: '@acme/extra', version: '1.0.0'}),
537
- );
538
- fs.writeFileSync(
539
- path.join(accidental, 'astryx.integration.mjs'),
540
- `export default {templates: './templates'};\n`,
541
- );
542
- writeTemplate(accidental, 'CardCallout', {
543
- kind: 'block',
544
- body: `export default {type: 'block', name: 'ZZZ accidental block', description: 'collision'};\n`,
545
- source:
546
- 'export default function Accidental() { return <span>Accidental block</span>; }\n',
547
- });
548
- fs.writeFileSync(
549
- path.join(tmpDir, 'astryx.config.mjs'),
550
- `export default { integrations: ['@acme/widgets', '@acme/extra'] };\n`,
551
- );
552
-
553
- const result = await layoutExpand('C{card-callout}', {
554
- name: 'ReplacementLayout',
555
- cwd: tmpDir,
556
- });
557
-
558
- expect(result.data.code).toContain('Acme replacement block');
559
- expect(result.data.code).not.toContain('Accidental block');
560
- expect(result.data.blocksReferenced).toEqual(
561
- expect.arrayContaining([
562
- expect.objectContaining({name: 'CardCallout', mode: 'splice'}),
563
- ]),
564
- );
565
- }, 30_000);
566
-
567
- it('resolves chained block aliases consistently in template and layout', async () => {
520
+ it('resolves chained block aliases consistently in template', async () => {
568
521
  const [firstTarget, secondTarget] = (await discoverCoreTemplates()).filter(
569
522
  candidate => candidate.type === 'block',
570
523
  );
@@ -592,29 +545,12 @@ describe('integration template discovery', () => {
592
545
  cwd: tmpDir,
593
546
  });
594
547
  expect(firstTemplate.data.source).toContain('First chain replacement');
595
- const layoutId = id =>
596
- id.replace(/([a-z0-9])([A-Z])/gu, '$1-$2').toLowerCase();
597
- const firstLayout = await layoutExpand(
598
- `C{${layoutId(firstTarget.dirName)}}`,
599
- {
600
- cwd: tmpDir,
601
- },
602
- );
603
- expect(firstLayout.data.code).toContain('First chain replacement');
604
- expect(firstLayout.data.code).not.toContain('Final chain replacement');
605
548
 
606
549
  const secondTemplate = await template(secondTarget.dirName, {
607
550
  show: true,
608
551
  cwd: tmpDir,
609
552
  });
610
553
  expect(secondTemplate.data.source).toContain('Final chain replacement');
611
- const secondLayout = await layoutExpand(
612
- `C{${layoutId(secondTarget.dirName)}}`,
613
- {
614
- cwd: tmpDir,
615
- },
616
- );
617
- expect(secondLayout.data.code).toContain('Final chain replacement');
618
554
  }, 30_000);
619
555
 
620
556
  it('keeps the old discovery behavior when no replacement is declared', async () => {
@@ -8,7 +8,7 @@
8
8
  * the requested one, and routes to a leaf (list/show/skeleton/copy/cdn). The shared
9
9
  * discovery/IO + cross-command helpers live in `foundation/discovery/template-adapter.mjs` and are
10
10
  * RE-EXPORTED here so external import paths (`api/template/template.mjs`) —
11
- * used by component, layout, search, init, discover, Doctor integration, and
11
+ * used by component, search, init, discover, Doctor integration, and
12
12
  * lib/project — keep resolving unchanged.
13
13
  *
14
14
  * @position api/template — the template dispatcher + barrel; leaves live under
@@ -15,6 +15,7 @@ import {
15
15
  import {AstryxError} from '../../error.mjs';
16
16
  import {ERROR_CODES} from '../../../foundation/response/error-codes.mjs';
17
17
  import {listAvailableThemes, findTheme} from '../_adapter.mjs';
18
+ import {applyWrites} from '../../integration/add-helpers.mjs';
18
19
  // Scaffolded files must not carry our repo boilerplate into a consumer's tree.
19
20
  import {stripCopyrightHeader} from '../../../foundation/text/copyright-header.mjs';
20
21
 
@@ -136,37 +137,28 @@ export async function themeAdd(slug, options = {}) {
136
137
  }
137
138
  }
138
139
 
139
- // Stage to temp files then rename, rolling back partials on failure so a
140
- // failed write never leaves a half-written theme. mkdir is inside the try so
141
- // a failure (e.g. an ancestor is a file → EEXIST/ENOTDIR) surfaces as a
142
- // stable ERR_WRITE_FAILED rather than leaking a raw fs errno + absolute path.
143
- const staged = [];
140
+ // One transaction: every file publishes, or every replaced file gets its
141
+ // previous bytes back and every created file is removed. mkdir is inside the
142
+ // try so a failure (e.g. an ancestor is a file → EEXIST/ENOTDIR) surfaces as
143
+ // a stable ERR_WRITE_FAILED rather than leaking a raw fs errno + absolute path.
144
144
  try {
145
145
  fs.mkdirSync(resolvedDir, {recursive: true});
146
- for (const w of writes) {
146
+ const plans = writes.map(w => {
147
+ fs.mkdirSync(path.dirname(w.dest), {recursive: true});
148
+ // Confine again once the directories exist: one may have been swapped
149
+ // for a link since the destination was first checked.
147
150
  const dest = assertWithin(w.name, resolvedDir, {
148
151
  label: `theme destination for ${w.name}`,
149
152
  });
150
- fs.mkdirSync(path.dirname(dest), {recursive: true});
151
- // The staging file is an output path too: confine it, and never write
152
- // through an entry that already exists under its name.
153
- const tmp = assertWithin(`${w.name}.${process.pid}.tmp`, resolvedDir, {
154
- label: `theme staging file for ${w.name}`,
155
- });
156
- fs.writeFileSync(tmp, scaffoldContents(fs.readFileSync(w.src)), {flag: 'wx'});
157
- staged.push({tmp, dest});
158
- }
159
- for (const s of staged) {
160
- fs.renameSync(s.tmp, s.dest);
161
- }
153
+ return {
154
+ path: dest,
155
+ contents: scaffoldContents(fs.readFileSync(w.src)),
156
+ createOnly: !overwrite,
157
+ };
158
+ });
159
+ applyWrites(plans);
162
160
  } catch (err) {
163
- for (const s of staged) {
164
- try {
165
- fs.rmSync(s.tmp, {force: true});
166
- } catch {
167
- /* best-effort */
168
- }
169
- }
161
+ if (err instanceof AstryxError) throw err;
170
162
  if (err instanceof PathSafetyError) {
171
163
  throw new AstryxError(
172
164
  err.message,
@@ -0,0 +1,158 @@
1
+ // Copyright (c) Meta Platforms, Inc. and affiliates.
2
+
3
+ /**
4
+ * `theme add` writes a theme as one transaction: when a later file fails to
5
+ * publish, every file it already replaced gets its previous bytes back and
6
+ * every file it created is removed. Publishing is forced to fail by wrapping
7
+ * the two calls that publish a staged file: `linkSync` for a new file and
8
+ * `renameSync` for a replacement.
9
+ *
10
+ * Separate file because vi.mock is hoisted and affects the whole module.
11
+ */
12
+
13
+ import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
14
+ import * as os from 'node:os';
15
+ import * as path from 'node:path';
16
+
17
+ const failures = vi.hoisted(() => ({
18
+ /** Fail the Nth staged-file publish (1-based); 0 disables. */
19
+ publish: 0,
20
+ /** Also fail every rollback restore. */
21
+ restore: false,
22
+ count: 0,
23
+ }));
24
+
25
+ vi.mock('node:fs', async importOriginal => {
26
+ const actual = /** @type {typeof import('node:fs')} */ (
27
+ await importOriginal()
28
+ );
29
+ /** @param {string} source */
30
+ const isStaged = source => path.basename(String(source)).includes('.tmp');
31
+ /** @param {string} source */
32
+ const isRestore = source =>
33
+ path.basename(String(source)).includes('.restore-');
34
+ /** @param {string} source @param {string} op */
35
+ const maybeFail = (source, op) => {
36
+ if (isStaged(source) && failures.publish > 0) {
37
+ failures.count++;
38
+ if (failures.count === failures.publish) {
39
+ throw Object.assign(new Error(`EIO: forced ${op} failure`), {
40
+ code: 'EIO',
41
+ });
42
+ }
43
+ }
44
+ if (isRestore(source) && failures.restore) {
45
+ throw Object.assign(new Error(`EIO: forced restore failure`), {
46
+ code: 'EIO',
47
+ });
48
+ }
49
+ };
50
+ return {
51
+ ...actual,
52
+ linkSync: vi.fn((source, destination) => {
53
+ maybeFail(source, 'link');
54
+ return actual.linkSync(source, destination);
55
+ }),
56
+ renameSync: vi.fn((source, destination) => {
57
+ maybeFail(source, 'rename');
58
+ return actual.renameSync(source, destination);
59
+ }),
60
+ };
61
+ });
62
+
63
+ const fs = await import('node:fs');
64
+ const {themeAdd} = await import('./add.mjs');
65
+ const {listThemes} = await import('../_adapter.mjs');
66
+
67
+ let tmpDir;
68
+
69
+ beforeEach(() => {
70
+ tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'astryx-themeadd-rollback-'));
71
+ failures.publish = 0;
72
+ failures.restore = false;
73
+ failures.count = 0;
74
+ });
75
+
76
+ afterEach(() => {
77
+ failures.publish = 0;
78
+ failures.restore = false;
79
+ fs.rmSync(tmpDir, {recursive: true, force: true});
80
+ });
81
+
82
+ function stoneFiles() {
83
+ const theme = listThemes().find(entry => entry.slug === 'stone');
84
+ if (!theme) throw new Error('missing bundled theme stone');
85
+ expect(theme.files.length).toBeGreaterThanOrEqual(2);
86
+ return theme.files.map(name =>
87
+ path.join(tmpDir, 'src', 'themes', 'stone', name),
88
+ );
89
+ }
90
+
91
+ /** Entries staging or rollback left behind in the theme directory. */
92
+ function strays() {
93
+ const dir = path.join(tmpDir, 'src', 'themes', 'stone');
94
+ if (!fs.existsSync(dir)) return [];
95
+ return fs
96
+ .readdirSync(dir, {recursive: true})
97
+ .map(String)
98
+ .filter(name => name.includes('.tmp') || name.includes('.restore-'));
99
+ }
100
+
101
+ describe('themeAdd rolls back a partial write', () => {
102
+ it('removes every created file when the second publish fails', async () => {
103
+ const files = stoneFiles();
104
+ failures.publish = 2;
105
+
106
+ await expect(themeAdd('stone', {cwd: tmpDir})).rejects.toMatchObject({
107
+ code: 'ERR_WRITE_FAILED',
108
+ });
109
+
110
+ for (const file of files) expect(fs.existsSync(file)).toBe(false);
111
+ expect(strays()).toEqual([]);
112
+ });
113
+
114
+ it('restores every replaced byte when the second publish fails', async () => {
115
+ const files = stoneFiles();
116
+ fs.mkdirSync(path.dirname(files[0]), {recursive: true});
117
+ const before = Buffer.from([0x00, 0xff, 0x0a, 0x62, 0x65, 0x66]);
118
+ fs.writeFileSync(files[0], before);
119
+ failures.publish = 2;
120
+
121
+ await expect(
122
+ themeAdd('stone', {cwd: tmpDir, overwrite: true}),
123
+ ).rejects.toMatchObject({code: 'ERR_WRITE_FAILED'});
124
+
125
+ expect(fs.readFileSync(files[0]).equals(before)).toBe(true);
126
+ for (const file of files.slice(1)) expect(fs.existsSync(file)).toBe(false);
127
+ expect(strays()).toEqual([]);
128
+ });
129
+
130
+ it('names a file it could not restore', async () => {
131
+ const files = stoneFiles();
132
+ fs.mkdirSync(path.dirname(files[0]), {recursive: true});
133
+ fs.writeFileSync(files[0], 'before\n');
134
+ failures.publish = 2;
135
+ failures.restore = true;
136
+
137
+ let error;
138
+ try {
139
+ await themeAdd('stone', {cwd: tmpDir, overwrite: true});
140
+ } catch (caught) {
141
+ error = caught;
142
+ }
143
+
144
+ expect(error?.code).toBe('ERR_WRITE_FAILED');
145
+ expect(error?.message).toContain('Could not restore');
146
+ expect(error?.message).toContain(files[0]);
147
+ });
148
+
149
+ it('writes every file when nothing fails', async () => {
150
+ const files = stoneFiles();
151
+
152
+ const result = await themeAdd('stone', {cwd: tmpDir});
153
+
154
+ expect(result.type).toBe('theme.add');
155
+ for (const file of files) expect(fs.existsSync(file)).toBe(true);
156
+ expect(strays()).toEqual([]);
157
+ });
158
+ });
@@ -6,14 +6,15 @@ import * as os from 'node:os';
6
6
  import * as path from 'node:path';
7
7
  import {themeAdd} from './add.mjs';
8
8
  import {listThemes} from '../_adapter.mjs';
9
- import {isErrorCode} from '../../../foundation/response/error-codes.mjs';
10
9
 
11
10
  let tmpDir;
12
11
  let outsideDir;
13
12
 
14
13
  beforeEach(() => {
15
14
  tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'astryx-themeadd-staging-'));
16
- outsideDir = fs.mkdtempSync(path.join(os.tmpdir(), 'astryx-themeadd-outside-'));
15
+ outsideDir = fs.mkdtempSync(
16
+ path.join(os.tmpdir(), 'astryx-themeadd-outside-'),
17
+ );
17
18
  });
18
19
 
19
20
  afterEach(() => {
@@ -22,45 +23,61 @@ afterEach(() => {
22
23
  });
23
24
 
24
25
  /**
25
- * Put a symlink where `theme add` stages the first file of `slug`.
26
+ * Where `theme add` writes the first file of `slug`.
26
27
  * @param {string} slug
27
- * @param {string} target
28
28
  */
29
- function plantStagingLink(slug, target) {
29
+ function firstDestination(slug) {
30
30
  const theme = listThemes().find(entry => entry.slug === slug);
31
31
  if (!theme) throw new Error(`missing bundled theme ${slug}`);
32
- const first = theme.files[0];
33
- const dest = path.join(tmpDir, 'src', 'themes', slug, first);
32
+ const dest = path.join(tmpDir, 'src', 'themes', slug, theme.files[0]);
34
33
  fs.mkdirSync(path.dirname(dest), {recursive: true});
35
- fs.symlinkSync(target, `${dest}.${process.pid}.tmp`);
36
34
  return dest;
37
35
  }
38
36
 
37
+ // Staging names are unpredictable and created exclusively, so an entry planted
38
+ // at a predictable name beside the destination is never written through.
39
39
  describe('themeAdd staging writes stay inside the project', () => {
40
- it('refuses a staging path that links outside the project', async () => {
40
+ it('never writes through a link planted at a predictable staging name', async () => {
41
41
  const victim = path.join(outsideDir, 'victim.txt');
42
42
  fs.writeFileSync(victim, 'outside\n');
43
- const dest = plantStagingLink('stone', victim);
43
+ const dest = firstDestination('stone');
44
+ fs.symlinkSync(victim, `${dest}.${process.pid}.tmp`);
45
+
46
+ await themeAdd('stone', {cwd: tmpDir});
44
47
 
45
- await expect(themeAdd('stone', {cwd: tmpDir})).rejects.toMatchObject({
46
- code: 'ERR_PATH_TRAVERSAL',
47
- });
48
48
  expect(fs.readFileSync(victim, 'utf-8')).toBe('outside\n');
49
- expect(fs.existsSync(dest)).toBe(false);
49
+ expect(fs.lstatSync(dest).isFile()).toBe(true);
50
50
  });
51
51
 
52
- it('never creates a file through a dangling staging link', async () => {
52
+ it('never creates a file through a dangling link at a predictable staging name', async () => {
53
53
  const victim = path.join(outsideDir, 'created.txt');
54
- plantStagingLink('stone', victim);
54
+ fs.symlinkSync(victim, `${firstDestination('stone')}.${process.pid}.tmp`);
55
+
56
+ await themeAdd('stone', {cwd: tmpDir});
57
+
58
+ expect(fs.existsSync(victim)).toBe(false);
59
+ });
60
+
61
+ it('refuses to replace a destination that links outside the project', async () => {
62
+ const victim = path.join(outsideDir, 'victim.txt');
63
+ fs.writeFileSync(victim, 'outside\n');
64
+ const dest = firstDestination('stone');
65
+ fs.symlinkSync(victim, dest);
55
66
 
56
- let error;
57
- try {
58
- await themeAdd('stone', {cwd: tmpDir});
59
- } catch (caught) {
60
- error = caught;
61
- }
67
+ await expect(
68
+ themeAdd('stone', {cwd: tmpDir, overwrite: true}),
69
+ ).rejects.toMatchObject({code: 'ERR_PATH_TRAVERSAL'});
70
+ expect(fs.readFileSync(victim, 'utf-8')).toBe('outside\n');
71
+ expect(fs.lstatSync(dest).isSymbolicLink()).toBe(true);
72
+ });
62
73
 
63
- expect(isErrorCode(error?.code)).toBe(true);
74
+ it('never creates a file through a dangling destination link', async () => {
75
+ const victim = path.join(outsideDir, 'created.txt');
76
+ fs.symlinkSync(victim, firstDestination('stone'));
77
+
78
+ await expect(themeAdd('stone', {cwd: tmpDir})).rejects.toMatchObject({
79
+ code: 'ERR_PATH_TRAVERSAL',
80
+ });
64
81
  expect(fs.existsSync(victim)).toBe(false);
65
82
  });
66
83
  });
@@ -251,23 +251,18 @@ describe('themeBuildFamily()', () => {
251
251
  const dir = makeDir();
252
252
  const files = writeFamily(dir);
253
253
  const outputDir = path.join(dir, 'themes');
254
- const blockedTmp = path.join(
255
- outputDir,
256
- `${FAMILY_KEY}.js.${process.pid}.tmp`,
257
- );
258
- fs.mkdirSync(blockedTmp);
254
+ // A directory where the JS output goes fails its staging after the CSS
255
+ // output was already staged.
256
+ fs.mkdirSync(path.join(outputDir, `${FAMILY_KEY}.js`));
259
257
 
260
258
  await expect(build(dir, files)).rejects.toThrow(
261
259
  /Failed to write theme outputs/,
262
260
  );
263
- for (const output of OUTPUTS) {
264
- expect(fs.existsSync(path.join(outputDir, output))).toBe(false);
265
- }
261
+ expect(fs.existsSync(path.join(outputDir, `${FAMILY_KEY}.css`))).toBe(false);
262
+ expect(fs.existsSync(path.join(outputDir, `${FAMILY_KEY}.d.ts`))).toBe(false);
266
263
  expect(
267
- fs.existsSync(
268
- path.join(outputDir, `${FAMILY_KEY}.css.${process.pid}.tmp`),
269
- ),
270
- ).toBe(false);
264
+ fs.readdirSync(outputDir).filter(name => name.includes('.tmp-')),
265
+ ).toEqual([]);
271
266
  });
272
267
 
273
268
  it('rejects invalid graphs and keys before touching an existing trio', async () => {
@@ -53,6 +53,7 @@ import {
53
53
  } from '../../../foundation/fs/path-safety.mjs';
54
54
  import {ERROR_CODES} from '../../../foundation/response/error-codes.mjs';
55
55
  import {AstryxError} from '../../error.mjs';
56
+ import {applyWrites} from '../../integration/add-helpers.mjs';
56
57
  import {logger} from '../../logger.mjs';
57
58
  import {loadComponentDoc} from '../../../foundation/discovery/component-loader.mjs';
58
59
  import {
@@ -224,26 +225,15 @@ function staleBuildOutputs(writes, cwd) {
224
225
  /** @param {Array<{dest: string, content: string}>} writes */
225
226
  function writeBuildOutputs(writes) {
226
227
  if (writes.length === 0) return;
227
- /** @type {Array<{tmp: string, dest: string}>} */
228
- const staged = [];
229
228
  try {
230
- fs.mkdirSync(path.dirname(writes[0].dest), {recursive: true});
231
- for (const write of writes) {
232
- const tmp = `${write.dest}.${process.pid}.tmp`;
233
- fs.writeFileSync(tmp, write.content);
234
- staged.push({tmp, dest: write.dest});
235
- }
236
- for (const stagedWrite of staged) {
237
- fs.renameSync(stagedWrite.tmp, stagedWrite.dest);
238
- }
229
+ applyWrites(
230
+ writes.map(write => ({
231
+ path: write.dest,
232
+ contents: write.content,
233
+ createOnly: false,
234
+ })),
235
+ );
239
236
  } catch (error) {
240
- for (const stagedWrite of staged) {
241
- try {
242
- fs.rmSync(stagedWrite.tmp, {force: true});
243
- } catch {
244
- // Best effort: the command still fails and never reports success.
245
- }
246
- }
247
237
  const message = `Failed to write theme outputs: ${/** @type {Error} */ (error).message}`;
248
238
  throw new AstryxError(message, undefined, ERROR_CODES.ERR_WRITE_FAILED);
249
239
  }
@@ -0,0 +1,148 @@
1
+ // Copyright (c) Meta Platforms, Inc. and affiliates.
2
+
3
+ /**
4
+ * `theme build` writes its CSS, JS, and declarations as one transaction: when
5
+ * a later output fails to publish, every output it already replaced gets its
6
+ * previous bytes back and every output it created is removed. Publishing is
7
+ * forced to fail by wrapping the two calls that publish a staged file:
8
+ * `linkSync` for a new file and `renameSync` for a replacement.
9
+ *
10
+ * Separate file because vi.mock is hoisted and affects the whole module.
11
+ * `themeBuild` needs a built core; the `node` project's globalSetup builds it.
12
+ */
13
+
14
+ import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
15
+ import * as os from 'node:os';
16
+ import * as path from 'node:path';
17
+
18
+ const failures = vi.hoisted(() => ({
19
+ /** Fail the Nth staged-file publish (1-based); 0 disables. */
20
+ publish: 0,
21
+ count: 0,
22
+ }));
23
+
24
+ vi.mock('node:fs', async importOriginal => {
25
+ const actual = /** @type {typeof import('node:fs')} */ (
26
+ await importOriginal()
27
+ );
28
+ /** @param {string} source @param {string} op */
29
+ const maybeFail = (source, op) => {
30
+ if (!path.basename(String(source)).includes('.tmp')) return;
31
+ if (failures.publish === 0) return;
32
+ failures.count++;
33
+ if (failures.count === failures.publish) {
34
+ throw Object.assign(new Error(`EIO: forced ${op} failure`), {
35
+ code: 'EIO',
36
+ });
37
+ }
38
+ };
39
+ return {
40
+ ...actual,
41
+ linkSync: vi.fn((source, destination) => {
42
+ maybeFail(source, 'link');
43
+ return actual.linkSync(source, destination);
44
+ }),
45
+ renameSync: vi.fn((source, destination) => {
46
+ maybeFail(source, 'rename');
47
+ return actual.renameSync(source, destination);
48
+ }),
49
+ };
50
+ });
51
+
52
+ const fs = await import('node:fs');
53
+ const {themeBuild} = await import('./build.mjs');
54
+
55
+ vi.setConfig({testTimeout: 30000});
56
+
57
+ let tmpDir;
58
+
59
+ beforeEach(() => {
60
+ tmpDir = fs.mkdtempSync(
61
+ path.join(os.tmpdir(), 'astryx-theme-build-rollback-'),
62
+ );
63
+ failures.publish = 0;
64
+ failures.count = 0;
65
+ });
66
+
67
+ afterEach(() => {
68
+ failures.publish = 0;
69
+ fs.rmSync(tmpDir, {recursive: true, force: true});
70
+ });
71
+
72
+ /**
73
+ * Write a source for the theme named `rollbacktheme`. Each call uses a new
74
+ * file so the loader cannot serve an earlier version from its cache.
75
+ * @param {string} file @param {string} background
76
+ */
77
+ function writeTheme(file, background) {
78
+ fs.writeFileSync(
79
+ path.join(tmpDir, file),
80
+ `export default { name: 'rollbacktheme', tokens: { '--color-bg': '${background}' } };\n`,
81
+ );
82
+ return file;
83
+ }
84
+
85
+ const OUTPUTS = ['rollbacktheme.css', 'rollbacktheme.js', 'rollbacktheme.d.ts'];
86
+
87
+ /** @returns {Map<string, Buffer | null>} */
88
+ function readOutputs() {
89
+ return new Map(
90
+ OUTPUTS.map(name => {
91
+ const file = path.join(tmpDir, name);
92
+ return [name, fs.existsSync(file) ? fs.readFileSync(file) : null];
93
+ }),
94
+ );
95
+ }
96
+
97
+ function strays() {
98
+ return fs
99
+ .readdirSync(tmpDir)
100
+ .filter(name => name.includes('.tmp') || name.includes('.restore-'));
101
+ }
102
+
103
+ describe('themeBuild rolls back a partial write', () => {
104
+ it('removes every created output when the second publish fails', async () => {
105
+ const source = writeTheme('first.mjs', '#0a0a0a');
106
+ failures.publish = 2;
107
+
108
+ await expect(themeBuild(source, {}, {cwd: tmpDir})).rejects.toMatchObject({
109
+ code: 'ERR_WRITE_FAILED',
110
+ });
111
+
112
+ for (const bytes of readOutputs().values()) expect(bytes).toBeNull();
113
+ expect(strays()).toEqual([]);
114
+ });
115
+
116
+ it('restores every replaced output when the second publish fails', async () => {
117
+ const first = await themeBuild(
118
+ writeTheme('first.mjs', '#0a0a0a'),
119
+ {},
120
+ {cwd: tmpDir},
121
+ );
122
+ expect(first?.type).toBe('theme.build');
123
+ const before = readOutputs();
124
+ for (const bytes of before.values()) expect(bytes).not.toBeNull();
125
+
126
+ const next = writeTheme('next.mjs', '#fafafa');
127
+ failures.publish = 2;
128
+ await expect(themeBuild(next, {}, {cwd: tmpDir})).rejects.toMatchObject({
129
+ code: 'ERR_WRITE_FAILED',
130
+ });
131
+
132
+ const after = readOutputs();
133
+ for (const name of OUTPUTS) {
134
+ expect(
135
+ after.get(name)?.equals(/** @type {Buffer} */ (before.get(name))),
136
+ ).toBe(true);
137
+ }
138
+
139
+ // The failed build really had different bytes to write.
140
+ failures.publish = 0;
141
+ await themeBuild(next, {}, {cwd: tmpDir});
142
+ const css = readOutputs().get('rollbacktheme.css');
143
+ expect(
144
+ css?.equals(/** @type {Buffer} */ (before.get('rollbacktheme.css'))),
145
+ ).toBe(false);
146
+ expect(strays()).toEqual([]);
147
+ });
148
+ });