@smoothbricks/nx-plugin 0.4.14 → 0.4.16

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 (119) hide show
  1. package/README.md +20 -3
  2. package/dist/deploy-policy.d.ts +26 -0
  3. package/dist/deploy-policy.d.ts.map +1 -0
  4. package/dist/deploy-policy.js +36 -0
  5. package/dist/index.d.ts.map +1 -1
  6. package/dist/index.js +160 -37
  7. package/dist/managed-assets.d.ts +3 -0
  8. package/dist/managed-assets.d.ts.map +1 -0
  9. package/dist/managed-assets.js +3 -0
  10. package/dist/managed-files/ci-workflow.d.ts +215 -0
  11. package/dist/managed-files/ci-workflow.d.ts.map +1 -0
  12. package/dist/managed-files/ci-workflow.js +1082 -0
  13. package/dist/managed-files/context.d.ts +51 -0
  14. package/dist/managed-files/context.d.ts.map +1 -0
  15. package/dist/managed-files/context.js +206 -0
  16. package/dist/managed-files/files.d.ts +53 -0
  17. package/dist/managed-files/files.d.ts.map +1 -0
  18. package/dist/managed-files/files.js +248 -0
  19. package/dist/managed-files/generator.d.ts +16 -0
  20. package/dist/managed-files/generator.d.ts.map +1 -0
  21. package/dist/managed-files/generator.js +41 -0
  22. package/dist/managed-files/github-runs-on.d.ts +19 -0
  23. package/dist/managed-files/github-runs-on.d.ts.map +1 -0
  24. package/dist/managed-files/github-runs-on.js +48 -0
  25. package/dist/managed-files/managed-content.d.ts +45 -0
  26. package/dist/managed-files/managed-content.d.ts.map +1 -0
  27. package/dist/managed-files/managed-content.js +102 -0
  28. package/dist/managed-files/managed-format.d.ts +37 -0
  29. package/dist/managed-files/managed-format.d.ts.map +1 -0
  30. package/dist/managed-files/managed-format.js +94 -0
  31. package/dist/managed-files/paths.d.ts +8 -0
  32. package/dist/managed-files/paths.d.ts.map +1 -0
  33. package/dist/managed-files/paths.js +46 -0
  34. package/dist/managed-files/pr-preview-cleanup-workflow.d.ts +5 -0
  35. package/dist/managed-files/pr-preview-cleanup-workflow.d.ts.map +1 -0
  36. package/dist/managed-files/pr-preview-cleanup-workflow.js +38 -0
  37. package/dist/managed-files/private-npm-policy.d.ts +7 -0
  38. package/dist/managed-files/private-npm-policy.d.ts.map +1 -0
  39. package/dist/managed-files/private-npm-policy.js +51 -0
  40. package/dist/managed-files/publish-workflow.d.ts +150 -0
  41. package/dist/managed-files/publish-workflow.d.ts.map +1 -0
  42. package/dist/managed-files/publish-workflow.js +989 -0
  43. package/dist/managed-files/tree.d.ts +30 -0
  44. package/dist/managed-files/tree.d.ts.map +1 -0
  45. package/dist/managed-files/tree.js +91 -0
  46. package/dist/package-target-policy.d.ts +0 -1
  47. package/dist/package-target-policy.d.ts.map +1 -1
  48. package/dist/package-target-policy.js +50 -23
  49. package/dist/platform-targets.d.ts +5 -0
  50. package/dist/platform-targets.d.ts.map +1 -0
  51. package/dist/platform-targets.js +4 -0
  52. package/dist/typecheck-test-policy.d.ts +5 -9
  53. package/dist/typecheck-test-policy.d.ts.map +1 -1
  54. package/dist/typecheck-test-policy.js +69 -99
  55. package/dist/workspace-config-policy.d.ts +23 -3
  56. package/dist/workspace-config-policy.d.ts.map +1 -1
  57. package/dist/workspace-config-policy.js +35 -3
  58. package/dist/workspace-manifest.d.ts +291 -0
  59. package/dist/workspace-manifest.d.ts.map +1 -0
  60. package/dist/workspace-manifest.js +6 -0
  61. package/dist/workspace-package-policy.d.ts +13 -0
  62. package/dist/workspace-package-policy.d.ts.map +1 -0
  63. package/dist/workspace-package-policy.js +24 -0
  64. package/generators.json +5 -0
  65. package/managed/raw/envrc +20 -0
  66. package/managed/raw/git-format-staged.yml +82 -0
  67. package/managed/raw/gitattributes +8 -0
  68. package/managed/raw/tooling/devenv +83 -0
  69. package/managed/raw/tooling/direnv/devenv.smoo.nix +422 -0
  70. package/managed/raw/tooling/direnv/github-actions-bootstrap.sh +251 -0
  71. package/managed/raw/tooling/direnv/merge-newer-pins.sh +48 -0
  72. package/managed/raw/tooling/direnv/repo-path +34 -0
  73. package/managed/raw/tooling/direnv/secret-references.ts +636 -0
  74. package/managed/raw/tooling/direnv/setup-environment.ts +585 -0
  75. package/managed/raw/tooling/direnv/toolchain-stamp.ts +88 -0
  76. package/managed/raw/tooling/git-hooks/commit-msg.sh +9 -0
  77. package/managed/raw/tooling/git-hooks/post-commit.sh +71 -0
  78. package/managed/raw/tooling/git-hooks/pre-commit.sh +18 -0
  79. package/managed/raw/tooling/git-hooks/pre-push.sh +48 -0
  80. package/managed/raw/tsconfig.lib.json +28 -0
  81. package/managed/templates/github/actions/cache-nix-devenv/action.yml +45 -0
  82. package/managed/templates/github/actions/cache-node-modules/action.yml +17 -0
  83. package/managed/templates/github/actions/cache-nx/action.yml +21 -0
  84. package/managed/templates/github/actions/cache-ttsc-plugins/action.yml +19 -0
  85. package/managed/templates/github/actions/save-nix-devenv/action.yml +32 -0
  86. package/managed/templates/github/actions/setup-devenv/action.yml +241 -0
  87. package/managed/templates/github/workflows/managed-files.yml +127 -0
  88. package/package.json +89 -5
  89. package/src/bun-bootstrap.test.ts +0 -6
  90. package/src/deploy-policy.ts +40 -0
  91. package/src/index.test.ts +232 -9
  92. package/src/index.ts +187 -40
  93. package/src/managed-assets.ts +4 -0
  94. package/src/managed-files/ci-workflow.ts +1365 -0
  95. package/src/managed-files/context.ts +240 -0
  96. package/src/managed-files/files.ts +324 -0
  97. package/src/managed-files/generator.test.ts +151 -0
  98. package/src/managed-files/generator.ts +60 -0
  99. package/src/managed-files/github-runs-on.ts +51 -0
  100. package/src/managed-files/managed-content.test.ts +147 -0
  101. package/src/managed-files/managed-content.ts +121 -0
  102. package/src/managed-files/managed-format.ts +102 -0
  103. package/src/managed-files/paths.ts +44 -0
  104. package/src/managed-files/pr-preview-cleanup-workflow.ts +44 -0
  105. package/src/managed-files/private-npm-policy.ts +62 -0
  106. package/src/managed-files/publish-workflow.ts +1523 -0
  107. package/src/managed-files/schema.json +8 -0
  108. package/src/managed-files/tree-permissions.test.ts +109 -0
  109. package/src/managed-files/tree.test.ts +123 -0
  110. package/src/managed-files/tree.ts +118 -0
  111. package/src/package-target-policy.test.ts +4 -28
  112. package/src/package-target-policy.ts +55 -31
  113. package/src/platform-targets.ts +4 -0
  114. package/src/typecheck-test-policy.test.ts +28 -3
  115. package/src/typecheck-test-policy.ts +46 -121
  116. package/src/workspace-config-policy.test.ts +14 -2
  117. package/src/workspace-config-policy.ts +42 -3
  118. package/src/workspace-manifest.ts +327 -0
  119. package/src/workspace-package-policy.ts +32 -0
@@ -0,0 +1,8 @@
1
+ {
2
+ "$schema": "https://json-schema.org/schema",
3
+ "$id": "SmoothbricksManagedFiles",
4
+ "title": "Synchronize managed monorepo files",
5
+ "type": "object",
6
+ "properties": {},
7
+ "additionalProperties": false
8
+ }
@@ -0,0 +1,109 @@
1
+ import { afterEach, describe, expect, it } from 'bun:test';
2
+ import { chmodSync, mkdirSync, mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs';
3
+ import { tmpdir } from 'node:os';
4
+ import { dirname, join } from 'node:path';
5
+ import { createTree } from 'nx/src/devkit-testing-exports.js';
6
+ import { FsTree, flushChanges } from 'nx/src/generators/tree.js';
7
+ import { LOCAL_SECTION_MARKER } from './managed-content.js';
8
+ import { type ManagedFile, stageManagedFiles } from './tree.js';
9
+
10
+ const script = {
11
+ target: 'tooling/run',
12
+ content: '#!/bin/sh\necho ready\n',
13
+ executable: true,
14
+ } satisfies ManagedFile;
15
+ const roots: string[] = [];
16
+
17
+ function diskTree(content: string, mode: number): FsTree {
18
+ const root = mkdtempSync(join(tmpdir(), 'smoo-tree-mode-'));
19
+ roots.push(root);
20
+ const target = join(root, script.target);
21
+ mkdirSync(dirname(target), { recursive: true });
22
+ writeFileSync(target, content);
23
+ chmodSync(target, mode);
24
+ return new FsTree(root, false);
25
+ }
26
+
27
+ afterEach(() => {
28
+ for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true });
29
+ });
30
+
31
+ describe('managed permissions compose with other Nx generators', () => {
32
+ it('makes an already-staged matching script executable', () => {
33
+ const tree = createTree();
34
+ tree.write(script.target, script.content);
35
+ expect(stageManagedFiles(tree, [script])[0].action).toBe('updated');
36
+ expect(tree.listChanges().find(({ path }) => path === script.target)?.options?.mode).toBe(0o755);
37
+ });
38
+
39
+ it('uses staged permissions rather than stale filesystem metadata', () => {
40
+ const tree = createTree();
41
+ tree.write(script.target, script.content, { mode: 0o644 });
42
+ const paths = new Map([[script.target, { executable: true }]]);
43
+ expect(stageManagedFiles(tree, [script], paths)[0].action).toBe('updated');
44
+ expect(tree.listChanges().find(({ path }) => path === script.target)?.options?.mode).toBe(0o755);
45
+ });
46
+
47
+ it('is unchanged on a second pass even when the disk snapshot predates the repair', () => {
48
+ const tree = createTree();
49
+ tree.write(script.target, script.content);
50
+ const paths = new Map([[script.target, { executable: false }]]);
51
+ stageManagedFiles(tree, [script], paths);
52
+ const before = tree.listChanges();
53
+ expect(stageManagedFiles(tree, [script], paths)[0].action).toBe('unchanged');
54
+ expect(tree.listChanges()).toEqual(before);
55
+ });
56
+
57
+ it('recognizes octal-string modes supported by Nx Tree', () => {
58
+ const tree = createTree();
59
+ tree.write(script.target, script.content, { mode: '755' });
60
+ const before = tree.listChanges();
61
+ expect(stageManagedFiles(tree, [script], new Map([[script.target, { executable: false }]]))[0].action).toBe(
62
+ 'unchanged',
63
+ );
64
+ expect(tree.listChanges()).toEqual(before);
65
+ });
66
+
67
+ it('removes a staged executable bit from a non-executable managed file', () => {
68
+ const tree = createTree();
69
+ tree.write(script.target, script.content, { mode: 0o755 });
70
+ expect(stageManagedFiles(tree, [{ ...script, executable: false }])[0].action).toBe('updated');
71
+ expect(tree.listChanges().find(({ path }) => path === script.target)?.options?.mode).toBe(0o644);
72
+ });
73
+
74
+ it('preserves local content during a staged permission-only repair', () => {
75
+ const tree = createTree();
76
+ const current = `${script.content}\n${LOCAL_SECTION_MARKER}\n# local\n`;
77
+ tree.write(script.target, current);
78
+ stageManagedFiles(tree, [script]);
79
+ expect(tree.read(script.target, 'utf8')).toBe(current);
80
+ expect(tree.listChanges().find(({ path }) => path === script.target)?.options?.mode).toBe(0o755);
81
+ });
82
+
83
+ it('retains the required mode when write() elides a reversion to the disk contents', () => {
84
+ const tree = diskTree(script.content, 0o644);
85
+ tree.write(script.target, '#!/bin/sh\necho temporary\n', { mode: 0o755 });
86
+ stageManagedFiles(tree, [script], new Map([[script.target, { executable: false }]]));
87
+ flushChanges(tree.root, tree.listChanges());
88
+ expect(readFileSync(join(tree.root, script.target), 'utf8')).toBe(script.content);
89
+ expect(statSync(join(tree.root, script.target)).mode & 0o777).toBe(0o755);
90
+
91
+ const fresh = new FsTree(tree.root, false);
92
+ expect(stageManagedFiles(fresh, [script], new Map([[script.target, { executable: true }]]))[0].action).toBe(
93
+ 'unchanged',
94
+ );
95
+ expect(fresh.listChanges()).toEqual([]);
96
+ });
97
+
98
+ it('inherits the disk mode for a pending update with no explicit mode', () => {
99
+ const tree = diskTree('#!/bin/sh\necho old\n', 0o755);
100
+ tree.write(script.target, script.content);
101
+ const before = tree.listChanges();
102
+ expect(stageManagedFiles(tree, [script], new Map([[script.target, { executable: true }]]))[0].action).toBe(
103
+ 'unchanged',
104
+ );
105
+ expect(tree.listChanges()).toEqual(before);
106
+ flushChanges(tree.root, tree.listChanges());
107
+ expect(statSync(join(tree.root, script.target)).mode & 0o777).toBe(0o755);
108
+ });
109
+ });
@@ -0,0 +1,123 @@
1
+ import { describe, expect, it } from 'bun:test';
2
+ import fc from 'fast-check';
3
+ import { createTree } from 'nx/src/devkit-testing-exports.js';
4
+ import { INLINE_LOCAL_BEGIN, INLINE_LOCAL_END, LOCAL_SECTION_MARKER } from './managed-content.js';
5
+ import { assertNoManagedConflicts, mergeManagedContent, stageManagedFiles } from './tree.js';
6
+
7
+ const file = { target: 'tooling/config', content: 'managed\n' };
8
+
9
+ describe('managed files in Nx Tree', () => {
10
+ it('stages a missing template with explicit permissions', () => {
11
+ const tree = createTree();
12
+ const initial = tree.listChanges();
13
+ expect(stageManagedFiles(tree, [file])).toEqual([{ target: file.target, action: 'created' }]);
14
+ expect(tree.listChanges()).toEqual([
15
+ ...initial,
16
+ { path: file.target, type: 'CREATE', content: Buffer.from(file.content), options: { mode: 0o644 } },
17
+ ]);
18
+ });
19
+
20
+ it('distinguishes an empty file from a missing file', () => {
21
+ const tree = createTree();
22
+ tree.write(file.target, '');
23
+ expect(stageManagedFiles(tree, [file])[0].action).toBe('updated');
24
+ });
25
+
26
+ it('does not delete disabled descriptors or their customizations', () => {
27
+ const tree = createTree();
28
+ tree.write(file.target, 'owned locally');
29
+ expect(stageManagedFiles(tree, [{ ...file, content: null }])[0].action).toBe('skipped');
30
+ expect(tree.read(file.target, 'utf8')).toBe('owned locally');
31
+ });
32
+
33
+ it('preserves tails, adjacent inline blocks, indentation, and their order', () => {
34
+ const tree = createTree();
35
+ const local = [
36
+ 'anchor',
37
+ ` ${INLINE_LOCAL_BEGIN}`,
38
+ 'one',
39
+ ` ${INLINE_LOCAL_END}`,
40
+ INLINE_LOCAL_BEGIN,
41
+ 'two',
42
+ INLINE_LOCAL_END,
43
+ 'old',
44
+ LOCAL_SECTION_MARKER,
45
+ 'tail',
46
+ ].join('\n');
47
+ tree.write(file.target, local);
48
+ assertNoManagedConflicts(stageManagedFiles(tree, [{ ...file, content: 'anchor\nnew\n' }]));
49
+ const result = tree.read(file.target, 'utf8');
50
+ expect(result).toBe(local.replace('old\n', 'new\n\n'));
51
+ expect(stageManagedFiles(tree, [{ ...file, content: 'anchor\nnew\n' }])[0].action).toBe('unchanged');
52
+ expect(tree.read(file.target, 'utf8')).toBe(result);
53
+ });
54
+
55
+ it('uses Tree for an existing pending edit instead of rereading the disk', () => {
56
+ const tree = createTree();
57
+ tree.write(file.target, `before\n${LOCAL_SECTION_MARKER}\nfirst`);
58
+ tree.write(file.target, `before\n${LOCAL_SECTION_MARKER}\nsecond`);
59
+ stageManagedFiles(tree, [file]);
60
+ expect(tree.read(file.target, 'utf8')).toBe(`${file.content}\n${LOCAL_SECTION_MARKER}\nsecond`);
61
+ });
62
+
63
+ it.each(['../outside', '/outside', './config', 'a//b', 'C:/config', 'a\\b', 'a\0b'])(
64
+ 'rejects non-relative target %s',
65
+ (target) => {
66
+ const tree = createTree();
67
+ const initial = tree.listChanges();
68
+ const results = stageManagedFiles(tree, [{ ...file, target }]);
69
+ expect(() => assertNoManagedConflicts(results)).toThrow('workspace-relative');
70
+ expect(tree.listChanges()).toEqual(initial);
71
+ },
72
+ );
73
+
74
+ it('reports duplicate descriptors and overlapping file/directory targets', () => {
75
+ expect(() => assertNoManagedConflicts(stageManagedFiles(createTree(), [file, file]))).toThrow('duplicate');
76
+ expect(() =>
77
+ assertNoManagedConflicts(stageManagedFiles(createTree(), [{ ...file, target: 'tooling' }, file])),
78
+ ).toThrow('parent directory');
79
+ });
80
+
81
+ it('refuses lost or ambiguous anchors without changing that file', () => {
82
+ for (const content of ['removed\n', 'anchor\nanchor\n']) {
83
+ const tree = createTree();
84
+ const current = ['anchor', INLINE_LOCAL_BEGIN, 'local', INLINE_LOCAL_END, ''].join('\n');
85
+ tree.write(file.target, current);
86
+ expect(() => assertNoManagedConflicts(stageManagedFiles(tree, [{ ...file, content }]))).toThrow('matches');
87
+ expect(tree.read(file.target, 'utf8')).toBe(current);
88
+ }
89
+ });
90
+
91
+ it('keeps matching links and refuses drifted links', () => {
92
+ const tree = createTree();
93
+ tree.write(file.target, file.content);
94
+ const paths = new Map([[file.target, { symlink: true, executable: false }]]);
95
+ expect(stageManagedFiles(tree, [file], paths)[0].action).toBe('ok-symlink');
96
+ expect(() => assertNoManagedConflicts(stageManagedFiles(tree, [{ ...file, content: 'new' }], paths))).toThrow(
97
+ 'symlink content',
98
+ );
99
+ expect(tree.read(file.target, 'utf8')).toBe(file.content);
100
+ });
101
+
102
+ it('uses Tree.changePermissions for a permission-only update and preserves the content', () => {
103
+ const tree = createTree();
104
+ const content = `${file.content}${LOCAL_SECTION_MARKER}\nlocal`;
105
+ tree.write(file.target, content);
106
+ const paths = new Map([[file.target, { executable: false }]]);
107
+ expect(stageManagedFiles(tree, [{ ...file, executable: true }], paths)[0].action).toBe('updated');
108
+ expect(tree.listChanges().find((change) => change.path === file.target)?.options?.mode).toBe(0o755);
109
+ expect(tree.read(file.target, 'utf8')).toBe(content);
110
+ });
111
+
112
+ it('preserves arbitrary local tails and converges under repeated rendering', () => {
113
+ fc.assert(
114
+ fc.property(fc.string(), fc.string(), (old, tail) => {
115
+ const current = `${old.replaceAll('# smoo-local', '# ordinary')}\n${LOCAL_SECTION_MARKER}\n${tail}`;
116
+ const next = mergeManagedContent(current, file.content);
117
+ expect(next.endsWith(`${LOCAL_SECTION_MARKER}\n${tail}`)).toBe(true);
118
+ expect(mergeManagedContent(next, file.content)).toBe(next);
119
+ }),
120
+ { numRuns: 100 },
121
+ );
122
+ });
123
+ });
@@ -0,0 +1,118 @@
1
+ import type { FileChange, Tree } from 'nx/src/devkit-exports.js';
2
+ import {
3
+ extractInlineLocalBlocks,
4
+ ManagedContentConflict,
5
+ reinsertInlineLocalBlocks,
6
+ splitLocalSection,
7
+ } from './managed-content.js';
8
+
9
+ /** Rendered template input. A disabled descriptor never authorizes deletion. */
10
+ export interface ManagedFile {
11
+ target: string;
12
+ content: string | null;
13
+ executable?: boolean;
14
+ }
15
+
16
+ /** Only facts Tree cannot expose. File contents always come from Tree. */
17
+ export interface ManagedPathInfo {
18
+ symlink?: boolean;
19
+ executable?: boolean;
20
+ error?: string;
21
+ }
22
+
23
+ /** User-facing diagnostics, not a second representation of Tree's file changes. */
24
+ export interface FileResult {
25
+ target: string;
26
+ action: 'created' | 'updated' | 'unchanged' | 'skipped' | 'skipped-symlink' | 'drifted' | 'ok-symlink';
27
+ reason?: string;
28
+ }
29
+
30
+ export function isManagedTarget(target: string): boolean {
31
+ return (
32
+ target.length > 0 &&
33
+ !/[\0\\:]/.test(target) &&
34
+ target.split('/').every((part) => part !== '' && part !== '.' && part !== '..')
35
+ );
36
+ }
37
+
38
+ /** Pure ownership rule; retain exact existing bytes when only permissions need repair. */
39
+ export function mergeManagedContent(current: string, desired: string): string {
40
+ const { managed, localTail } = splitLocalSection(current);
41
+ const { withoutInline, blocks } = extractInlineLocalBlocks(managed);
42
+ const rendered = reinsertInlineLocalBlocks(desired, blocks);
43
+ if (withoutInline === desired || (localTail !== '' && withoutInline === `${desired}\n`)) return current;
44
+ return localTail === '' ? rendered : `${rendered}\n${localTail}`;
45
+ }
46
+
47
+ /** Pending Nx edits override disk facts; updates without a mode retain the disk mode. */
48
+ function stagedExecutable(change: FileChange | undefined, onDisk: boolean | undefined): boolean | undefined {
49
+ const mode = change?.options?.mode;
50
+ if (mode === undefined) return change?.type === 'CREATE' ? false : onDisk;
51
+ return ((typeof mode === 'string' ? Number.parseInt(mode, 8) : mode) & 0o100) !== 0;
52
+ }
53
+
54
+ /**
55
+ * Stage updates in Nx's virtual filesystem. No disk, process, graph, or network
56
+ * access. The caller decides whether to inspect or flush Tree.listChanges().
57
+ * A conflict may leave earlier edits staged; neither caller may flush that Tree.
58
+ */
59
+ export function stageManagedFiles(
60
+ tree: Tree,
61
+ files: readonly ManagedFile[],
62
+ paths: ReadonlyMap<string, ManagedPathInfo> = new Map(),
63
+ ): FileResult[] {
64
+ const seen = new Set<string>();
65
+ const pending = new Map(tree.listChanges().map((change) => [change.path, change]));
66
+ const targets = new Set(files.map((file) => file.target));
67
+ return files.map(({ target, content, executable = false }): FileResult => {
68
+ const conflict = (reason: string): FileResult => ({ target, action: 'drifted', reason });
69
+ if (!isManagedTarget(target)) return conflict('expected a canonical workspace-relative path');
70
+ if (seen.has(target)) return conflict('duplicate managed target');
71
+ seen.add(target);
72
+ const parts = target.split('/');
73
+ if (parts.some((_, i) => i > 0 && targets.has(parts.slice(0, i).join('/')))) {
74
+ return conflict('a managed file is also declared as a parent directory');
75
+ }
76
+ if (content === null) return { target, action: 'skipped' };
77
+ const path = paths.get(target);
78
+ if (path?.error) return conflict(path.error);
79
+ for (let i = 1; i < parts.length; i++) {
80
+ if (tree.isFile(parts.slice(0, i).join('/'))) return conflict('parent path is a file');
81
+ }
82
+ if (tree.exists(target) && !tree.isFile(target)) return conflict('target is not a regular file');
83
+ const current = tree.read(target, 'utf8');
84
+ if (current === null && tree.exists(target)) return conflict('target cannot be read');
85
+ try {
86
+ const rendered = current === null ? content : mergeManagedContent(current, content);
87
+ const currentExecutable = stagedExecutable(pending.get(target), path?.executable);
88
+ const modeMatches = currentExecutable === undefined || currentExecutable === executable;
89
+ if (path?.symlink) {
90
+ return current === rendered && modeMatches
91
+ ? { target, action: 'ok-symlink' }
92
+ : conflict('symlink content or executable mode differs; update its source explicitly');
93
+ }
94
+ const mode = executable ? 0o755 : 0o644;
95
+ if (current !== rendered) tree.write(target, rendered);
96
+ // A write reverting a prior generator's edit to the on-disk content can
97
+ // erase its pending mode too. Stage permissions after every content write,
98
+ // as well as for permission-only repairs, using Nx's dedicated API.
99
+ if (current !== rendered || !modeMatches) tree.changePermissions(target, mode);
100
+ return {
101
+ target,
102
+ action: current === null ? 'created' : current !== rendered || !modeMatches ? 'updated' : 'unchanged',
103
+ };
104
+ } catch (error) {
105
+ if (!(error instanceof ManagedContentConflict)) throw error;
106
+ return conflict(error.message);
107
+ }
108
+ });
109
+ }
110
+
111
+ export function assertNoManagedConflicts(results: readonly FileResult[]): void {
112
+ const conflicts = results.filter((result) => result.reason !== undefined);
113
+ if (conflicts.length > 0) {
114
+ throw new ManagedContentConflict(
115
+ `Managed-file update refused before writing:\n${conflicts.map(({ target, reason }) => `${target}: ${reason}`).join('\n')}`,
116
+ );
117
+ }
118
+ }
@@ -175,13 +175,7 @@ describe('package target policy', () => {
175
175
  });
176
176
 
177
177
  const resolvedTargetsByProject = new Map<string, ResolvedProjectTargets>([
178
- [
179
- 'lib',
180
- {
181
- targets: new Set(['build', 'tsc-js']),
182
- buildDependsOn: ['^build', '*-js'],
183
- },
184
- ],
178
+ ['lib', { targets: new Set(['build', 'tsc-js']) }],
185
179
  ]);
186
180
 
187
181
  expect(applyPackageTargetPolicy(root, { resolvedTargetsByProject })).toBe(true);
@@ -216,13 +210,7 @@ describe('package target policy', () => {
216
210
  });
217
211
 
218
212
  const resolvedTargetsByProject = new Map<string, ResolvedProjectTargets>([
219
- [
220
- 'lib',
221
- {
222
- targets: new Set(['build', 'tsc-js']),
223
- buildDependsOn: ['^build', '*-js'],
224
- },
225
- ],
213
+ ['lib', { targets: new Set(['build', 'tsc-js']) }],
226
214
  ]);
227
215
 
228
216
  expect(applyPackageTargetPolicy(root, { resolvedTargetsByProject })).toBe(false);
@@ -911,13 +899,7 @@ describe('applyPackageTargetPolicyTree', () => {
911
899
  });
912
900
 
913
901
  const resolvedTargetsByProject = new Map<string, ResolvedProjectTargets>([
914
- [
915
- 'lib',
916
- {
917
- targets: new Set(['build', 'tsc-js']),
918
- buildDependsOn: ['^build', '*-js'],
919
- },
920
- ],
902
+ ['lib', { targets: new Set(['build', 'tsc-js']) }],
921
903
  ]);
922
904
 
923
905
  expect(applyPackageTargetPolicyTree(tree, { resolvedTargetsByProject })).toBe(true);
@@ -943,13 +925,7 @@ describe('applyPackageTargetPolicyTree', () => {
943
925
  });
944
926
 
945
927
  const resolvedTargetsByProject = new Map<string, ResolvedProjectTargets>([
946
- [
947
- 'lib',
948
- {
949
- targets: new Set(['build', 'tsc-js']),
950
- buildDependsOn: ['^build', '*-js'],
951
- },
952
- ],
928
+ ['lib', { targets: new Set(['build', 'tsc-js']) }],
953
929
  ]);
954
930
 
955
931
  expect(applyPackageTargetPolicyTree(tree, { resolvedTargetsByProject })).toBe(false);
@@ -7,6 +7,8 @@ import { boundedTestScriptAlias } from './bounded-test-policy.js';
7
7
  import { isNonSourceDirectory } from './source-directories.js';
8
8
  import {
9
9
  BUILD_OUTPUT_DEPENDENCIES,
10
+ isBuildOutputTargetName,
11
+ isTestRunnerTargetName,
10
12
  LINUX_PLATFORM_TARGET_GLOBS,
11
13
  MACOS_PLATFORM_TARGET_GLOBS,
12
14
  type NxPolicyIssue,
@@ -18,7 +20,6 @@ export type { NxPolicyIssue };
18
20
  export interface ResolvedProjectTargets {
19
21
  root?: string;
20
22
  targets: ReadonlySet<string>;
21
- buildDependsOn?: readonly string[];
22
23
  targetDependencies?: ReadonlyMap<string, readonly string[]>;
23
24
  targetExecutors?: ReadonlyMap<string, string>;
24
25
  targetOptions?: ReadonlyMap<string, Readonly<Record<string, unknown>>>;
@@ -190,15 +191,6 @@ function resolvedProjectTargetNames(
190
191
  return isResolvedProjectTargets(resolvedProject) ? resolvedProject.targets : resolvedProject;
191
192
  }
192
193
 
193
- function resolvedProjectBuildDependsOn(
194
- resolvedProject?: ReadonlySet<string> | ResolvedProjectTargets,
195
- ): readonly string[] | undefined {
196
- if (!isResolvedProjectTargets(resolvedProject)) {
197
- return undefined;
198
- }
199
- return resolvedProject.buildDependsOn;
200
- }
201
-
202
194
  function resolvedProjectTargetExecutor(
203
195
  resolvedProject: ReadonlySet<string> | ResolvedProjectTargets | undefined,
204
196
  targetName: string,
@@ -286,43 +278,75 @@ function isNoopTarget(target: Record<string, unknown>): boolean {
286
278
  return !options || stringProperty(options, 'command') === null;
287
279
  }
288
280
 
289
- function targetDependenciesMatchResolvedBuild(
290
- target: Record<string, unknown>,
291
- resolvedBuildDependsOn: readonly string[],
292
- ): boolean {
293
- if (!Array.isArray(target.dependsOn)) {
281
+ /**
282
+ * Properties the inferred aggregate already sets to exactly these values. A
283
+ * declaration carrying anything else — `inputs`, `outputs`, `cache: false`, a
284
+ * `configurations` block — is CHANGING the aggregate, not restating it.
285
+ */
286
+ const inferredNoopBuildProperties: Record<string, true> = { executor: true, cache: true, dependsOn: true };
287
+
288
+ /**
289
+ * Can the build-aggregate inference produce this edge on its own?
290
+ *
291
+ * The inferred aggregate is `^build` plus the project's own build-output
292
+ * targets — `isBuildOutputTargetName`, test runners excluded — and
293
+ * `BUILD_OUTPUT_DEPENDENCIES` is the glob spelling of that same list. Anything
294
+ * else is an edge only the declaration carries: a project-local target outside
295
+ * the families (`build-cli`), or a `project:target` edge to a sibling target
296
+ * that is not named `build`, which `^build` never visits.
297
+ */
298
+ function isInferredBuildDependency(dependency: unknown, resolvedTargets: ReadonlySet<string>): boolean {
299
+ if (typeof dependency !== 'string') {
294
300
  return false;
295
301
  }
296
- const expected = new Set(resolvedBuildDependsOn);
297
- if (target.dependsOn.length !== expected.size) {
302
+ if (dependency === '^build' || isBuildOutputDependencyPattern(dependency)) {
303
+ return true;
304
+ }
305
+ return isBuildOutputTargetName(dependency) && !isTestRunnerTargetName(dependency) && resolvedTargets.has(dependency);
306
+ }
307
+
308
+ function isRedundantBuildDeclaration(build: Record<string, unknown>, resolvedTargets: ReadonlySet<string>): boolean {
309
+ if (!Object.keys(build).every((key) => inferredNoopBuildProperties[key] === true)) {
298
310
  return false;
299
311
  }
300
- return target.dependsOn.every((dependency) => {
301
- if (typeof dependency !== 'string') {
302
- return false;
303
- }
304
- return expected.has(dependency);
305
- });
312
+ if ('cache' in build && build.cache !== true) {
313
+ return false;
314
+ }
315
+ // An empty list is a deliberate cut — "this aggregate waits for nothing" —
316
+ // and restoring the inferred edges by deleting it is a behaviour change.
317
+ return (
318
+ Array.isArray(build.dependsOn) &&
319
+ build.dependsOn.length > 0 &&
320
+ build.dependsOn.every((dependency) => isInferredBuildDependency(dependency, resolvedTargets))
321
+ );
306
322
  }
307
323
 
324
+ /**
325
+ * A hand-declared `build` is deleted only when inference provably rebuilds it.
326
+ *
327
+ * Deliberately NOT decided against the resolved project graph. Nx replaces a
328
+ * named property of an inferred target with the declared one, so the resolved
329
+ * `build.dependsOn` IS the declaration: comparing them answered "redundant"
330
+ * for every noop aggregate anyone ever wrote. AxE's `containium` lost seven
331
+ * edges that way — four of them targets no inference can reach — and a clean
332
+ * checkout then built it without its producers. The question this has to
333
+ * answer is what inference yields WITHOUT the declaration, so the test is
334
+ * structural: every declared edge must be one the aggregate already collects.
335
+ */
308
336
  function removeRedundantNoopBuildTarget(
309
337
  pkg: Record<string, unknown>,
310
338
  resolvedProject?: ReadonlySet<string> | ResolvedProjectTargets,
311
339
  ): boolean {
312
340
  const resolvedTargets = resolvedProjectTargetNames(resolvedProject);
313
- const resolvedBuildDependsOn = resolvedProjectBuildDependsOn(resolvedProject);
314
- if (!resolvedTargets?.has('build') || !resolvedBuildDependsOn) {
341
+ // No build-output target in the project, no inferred aggregate to fall back
342
+ // on: deleting the declaration would leave it with no `build` at all.
343
+ if (!resolvedTargets?.has('build') || ![...resolvedTargets].some(isBuildOutputTargetName)) {
315
344
  return false;
316
345
  }
317
346
  const nx = recordProperty(pkg, 'nx');
318
347
  const targets = nx ? recordProperty(nx, 'targets') : null;
319
348
  const build = targets ? recordProperty(targets, 'build') : null;
320
- if (
321
- !targets ||
322
- !build ||
323
- !isNoopTarget(build) ||
324
- !targetDependenciesMatchResolvedBuild(build, resolvedBuildDependsOn)
325
- ) {
349
+ if (!targets || !build || !isNoopTarget(build) || !isRedundantBuildDeclaration(build, resolvedTargets)) {
326
350
  return false;
327
351
  }
328
352
  delete targets.build;
@@ -0,0 +1,4 @@
1
+ /** Shared artifact target naming conventions; no graph construction or filesystem access. */
2
+ export const MACOS_PLATFORM_TARGET_GLOBS = ['*-macos', '*-ios'] as const;
3
+ export const LINUX_PLATFORM_TARGET_GLOBS = ['*-linux'] as const;
4
+ export const PLATFORM_TARGET_GLOBS = [...MACOS_PLATFORM_TARGET_GLOBS, ...LINUX_PLATFORM_TARGET_GLOBS] as const;
@@ -3,19 +3,21 @@ import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';
3
3
  import { tmpdir } from 'node:os';
4
4
  import { dirname, join } from 'node:path';
5
5
 
6
- import { addProjectConfiguration, readJson, writeJson } from 'nx/src/devkit-exports.js';
6
+ import { addProjectConfiguration, readJson, type Tree, writeJson } from 'nx/src/devkit-exports.js';
7
7
  import { createTreeWithEmptyWorkspace } from 'nx/src/devkit-testing-exports.js';
8
+ import { FsTree, flushChanges } from 'nx/src/generators/tree.js';
9
+ import { inspectManagedPaths } from './managed-files/paths.js';
10
+ import { assertNoManagedConflicts, stageManagedFiles } from './managed-files/tree.js';
8
11
 
9
12
  import {
10
13
  applyTypecheckTestDefaults,
11
- applyTypecheckTestPolicy,
12
- applyTypecheckTestPolicyTree,
13
14
  checkTsconfigTestReference,
14
15
  checkTypecheckTestConfig,
15
16
  checkTypecheckTestPolicy,
16
17
  checkTypecheckTestPolicyTree,
17
18
  detectPackageTestRunners,
18
19
  removeTsconfigTestReference,
20
+ renderTypecheckTestFiles,
19
21
  } from './typecheck-test-policy.js';
20
22
 
21
23
  // ---------------------------------------------------------------------------
@@ -27,6 +29,29 @@ async function writeJsonFs(path: string, value: unknown): Promise<void> {
27
29
  await writeFile(path, `${JSON.stringify(value, null, 2)}\n`);
28
30
  }
29
31
 
32
+ function applyTypecheckTestPolicyTree(tree: Tree): boolean {
33
+ const results = stageManagedFiles(tree, renderTypecheckTestFiles(tree));
34
+ assertNoManagedConflicts(results);
35
+ return results.some((result) => result.action === 'created' || result.action === 'updated');
36
+ }
37
+
38
+ function applyTypecheckTestPolicy(root: string): boolean {
39
+ const tree = new FsTree(root, false);
40
+ const files = renderTypecheckTestFiles(tree);
41
+ const results = stageManagedFiles(
42
+ tree,
43
+ files,
44
+ inspectManagedPaths(
45
+ root,
46
+ files.map((file) => file.target),
47
+ ),
48
+ );
49
+ assertNoManagedConflicts(results);
50
+ const changes = tree.listChanges();
51
+ flushChanges(root, changes);
52
+ return changes.length > 0;
53
+ }
54
+
30
55
  async function readJsonFs(path: string): Promise<unknown> {
31
56
  return JSON.parse(await readFile(path, 'utf8'));
32
57
  }