@otwld/nx-argo 0.0.5 → 0.0.6

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 (29) hide show
  1. package/CHANGELOG.md +17 -0
  2. package/README.md +18 -61
  3. package/generators.json +8 -13
  4. package/package.json +1 -1
  5. package/src/executors/validate/schema.d.ts +5 -1
  6. package/src/executors/validate/schema.json +14 -3
  7. package/src/executors/validate/validate.d.ts +1 -1
  8. package/src/executors/validate/validate.js +149 -15
  9. package/src/executors/write-artifact-lock/schema.d.ts +8 -0
  10. package/src/executors/write-artifact-lock/schema.json +19 -1
  11. package/src/executors/write-artifact-lock/write-artifact-lock.d.ts +1 -1
  12. package/src/executors/write-artifact-lock/write-artifact-lock.js +127 -16
  13. package/src/generators/environment-project/environment-project.d.ts +4 -0
  14. package/src/generators/{service-application/service-application.js → environment-project/environment-project.js} +13 -9
  15. package/src/generators/environment-project/schema.d.ts +13 -0
  16. package/src/generators/{service-application → environment-project}/schema.json +7 -11
  17. package/src/generators/preview-project/preview-project.d.ts +4 -0
  18. package/src/generators/{preview-stack/preview-stack.js → preview-project/preview-project.js} +7 -8
  19. package/src/generators/{preview-stack → preview-project}/schema.d.ts +2 -4
  20. package/src/generators/{preview-stack → preview-project}/schema.json +2 -6
  21. package/src/index.d.ts +4 -6
  22. package/src/index.js +5 -7
  23. package/src/generators/application/application.d.ts +0 -9
  24. package/src/generators/application/application.js +0 -263
  25. package/src/generators/application/schema.d.ts +0 -27
  26. package/src/generators/application/schema.json +0 -97
  27. package/src/generators/preview-stack/preview-stack.d.ts +0 -4
  28. package/src/generators/service-application/schema.d.ts +0 -15
  29. package/src/generators/service-application/service-application.d.ts +0 -4
package/CHANGELOG.md CHANGED
@@ -1,3 +1,20 @@
1
+ ## 0.0.6 (unreleased)
2
+
3
+ ### Breaking changes
4
+
5
+ - Replace `application`, `service-application`, and `preview-stack` with `environment-project` and `preview-project`.
6
+ - Validate project-local environment locks and preview ApplicationSets; artifact writes are revision-idempotent.
7
+
8
+ ## 0.0.5 (2026-08-12)
9
+
10
+ ### 🚀 Features
11
+
12
+ - **argo:** add GitOps project tooling ([b291a720](https://github.com/otwld/devops/commit/b291a720))
13
+
14
+ ### ❤️ Thank You
15
+
16
+ - Tréhout Nathan
17
+
1
18
  ## 0.0.4 (2026-08-12)
2
19
 
3
20
  ### 🚀 Features
package/README.md CHANGED
@@ -1,80 +1,37 @@
1
1
  # @otwld/nx-argo
2
2
 
3
- Nx generator for Argo CD Applications and Helm values files.
3
+ Nx contract tooling for GitOps projects. It does not create or operate Argo CD resources.
4
4
 
5
- ## GitOps Projects
5
+ ## Generators
6
6
 
7
- `service-application` creates a GitOps project for one workload and
8
- environment. It records the deployment service key, depends only on its owning
9
- app, and creates separate human-owned `values.yaml` and automation-owned
10
- `artifacts.yaml` files.
7
+ `environment-project` creates `gitops/environments/<service>/<environment>` with:
8
+
9
+ - `project.json`: `gitops-<service>-<environment>`, one owning app dependency, delivery metadata, validation, and uncached artifact writes.
10
+ - `values.yaml`: human-owned configuration.
11
+ - `artifacts.yaml`: automation-owned immutable artifact lock.
11
12
 
12
13
  ```shell
13
- pnpm exec nx g @otwld/nx-argo:service-application frontend \
14
- --environment=staging \
15
- --app=frontend
14
+ pnpm exec nx g @otwld/nx-argo:environment-project frontend \
15
+ --environment=staging --app=frontend
16
16
  ```
17
17
 
18
- `preview-stack` creates an explicit multi-workload preview boundary. The
19
- declared apps are the only Nx dependencies; Argo CD resources remain entirely
20
- user-defined.
18
+ `preview-project` creates `gitops/previews/<name>/project.json` with explicit app dependencies and `delivery.previewStack`. It creates no PR-specific lock. Add `application-set.yaml` before running validation.
21
19
 
22
20
  ```shell
23
- pnpm exec nx g @otwld/nx-argo:preview-stack web \
21
+ pnpm exec nx g @otwld/nx-argo:preview-project web \
24
22
  --apps=frontend,backend
25
23
  ```
26
24
 
27
- Generated GitOps projects use `validate` and `write-artifact-lock` targets.
28
- The latter writes one immutable image repository and digest to paths declared
29
- by project metadata. It does not publish images, invoke Argo CD, or interpret
30
- Kubernetes resources.
31
-
32
- ## Generate an Application
33
-
34
- ```shell
35
- pnpm exec nx g @otwld/nx-argo:application \
36
- --directory=deployments/service/development \
37
- --name=service-development \
38
- --chart=service \
39
- --chartRepository=oci://registry.example.com/charts \
40
- --chartVersion=0.1.0 \
41
- --valuesRepoUrl=https://github.com/example/config.git \
42
- --valuesRevision=main \
43
- --project=default \
44
- --destinationServer=https://kubernetes.default.svc \
45
- --namespace=service-development
46
- ```
25
+ ## Contracts
47
26
 
48
- The generator writes `application.yaml` and `values.yaml` to `--directory`.
27
+ Environment validation accepts either a pending or completed `artifacts.yaml`. A pending lock has `artifact.pending: true` and exactly empty string values for `image.repository`, `image.digest`, `artifact.service`, and `artifact.sourceRevision`. A completed lock has `artifact.pending: false` (or no pending field), a nonempty repository/service/source revision, and an immutable digest. An optional `application.yaml` must be an Argo CD `Application`; when it declares Helm value files, `artifacts.yaml` is last.
49
28
 
50
- ```yaml
51
- spec:
52
- sources:
53
- - repoURL: registry.example.com/charts
54
- chart: service
55
- targetRevision: 0.1.0
56
- helm:
57
- releaseName: service
58
- valueFiles:
59
- - $values/deployments/service/development/values.yaml
60
- - repoURL: https://github.com/example/config.git
61
- targetRevision: main
62
- ref: values
63
- ```
29
+ Preview validation requires an Argo CD `ApplicationSet` at `application-set.yaml`, a PR generator, a literal nonempty template project, enabled automated sync with `prune` and `selfHeal`, and no `preserveResourcesOnDeletion`.
64
30
 
65
- The values repository URL must use HTTPS. Chart repositories may use HTTP(S) or
66
- OCI URLs; `oci://` is removed from OCI chart-source URLs.
31
+ `write-artifact-lock` requires an existing project-local lock and accepts image repository/digest plus service/source revision values. It converts a valid pending lock to `artifact.pending: false`, advances a new revision, and only verifies identical service, repository, and digest for an existing revision.
67
32
 
68
33
  ## Package Targets
69
34
 
70
- - `nx build nx-argo`
71
- - `nx lint nx-argo`
72
- - `nx test nx-argo`
73
-
74
- ## npm Release
75
-
76
- ```shell
77
- pnpm exec nx release version --groups=npm --first-release --dry-run
78
- pnpm exec nx release publish --groups=npm --first-release --dry-run --access=public
79
- pnpm exec nx release --groups=npm --first-release
80
- ```
35
+ - `pnpm exec nx build nx-argo`
36
+ - `pnpm exec nx lint nx-argo`
37
+ - `pnpm exec nx test nx-argo`
package/generators.json CHANGED
@@ -1,20 +1,15 @@
1
1
  {
2
2
  "$schema": "https://json-schema.org/schema",
3
3
  "generators": {
4
- "application": {
5
- "factory": "./src/generators/application/application",
6
- "schema": "./src/generators/application/schema.json",
7
- "description": "Create an Argo CD Application and its Helm values file."
4
+ "environment-project": {
5
+ "factory": "./src/generators/environment-project/environment-project",
6
+ "schema": "./src/generators/environment-project/schema.json",
7
+ "description": "Create a GitOps project boundary for one service environment."
8
8
  },
9
- "service-application": {
10
- "factory": "./src/generators/service-application/service-application",
11
- "schema": "./src/generators/service-application/schema.json",
12
- "description": "Create a GitOps Application project for one workload."
13
- },
14
- "preview-stack": {
15
- "factory": "./src/generators/preview-stack/preview-stack",
16
- "schema": "./src/generators/preview-stack/schema.json",
17
- "description": "Create a GitOps preview stack project for multiple workloads."
9
+ "preview-project": {
10
+ "factory": "./src/generators/preview-project/preview-project",
11
+ "schema": "./src/generators/preview-project/schema.json",
12
+ "description": "Create a GitOps project boundary for an explicit preview stack."
18
13
  }
19
14
  }
20
15
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@otwld/nx-argo",
3
- "version": "0.0.5",
3
+ "version": "0.0.6",
4
4
  "private": false,
5
5
  "type": "commonjs",
6
6
  "exports": {
@@ -1,7 +1,11 @@
1
1
  /** Options accepted by the Argo CD validation executor. */
2
2
  export interface ValidateExecutorSchema {
3
- /** Application manifest relative to the owning Nx project root. */
3
+ /** GitOps project contract to validate. */
4
+ mode: 'environment' | 'preview';
5
+ /** Optional Application manifest relative to the owning Nx project root. */
4
6
  applicationFile?: string;
7
+ /** ApplicationSet manifest relative to the owning Nx project root. */
8
+ applicationSetFile?: string;
5
9
  /** Artifact lock file relative to the owning Nx project root. */
6
10
  artifactsFile?: string;
7
11
  }
@@ -2,16 +2,27 @@
2
2
  "$schema": "https://json-schema.org/schema",
3
3
  "version": 2,
4
4
  "title": "Validate Argo CD configuration",
5
- "description": "Validate optional Argo CD Application and artifact lock files.",
5
+ "description": "Validate a GitOps environment or preview project contract.",
6
6
  "type": "object",
7
7
  "properties": {
8
+ "mode": {
9
+ "type": "string",
10
+ "enum": ["environment", "preview"],
11
+ "description": "GitOps project contract to validate."
12
+ },
8
13
  "applicationFile": {
9
14
  "type": "string",
10
- "description": "Application manifest relative to the owning Nx project root."
15
+ "description": "Optional Application manifest relative to the owning Nx project root."
16
+ },
17
+ "applicationSetFile": {
18
+ "type": "string",
19
+ "description": "ApplicationSet manifest relative to the owning Nx project root."
11
20
  },
12
21
  "artifactsFile": {
13
22
  "type": "string",
14
23
  "description": "Artifact lock file relative to the owning Nx project root."
15
24
  }
16
- }
25
+ },
26
+ "required": ["mode"],
27
+ "additionalProperties": false
17
28
  }
@@ -1,5 +1,5 @@
1
1
  import type { PromiseExecutor } from '@nx/devkit';
2
2
  import type { ValidateExecutorSchema } from './schema';
3
- /** Validates optional Argo CD Application and artifact lock documents. */
3
+ /** Validates the declared Argo CD resources and artifact lock for one project. */
4
4
  declare const runExecutor: PromiseExecutor<ValidateExecutorSchema>;
5
5
  export default runExecutor;
@@ -3,38 +3,172 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  const node_fs_1 = require("node:fs");
4
4
  const node_path_1 = require("node:path");
5
5
  const yaml_1 = require("yaml");
6
- /** Validates optional Argo CD Application and artifact lock documents. */
6
+ /** Validates the declared Argo CD resources and artifact lock for one project. */
7
7
  const runExecutor = async (options, context) => {
8
8
  const projectRoot = context.projectsConfigurations?.projects[context.projectName ?? '']?.root;
9
9
  if (!projectRoot) {
10
10
  throw new Error('[nx-argo] Validation requires an Nx project context.');
11
11
  }
12
12
  const root = (0, node_path_1.resolve)(context.root, projectRoot);
13
- validateApplication((0, node_path_1.resolve)(root, options.applicationFile || 'application.yaml'));
14
- validateArtifacts((0, node_path_1.resolve)(root, options.artifactsFile || 'artifacts.yaml'));
13
+ if (options.mode === 'environment') {
14
+ validateArtifacts(resolveProjectFile(root, options.artifactsFile, 'artifactsFile'));
15
+ if (options.applicationFile) {
16
+ validateApplication(resolveProjectFile(root, options.applicationFile, 'applicationFile'));
17
+ }
18
+ }
19
+ else {
20
+ validateApplicationSet(resolveProjectFile(root, options.applicationSetFile, 'applicationSetFile'));
21
+ }
15
22
  return { success: true };
16
23
  };
17
- /** Validates an Application document when it is present. */
18
- function validateApplication(filePath) {
24
+ /** Resolves a required project-local file without accepting path escapes. */
25
+ function resolveProjectFile(root, file, optionName) {
26
+ if (!file?.trim()) {
27
+ throw new Error(`[nx-argo] ${optionName} is required.`);
28
+ }
29
+ if ((0, node_path_1.isAbsolute)(file) || file.split(/[\\/]+/).includes('..')) {
30
+ throw new Error(`[nx-argo] ${optionName} must stay within the project root.`);
31
+ }
32
+ const filePath = (0, node_path_1.resolve)(root, file);
33
+ const pathFromRoot = (0, node_path_1.relative)(root, filePath);
34
+ if (!pathFromRoot ||
35
+ pathFromRoot === '..' ||
36
+ pathFromRoot.startsWith(`..${node_path_1.sep}`) ||
37
+ (0, node_path_1.isAbsolute)(pathFromRoot)) {
38
+ throw new Error(`[nx-argo] ${optionName} must stay within the project root.`);
39
+ }
40
+ return filePath;
41
+ }
42
+ /** Parses an existing YAML mapping. */
43
+ function readMapping(filePath, label) {
19
44
  if (!(0, node_fs_1.existsSync)(filePath)) {
20
- return;
45
+ throw new Error(`[nx-argo] Required ${label} is missing: ${filePath}`);
21
46
  }
22
47
  const document = (0, yaml_1.parseDocument)((0, node_fs_1.readFileSync)(filePath, 'utf8'));
23
- if (document.errors.length ||
24
- document.get('apiVersion') !== 'argoproj.io/v1alpha1' ||
25
- document.get('kind') !== 'Application') {
48
+ if (document.errors.length || !document.contents || !(0, yaml_1.isMap)(document.contents)) {
49
+ throw new Error(`[nx-argo] Invalid ${label}: ${filePath}`);
50
+ }
51
+ return document.toJS();
52
+ }
53
+ /** Validates an Application document. */
54
+ function validateApplication(filePath) {
55
+ const application = readMapping(filePath, 'Argo CD Application');
56
+ if (application['apiVersion'] !== 'argoproj.io/v1alpha1' ||
57
+ application['kind'] !== 'Application') {
26
58
  throw new Error(`[nx-argo] Invalid Argo CD Application: ${filePath}`);
27
59
  }
60
+ const valueFiles = getHelmValueFiles(application);
61
+ if (valueFiles.length &&
62
+ valueFiles.at(-1)?.split('/').at(-1) !== 'artifacts.yaml') {
63
+ throw new Error(`[nx-argo] artifacts.yaml must be the final Helm values file: ${filePath}`);
64
+ }
65
+ }
66
+ /** Finds Helm value file lists across single- and multi-source Applications. */
67
+ function getHelmValueFiles(application) {
68
+ const spec = getMapping(application, 'spec');
69
+ if (!spec) {
70
+ return [];
71
+ }
72
+ const sources = [
73
+ spec['source'],
74
+ ...(Array.isArray(spec['sources']) ? spec['sources'] : []),
75
+ ];
76
+ return sources.flatMap((source) => {
77
+ const helm = getMapping(source, 'helm');
78
+ const valueFiles = helm?.['valueFiles'];
79
+ return Array.isArray(valueFiles)
80
+ ? valueFiles.filter((file) => typeof file === 'string')
81
+ : [];
82
+ });
83
+ }
84
+ /** Validates an ApplicationSet document needed by a preview project. */
85
+ function validateApplicationSet(filePath) {
86
+ const applicationSet = readMapping(filePath, 'Argo CD ApplicationSet');
87
+ if (applicationSet['apiVersion'] !== 'argoproj.io/v1alpha1' ||
88
+ applicationSet['kind'] !== 'ApplicationSet') {
89
+ throw new Error(`[nx-argo] Invalid Argo CD ApplicationSet: ${filePath}`);
90
+ }
91
+ const spec = getMapping(applicationSet, 'spec');
92
+ const template = getMapping(spec, 'template');
93
+ const templateSpec = getMapping(template, 'spec');
94
+ const project = templateSpec?.['project'];
95
+ const automated = getMapping(getMapping(templateSpec, 'syncPolicy'), 'automated');
96
+ if (!containsPullRequestGenerator(spec?.['generators']) ||
97
+ typeof project !== 'string' ||
98
+ !project.trim() ||
99
+ /{{|}}/.test(project) ||
100
+ automated?.['enabled'] !== true ||
101
+ automated['prune'] !== true ||
102
+ automated['selfHeal'] !== true ||
103
+ getMapping(spec, 'syncPolicy')?.['preserveResourcesOnDeletion'] === true) {
104
+ throw new Error(`[nx-argo] Invalid preview ApplicationSet contract: ${filePath}`);
105
+ }
106
+ }
107
+ /** Recursively finds a non-null ApplicationSet pull request generator. */
108
+ function containsPullRequestGenerator(value) {
109
+ if (Array.isArray(value)) {
110
+ return value.some(containsPullRequestGenerator);
111
+ }
112
+ if (!isRecord(value)) {
113
+ return false;
114
+ }
115
+ if (isRecord(value['pullRequest'])) {
116
+ return true;
117
+ }
118
+ return Object.values(value).some(containsPullRequestGenerator);
28
119
  }
29
- /** Validates that an artifact lock is a YAML mapping when it is present. */
120
+ /** Validates the complete artifact lock required by environment projects. */
30
121
  function validateArtifacts(filePath) {
31
- if (!(0, node_fs_1.existsSync)(filePath)) {
32
- return;
122
+ const artifacts = readMapping(filePath, 'artifact lock');
123
+ const pending = getPath(artifacts, ['artifact', 'pending']);
124
+ const values = [
125
+ getPath(artifacts, ['image', 'repository']),
126
+ getPath(artifacts, ['image', 'digest']),
127
+ getPath(artifacts, ['artifact', 'service']),
128
+ getPath(artifacts, ['artifact', 'sourceRevision']),
129
+ ];
130
+ if (pending === true) {
131
+ if (values.every((value) => value === '')) {
132
+ return;
133
+ }
134
+ throw new Error(`[nx-argo] Invalid pending artifact lock: ${filePath}`);
33
135
  }
34
- const document = (0, yaml_1.parseDocument)((0, node_fs_1.readFileSync)(filePath, 'utf8'));
35
- if (document.errors.length ||
36
- (document.contents && !(0, yaml_1.isMap)(document.contents))) {
136
+ if (pending !== undefined && pending !== false) {
37
137
  throw new Error(`[nx-argo] Invalid artifact lock: ${filePath}`);
38
138
  }
139
+ if (!isNonEmptyString(values[0]) ||
140
+ !isDigest(values[1]) ||
141
+ !isNonEmptyString(values[2]) ||
142
+ !isNonEmptyString(values[3])) {
143
+ throw new Error(`[nx-argo] Invalid artifact lock: ${filePath}`);
144
+ }
145
+ }
146
+ /** Reads a nested mapping value without treating non-mappings as paths. */
147
+ function getPath(root, path) {
148
+ let current = root;
149
+ for (const segment of path) {
150
+ if (!isRecord(current)) {
151
+ return undefined;
152
+ }
153
+ current = current[segment];
154
+ }
155
+ return current;
156
+ }
157
+ /** Returns a mapping when a value has the expected structural type. */
158
+ function getMapping(value, key) {
159
+ const candidate = key === undefined ? value : isRecord(value) ? value[key] : undefined;
160
+ return isRecord(candidate) ? candidate : undefined;
161
+ }
162
+ /** Narrows unknown YAML values to simple object mappings. */
163
+ function isRecord(value) {
164
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
165
+ }
166
+ /** Requires a non-empty string scalar. */
167
+ function isNonEmptyString(value) {
168
+ return typeof value === 'string' && Boolean(value.trim());
169
+ }
170
+ /** Validates an immutable SHA-256 image digest. */
171
+ function isDigest(value) {
172
+ return typeof value === 'string' && /^sha256:[a-f0-9]{64}$/.test(value);
39
173
  }
40
174
  exports.default = runExecutor;
@@ -6,6 +6,14 @@ export interface WriteArtifactLockExecutorSchema {
6
6
  repositoryPath: string;
7
7
  /** Dot-separated YAML path for the immutable image digest. */
8
8
  digestPath: string;
9
+ /** Dot-separated YAML path for the deployment service identity. */
10
+ servicePath: string;
11
+ /** Dot-separated YAML path for the source revision. */
12
+ sourceRevisionPath: string;
13
+ /** Deployment service identity to write. */
14
+ service: string;
15
+ /** Source revision that produced this immutable artifact. */
16
+ sourceRevision: string;
9
17
  /** Image repository to write. */
10
18
  repository: string;
11
19
  /** Immutable image digest to write. */
@@ -17,6 +17,24 @@
17
17
  "type": "string",
18
18
  "description": "Dot-separated YAML path for the immutable image digest."
19
19
  },
20
+ "servicePath": {
21
+ "type": "string",
22
+ "description": "Dot-separated YAML path for the deployment service identity."
23
+ },
24
+ "sourceRevisionPath": {
25
+ "type": "string",
26
+ "description": "Dot-separated YAML path for the source revision."
27
+ },
28
+ "service": {
29
+ "type": "string",
30
+ "description": "Deployment service identity to write.",
31
+ "minLength": 1
32
+ },
33
+ "sourceRevision": {
34
+ "type": "string",
35
+ "description": "Source revision that produced this immutable artifact.",
36
+ "minLength": 1
37
+ },
20
38
  "repository": {
21
39
  "type": "string",
22
40
  "description": "Image repository to write."
@@ -27,6 +45,6 @@
27
45
  "pattern": "^sha256:[a-f0-9]{64}$"
28
46
  }
29
47
  },
30
- "required": ["file", "repositoryPath", "digestPath", "repository", "digest"],
48
+ "required": ["file", "repositoryPath", "digestPath", "servicePath", "sourceRevisionPath", "service", "sourceRevision", "repository", "digest"],
31
49
  "additionalProperties": false
32
50
  }
@@ -1,5 +1,5 @@
1
1
  import type { PromiseExecutor } from '@nx/devkit';
2
2
  import type { WriteArtifactLockExecutorSchema } from './schema';
3
- /** Writes an immutable image reference to declared paths in an artifact lock. */
3
+ /** Writes or verifies one immutable artifact lock for a source revision. */
4
4
  declare const runExecutor: PromiseExecutor<WriteArtifactLockExecutorSchema>;
5
5
  export default runExecutor;
@@ -3,41 +3,144 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  const node_fs_1 = require("node:fs");
4
4
  const node_path_1 = require("node:path");
5
5
  const yaml_1 = require("yaml");
6
- /** Writes an immutable image reference to declared paths in an artifact lock. */
6
+ /** Writes or verifies one immutable artifact lock for a source revision. */
7
7
  const runExecutor = async (options, context) => {
8
8
  const projectRoot = context.projectsConfigurations?.projects[context.projectName ?? '']?.root;
9
9
  if (!projectRoot) {
10
10
  throw new Error('[nx-argo] Artifact locking requires an Nx project context.');
11
11
  }
12
+ if (!isNonEmptyString(options.repository)) {
13
+ throw new Error('[nx-argo] An image repository is required.');
14
+ }
12
15
  if (!/^sha256:[a-f0-9]{64}$/.test(options.digest)) {
13
16
  throw new Error('[nx-argo] An immutable sha256 image digest is required.');
14
17
  }
15
- const filePath = (0, node_path_1.resolve)(context.root, projectRoot, options.file);
16
- const lock = (0, node_fs_1.existsSync)(filePath)
17
- ? parseYaml((0, node_fs_1.readFileSync)(filePath, 'utf8'))
18
- : {};
19
- setPath(lock, options.repositoryPath, options.repository);
20
- setPath(lock, options.digestPath, options.digest);
18
+ if (!isNonEmptyString(options.service) || !isNonEmptyString(options.sourceRevision)) {
19
+ throw new Error('[nx-argo] A service and source revision are required.');
20
+ }
21
+ const root = (0, node_path_1.resolve)(context.root, projectRoot);
22
+ const filePath = resolveProjectFile(root, options.file);
23
+ if (!(0, node_fs_1.existsSync)(filePath)) {
24
+ throw new Error(`[nx-argo] Artifact lock file is missing: ${filePath}`);
25
+ }
26
+ const paths = {
27
+ repository: parsePath(options.repositoryPath),
28
+ digest: parsePath(options.digestPath),
29
+ service: parsePath(options.servicePath),
30
+ sourceRevision: parsePath(options.sourceRevisionPath),
31
+ };
32
+ assertDistinctPaths(paths);
33
+ const lock = parseYaml((0, node_fs_1.readFileSync)(filePath, 'utf8'));
34
+ const isPending = getPath(lock, ['artifact', 'pending']) === true;
35
+ if (isPending) {
36
+ validatePendingLock(lock, paths);
37
+ setPath(lock, ['artifact', 'pending'], false);
38
+ }
39
+ const existingRevision = getPath(lock, paths.sourceRevision);
40
+ if (!isPending &&
41
+ existingRevision !== undefined &&
42
+ !isNonEmptyString(existingRevision)) {
43
+ throw new Error('[nx-argo] Artifact source revision must be a string.');
44
+ }
45
+ if (!isPending && existingRevision === options.sourceRevision) {
46
+ verifyValue(lock, paths.service, options.service, 'service');
47
+ verifyValue(lock, paths.repository, options.repository, 'repository');
48
+ verifyValue(lock, paths.digest, options.digest, 'digest');
49
+ return { success: true };
50
+ }
51
+ setPath(lock, paths.repository, options.repository);
52
+ setPath(lock, paths.digest, options.digest);
53
+ setPath(lock, paths.service, options.service);
54
+ setPath(lock, paths.sourceRevision, options.sourceRevision);
21
55
  (0, node_fs_1.writeFileSync)(filePath, (0, yaml_1.stringify)(lock, { lineWidth: 0 }));
22
56
  return { success: true };
23
57
  };
24
- /** Parses a simple YAML object without accepting non-object lock roots. */
58
+ /** Resolves a required project-local file without accepting path escapes. */
59
+ function resolveProjectFile(root, file) {
60
+ if (!file.trim() || (0, node_path_1.isAbsolute)(file) || file.split(/[\\/]+/).includes('..')) {
61
+ throw new Error('[nx-argo] Artifact lock file must stay within the project root.');
62
+ }
63
+ const filePath = (0, node_path_1.resolve)(root, file);
64
+ const pathFromRoot = (0, node_path_1.relative)(root, filePath);
65
+ if (!pathFromRoot ||
66
+ pathFromRoot === '..' ||
67
+ pathFromRoot.startsWith(`..${node_path_1.sep}`) ||
68
+ (0, node_path_1.isAbsolute)(pathFromRoot)) {
69
+ throw new Error('[nx-argo] Artifact lock file must stay within the project root.');
70
+ }
71
+ return filePath;
72
+ }
73
+ /** Requires the four declared lock values to be empty before enrollment. */
74
+ function validatePendingLock(lock, paths) {
75
+ const pendingValues = [
76
+ getPath(lock, paths['repository']),
77
+ getPath(lock, paths['digest']),
78
+ getPath(lock, paths['service']),
79
+ getPath(lock, paths['sourceRevision']),
80
+ ];
81
+ if (!pendingValues.every((value) => value === '')) {
82
+ throw new Error('[nx-argo] Pending artifact locks require empty artifact values.');
83
+ }
84
+ }
85
+ /** Parses a YAML mapping without accepting malformed or empty documents. */
25
86
  function parseYaml(source) {
26
87
  const value = (0, yaml_1.parse)(source);
27
- if (value === null) {
28
- return {};
29
- }
30
- if (typeof value !== 'object' || Array.isArray(value)) {
88
+ if (value === null || typeof value !== 'object' || Array.isArray(value)) {
31
89
  throw new Error('[nx-argo] Artifact locks must contain a YAML mapping.');
32
90
  }
33
91
  return value;
34
92
  }
35
- /** Sets a dot-separated YAML mapping path. */
36
- function setPath(root, path, value) {
37
- const segments = path.split('.').filter(Boolean);
38
- if (!segments.length) {
93
+ /** Parses a dot-separated YAML mapping path. */
94
+ function parsePath(path) {
95
+ const segments = path.split('.');
96
+ if (segments.some((segment) => !segment.trim())) {
39
97
  throw new Error('[nx-argo] Artifact mapping paths must not be empty.');
40
98
  }
99
+ return segments;
100
+ }
101
+ /** Rejects equal or overlapping mapping paths before a write can corrupt data. */
102
+ function assertDistinctPaths(paths) {
103
+ const entries = [
104
+ ['repository', paths.repository],
105
+ ['digest', paths.digest],
106
+ ['service', paths.service],
107
+ ['sourceRevision', paths.sourceRevision],
108
+ ];
109
+ for (const [index, [name, path]] of entries.entries()) {
110
+ for (const [otherName, otherPath] of entries.slice(index + 1)) {
111
+ if (path.every((segment, pathIndex) => otherPath[pathIndex] === segment) ||
112
+ otherPath.every((segment, pathIndex) => path[pathIndex] === segment)) {
113
+ throw new Error(`[nx-argo] Artifact mapping paths conflict: ${name} and ${otherName}.`);
114
+ }
115
+ }
116
+ }
117
+ }
118
+ /** Reads a mapping path and reports malformed intermediate values. */
119
+ function getPath(root, path) {
120
+ let current = root;
121
+ for (const [index, segment] of path.entries()) {
122
+ const value = current[segment];
123
+ if (index === path.length - 1) {
124
+ return value;
125
+ }
126
+ if (value === undefined) {
127
+ return undefined;
128
+ }
129
+ if (!isRecord(value)) {
130
+ throw new Error(`[nx-argo] Artifact mapping path conflicts at ${segment}.`);
131
+ }
132
+ current = value;
133
+ }
134
+ return undefined;
135
+ }
136
+ /** Verifies an idempotent write against the values recorded for its revision. */
137
+ function verifyValue(lock, path, expected, label) {
138
+ if (getPath(lock, path) !== expected) {
139
+ throw new Error(`[nx-argo] Artifact ${label} conflicts with the existing source revision.`);
140
+ }
141
+ }
142
+ /** Sets a dot-separated YAML mapping path. */
143
+ function setPath(root, segments, value) {
41
144
  let current = root;
42
145
  for (const segment of segments.slice(0, -1)) {
43
146
  const child = current[segment];
@@ -53,4 +156,12 @@ function setPath(root, path, value) {
53
156
  }
54
157
  current[segments.at(-1)] = value;
55
158
  }
159
+ /** Narrows unknown YAML values to simple object mappings. */
160
+ function isRecord(value) {
161
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
162
+ }
163
+ /** Requires a non-empty string option. */
164
+ function isNonEmptyString(value) {
165
+ return typeof value === 'string' && Boolean(value.trim());
166
+ }
56
167
  exports.default = runExecutor;
@@ -0,0 +1,4 @@
1
+ import { type Tree } from '@nx/devkit';
2
+ import type { EnvironmentProjectGeneratorSchema } from './schema';
3
+ /** Creates a GitOps project boundary for one service environment. */
4
+ export default function environmentProjectGenerator(tree: Tree, options: EnvironmentProjectGeneratorSchema): Promise<void>;