@intentius/chant-lexicon-k8s 0.107.1 → 0.108.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (57) hide show
  1. package/dist/config-schema.d.ts +115 -1
  2. package/dist/config-schema.d.ts.map +1 -1
  3. package/dist/config.d.ts +58 -3
  4. package/dist/config.d.ts.map +1 -1
  5. package/dist/crd/loader.d.ts +4 -0
  6. package/dist/crd/loader.d.ts.map +1 -1
  7. package/dist/crd/parser.d.ts +5 -0
  8. package/dist/crd/parser.d.ts.map +1 -1
  9. package/dist/crd/project-codegen.d.ts +33 -0
  10. package/dist/crd/project-codegen.d.ts.map +1 -0
  11. package/dist/include/entity.d.ts +73 -0
  12. package/dist/include/entity.d.ts.map +1 -0
  13. package/dist/include/resolve.d.ts +29 -0
  14. package/dist/include/resolve.d.ts.map +1 -0
  15. package/dist/index.d.ts +7 -0
  16. package/dist/index.d.ts.map +1 -1
  17. package/dist/integrity.json +3 -3
  18. package/dist/kustomize/rendered-entity.d.ts +15 -1
  19. package/dist/kustomize/rendered-entity.d.ts.map +1 -1
  20. package/dist/kustomize/root.d.ts +11 -2
  21. package/dist/kustomize/root.d.ts.map +1 -1
  22. package/dist/lint/post-synth/crd-schema-helpers.d.ts +5 -1
  23. package/dist/lint/post-synth/crd-schema-helpers.d.ts.map +1 -1
  24. package/dist/manifest.json +1 -1
  25. package/dist/patch/json-patch.d.ts +51 -0
  26. package/dist/patch/json-patch.d.ts.map +1 -0
  27. package/dist/patch/rendered-patch.d.ts +90 -0
  28. package/dist/patch/rendered-patch.d.ts.map +1 -0
  29. package/dist/plugin.d.ts.map +1 -1
  30. package/dist/project-kinds.d.ts +46 -0
  31. package/dist/project-kinds.d.ts.map +1 -0
  32. package/dist/rules/crd-schema-helpers.ts +10 -2
  33. package/dist/serializer.d.ts.map +1 -1
  34. package/package.json +3 -3
  35. package/src/config-augmentation.test.ts +28 -0
  36. package/src/config-schema.ts +47 -1
  37. package/src/config.ts +44 -3
  38. package/src/crd/loader.ts +1 -1
  39. package/src/crd/parser.ts +9 -5
  40. package/src/crd/project-codegen.test.ts +239 -0
  41. package/src/crd/project-codegen.ts +327 -0
  42. package/src/include/entity.ts +119 -0
  43. package/src/include/include.test.ts +345 -0
  44. package/src/include/resolve.ts +204 -0
  45. package/src/index.ts +23 -0
  46. package/src/kustomize/rendered-entity.ts +43 -1
  47. package/src/kustomize/root.test.ts +39 -0
  48. package/src/kustomize/root.ts +16 -30
  49. package/src/lint/post-synth/crd-schema-helpers.ts +10 -2
  50. package/src/patch/json-patch.test.ts +91 -0
  51. package/src/patch/json-patch.ts +189 -0
  52. package/src/patch/rendered-patch.test.ts +143 -0
  53. package/src/patch/rendered-patch.ts +180 -0
  54. package/src/plugin.ts +16 -2
  55. package/src/project-kinds.ts +75 -0
  56. package/src/serializer.ts +10 -0
  57. package/src/testdata/include/bundle.yaml +45 -0
@@ -0,0 +1,180 @@
1
+ /**
2
+ * Patching rendered documents (#3566 item 3).
3
+ *
4
+ * A Helm render, a kustomize build root and a `k8sInclude` all hand chant
5
+ * finished manifests. When a chart or an upstream bundle does not expose a
6
+ * field, the alternatives were forking it or running an overlay outside
7
+ * chant. A `RenderedPatch` selects documents by kind and name (namespace and
8
+ * apiVersion optional) and changes them before they become entities, so the
9
+ * patched form is what the serializer emits, what ownership stamping and
10
+ * post-synth checks see, and what `lifecycle diff --live` compares against
11
+ * the cluster.
12
+ *
13
+ * One patch type for all three sources: `HelmRender({ patches })`,
14
+ * `k8sInclude({ patches })`, and `{ path, patches }` entries in
15
+ * `k8s.kustomize.roots`. Each source calls {@link applyRenderedPatches} on
16
+ * its parsed documents.
17
+ *
18
+ * A selector that matches nothing is an error. The common way to get there
19
+ * is a chart upgrade that renamed a resource, and a patch that silently
20
+ * stops applying is the failure this guards against. There is no opt-out:
21
+ * a patch whose target is legitimately absent (a chart value that turns a
22
+ * resource off) belongs behind the same condition in TypeScript that sets
23
+ * the value.
24
+ */
25
+ // The generated declaration file carries the real constructor props;
26
+ // `../generated/index` resolves to the runtime classes, which take
27
+ // `Record<string, unknown>`. The lexicon build copies the declaration file
28
+ // next to the emitted types (see composites/member-defaults.ts).
29
+ import type * as Generated from "../generated/index.d";
30
+ import { applyJsonPatch, applyMergePatch, type JsonPatchOperation } from "./json-patch";
31
+
32
+ export type { JsonPatchOperation } from "./json-patch";
33
+ export { applyJsonPatch, applyMergePatch } from "./json-patch";
34
+
35
+ /** Which rendered documents a patch applies to. */
36
+ export interface RenderedSelector<K extends string = string> {
37
+ /** The document's `kind`, e.g. `"Deployment"`. */
38
+ kind: K;
39
+ /** The document's `metadata.name`. */
40
+ name: string;
41
+ /** The document's `metadata.namespace`. Omitted, documents in any namespace (or none) match. */
42
+ namespace?: string;
43
+ /** The document's `apiVersion`, for a kind name two API groups share. */
44
+ apiVersion?: string;
45
+ }
46
+
47
+ /**
48
+ * The constructor props of the lexicon's generated class named `K`, when
49
+ * there is one; otherwise an open record. Merge patches for known kinds are
50
+ * checked against it.
51
+ */
52
+ export type KindProps<K extends string> = K extends keyof typeof Generated
53
+ ? (typeof Generated)[K] extends abstract new (props: infer P) => unknown
54
+ ? P
55
+ : Record<string, unknown>
56
+ : Record<string, unknown>;
57
+
58
+ /**
59
+ * An RFC 7386 merge patch over `T`: object fields are optional at every
60
+ * depth and may be `null` (which deletes them); arrays replace the target
61
+ * whole, so their elements stay complete.
62
+ */
63
+ export type MergePatchOf<T> = T extends readonly unknown[]
64
+ ? T
65
+ : T extends object
66
+ ? { [P in keyof T]?: MergePatchOf<T[P]> | null }
67
+ : T;
68
+
69
+ /** A patch applied as RFC 6902 operations. */
70
+ export interface RenderedJsonPatch<K extends string = string> extends RenderedSelector<K> {
71
+ jsonPatch: JsonPatchOperation[];
72
+ merge?: never;
73
+ }
74
+
75
+ /** A patch applied as an RFC 7386 merge. */
76
+ export interface RenderedMergePatch<K extends string = string> extends RenderedSelector<K> {
77
+ merge: MergePatchOf<KindProps<K>>;
78
+ jsonPatch?: never;
79
+ }
80
+
81
+ /** One patch on rendered output: a selector plus either `jsonPatch` or `merge`. */
82
+ export type RenderedPatch<K extends string = string> = RenderedJsonPatch<K> | RenderedMergePatch<K>;
83
+
84
+ /**
85
+ * Identity helper that infers `kind`, so a `merge` body is checked against
86
+ * that kind's props:
87
+ *
88
+ * ```ts
89
+ * renderedPatch({ kind: "Deployment", name: "web", merge: { spec: { replicas: 3 } } })
90
+ * ```
91
+ *
92
+ * A plain object literal works anywhere a `RenderedPatch` is taken; it just
93
+ * types `merge` as an open record.
94
+ */
95
+ export function renderedPatch<K extends string>(patch: RenderedPatch<K>): RenderedPatch {
96
+ return patch as unknown as RenderedPatch;
97
+ }
98
+
99
+ function describeSelector(sel: RenderedSelector): string {
100
+ const parts = [`kind ${sel.kind}`, `name ${sel.name}`];
101
+ if (sel.namespace !== undefined) parts.push(`namespace ${sel.namespace}`);
102
+ if (sel.apiVersion !== undefined) parts.push(`apiVersion ${sel.apiVersion}`);
103
+ return parts.join(", ");
104
+ }
105
+
106
+ function metadataOf(doc: Record<string, unknown>): Record<string, unknown> {
107
+ const m = doc.metadata;
108
+ return typeof m === "object" && m !== null && !Array.isArray(m) ? (m as Record<string, unknown>) : {};
109
+ }
110
+
111
+ function matches(doc: Record<string, unknown>, sel: RenderedSelector): boolean {
112
+ if (doc.kind !== sel.kind) return false;
113
+ if (sel.apiVersion !== undefined && doc.apiVersion !== sel.apiVersion) return false;
114
+ const metadata = metadataOf(doc);
115
+ if (metadata.name !== sel.name) return false;
116
+ if (sel.namespace !== undefined && metadata.namespace !== sel.namespace) return false;
117
+ return true;
118
+ }
119
+
120
+ /**
121
+ * Apply `patches` in order to `docs` and return the patched documents, in
122
+ * the same order. `source` names where the documents came from (a chart, a
123
+ * file, a URL, an overlay dir) and leads every error message.
124
+ *
125
+ * Each patch applies to every document its selector matches at that point,
126
+ * so a later patch sees an earlier one's changes. Throws when a selector
127
+ * matches nothing, when an operation fails (a `test` included), when a patch
128
+ * carries both or neither of `jsonPatch` and `merge`, and when a patched
129
+ * document no longer has a string `apiVersion` and `kind`.
130
+ */
131
+ export function applyRenderedPatches(
132
+ docs: ReadonlyArray<Record<string, unknown>>,
133
+ patches: ReadonlyArray<RenderedPatch> | undefined,
134
+ source: string,
135
+ ): Array<Record<string, unknown>> {
136
+ const out = [...docs];
137
+ if (!patches || patches.length === 0) return out;
138
+
139
+ patches.forEach((patch, p) => {
140
+ const where = `${source}: patch ${p} (${describeSelector(patch)})`;
141
+ const hasJson = patch.jsonPatch !== undefined;
142
+ const hasMerge = patch.merge !== undefined;
143
+ if (hasJson === hasMerge) {
144
+ throw new Error(`${where} must set exactly one of jsonPatch and merge`);
145
+ }
146
+
147
+ let matched = 0;
148
+ for (let i = 0; i < out.length; i++) {
149
+ if (!matches(out[i], patch)) continue;
150
+ matched++;
151
+ let next: Record<string, unknown>;
152
+ try {
153
+ next = hasJson ? applyJsonPatch(out[i], patch.jsonPatch!) : applyMergePatch(out[i], patch.merge);
154
+ } catch (err) {
155
+ throw new Error(`${where}: ${err instanceof Error ? err.message : String(err)}`);
156
+ }
157
+ if (typeof next !== "object" || next === null || typeof next.apiVersion !== "string" || typeof next.kind !== "string") {
158
+ throw new Error(`${where} left a document without a string apiVersion and kind`);
159
+ }
160
+ out[i] = next;
161
+ }
162
+
163
+ if (matched === 0) {
164
+ const sameKind = out
165
+ .filter((d) => d.kind === patch.kind)
166
+ .map((d) => {
167
+ const m = metadataOf(d);
168
+ return typeof m.namespace === "string" ? `${m.namespace}/${String(m.name)}` : String(m.name);
169
+ });
170
+ throw new Error(
171
+ `${where} matched no document. ` +
172
+ (sameKind.length > 0
173
+ ? `${patch.kind} documents present: ${sameKind.join(", ")}.`
174
+ : `There are no ${patch.kind} documents.`),
175
+ );
176
+ }
177
+ });
178
+
179
+ return out;
180
+ }
package/src/plugin.ts CHANGED
@@ -34,6 +34,8 @@ import { k8sConfigSchema } from "./config-schema";
34
34
  import type { K8sChantConfig } from "./config";
35
35
  import { renderKustomizeRoots } from "./kustomize/root";
36
36
  import { encryptedSecretBuildRoot } from "./sops/encrypted-secret-file";
37
+ import { k8sProjectCodegen } from "./crd/project-codegen";
38
+ import { includeBuildRoot } from "./include/resolve";
37
39
  import type { Declarable } from "@intentius/chant/declarable";
38
40
 
39
41
  export const k8sPlugin: LexiconPlugin = {
@@ -78,6 +80,13 @@ export const k8sPlugin: LexiconPlugin = {
78
80
  return postSynthCheckList;
79
81
  },
80
82
 
83
+ // Typed classes for the project's own CRDs (`k8s.crds`), written by
84
+ // `chant generate` and checked for drift by every build. See
85
+ // ./crd/project-codegen.ts.
86
+ projectCodegen() {
87
+ return k8sProjectCodegen();
88
+ },
89
+
81
90
  // #1548 piece 3 — kustomization dirs declared as build roots. Each entry in
82
91
  // `k8s.kustomize.roots` renders at build time (same injectable runner as
83
92
  // the kustomize-apply capability: `kustomize build`, `kubectl kustomize`
@@ -87,8 +96,10 @@ export const k8sPlugin: LexiconPlugin = {
87
96
  //
88
97
  // The same hook also resolves committed-encrypted `declareSecret()`
89
98
  // declarations: it reads the ciphertext each one names and contributes it
90
- // as a verbatim sidecar entity (see ./sops/encrypted-secret-file.ts). Both
91
- // halves are one filesystem read at the one sanctioned impure seam.
99
+ // as a verbatim sidecar entity (see ./sops/encrypted-secret-file.ts), and
100
+ // `k8sInclude()` declarations: it reads or fetches each declared YAML and
101
+ // contributes its documents as verbatim manifest entities (see
102
+ // ./include/resolve.ts). All three read at the one sanctioned impure seam.
92
103
  async buildRoots(ctx) {
93
104
  const entities = new Map<string, Declarable>();
94
105
  const warnings: string[] = [];
@@ -100,6 +111,9 @@ export const k8sPlugin: LexiconPlugin = {
100
111
  warnings.push(...rendered.warnings);
101
112
  }
102
113
 
114
+ const included = await includeBuildRoot(ctx);
115
+ for (const [name, entity] of included.entities) entities.set(name, entity);
116
+
103
117
  const encrypted = await encryptedSecretBuildRoot(ctx);
104
118
  for (const [name, entity] of encrypted.entities) entities.set(name, entity);
105
119
  warnings.push(...(encrypted.warnings ?? []));
@@ -0,0 +1,75 @@
1
+ /**
2
+ * Kinds a project generated for itself with `chant generate` from `k8s.crds`
3
+ * (./crd/project-codegen.ts), as opposed to the kinds the lexicon ships in
4
+ * `generated/lexicon-k8s.json`.
5
+ *
6
+ * The serializer's GVK lookup and the CRD spec checks (WK8501/WK8502) consult
7
+ * this registry before the packaged JSON. Entries arrive two ways:
8
+ *
9
+ * - The generated module registers its kinds (type and GVK) when it is
10
+ * imported, so a project's own tests that construct and serialize a
11
+ * resource need nothing else.
12
+ * - A build registers every kind, spec schema included, from the committed
13
+ * `kinds.json` beside the module before it serializes (the plugin's
14
+ * `projectCodegen().load`). That covers a build whose discovery imported the
15
+ * module somewhere else, such as the sandboxed child process.
16
+ *
17
+ * The store hangs off `globalThis` under a registered symbol, so two copies
18
+ * of this module (the plugin the CLI loaded and the one a project's import
19
+ * resolved) share it. No Node imports: the post-synth barrel reaches this
20
+ * through ./lint/post-synth/crd-schema-helpers.ts and must stay edge-safe.
21
+ */
22
+
23
+ import type { CrdFieldSchema } from "./spec/parse";
24
+
25
+ /** One project-generated kind. */
26
+ export interface ProjectKind {
27
+ /** The entity type the generated class constructs, e.g. `K8s::Example::Widget`. */
28
+ resourceType: string;
29
+ /** e.g. `example.com/v1`. */
30
+ apiVersion: string;
31
+ /** e.g. `Widget`. */
32
+ kind: string;
33
+ /** The CRD's `spec` field schema, for the spec checks. */
34
+ specSchema?: CrdFieldSchema;
35
+ }
36
+
37
+ const STORE = Symbol.for("@intentius/chant-lexicon-k8s/project-kinds");
38
+
39
+ function store(): Map<string, ProjectKind> {
40
+ const g = globalThis as { [STORE]?: Map<string, ProjectKind> };
41
+ g[STORE] ??= new Map();
42
+ return g[STORE];
43
+ }
44
+
45
+ /**
46
+ * Register project-generated kinds. A later registration of the same type
47
+ * replaces the earlier one, keeping its spec schema when the new entry has
48
+ * none (the module's import-time registration carries no schema).
49
+ */
50
+ export function registerProjectKinds(kinds: readonly ProjectKind[]): void {
51
+ const s = store();
52
+ for (const k of kinds) {
53
+ const previous = s.get(k.resourceType);
54
+ const specSchema = k.specSchema ?? (previous?.apiVersion === k.apiVersion && previous.kind === k.kind ? previous.specSchema : undefined);
55
+ s.set(k.resourceType, { ...k, ...(specSchema ? { specSchema } : {}) });
56
+ }
57
+ }
58
+
59
+ /** The project kind an entity type constructs, if a project registered one. */
60
+ export function projectKindForType(resourceType: string): ProjectKind | undefined {
61
+ return store().get(resourceType);
62
+ }
63
+
64
+ /** The spec schema a project registered for `apiVersion`/`kind`, if any. */
65
+ export function projectSpecSchema(apiVersion: string, kind: string): CrdFieldSchema | undefined {
66
+ for (const k of store().values()) {
67
+ if (k.apiVersion === apiVersion && k.kind === kind && k.specSchema) return k.specSchema;
68
+ }
69
+ return undefined;
70
+ }
71
+
72
+ /** Test seam: forget every registered kind. */
73
+ export function clearProjectKinds(): void {
74
+ store().clear();
75
+ }
package/src/serializer.ts CHANGED
@@ -32,7 +32,9 @@ import { walkValue, type SerializerVisitor } from "@intentius/chant/serializer-w
32
32
  import { emitYAML } from "@intentius/chant/yaml";
33
33
  import { isDefaultLabels, isDefaultAnnotations, type DefaultLabels, type DefaultAnnotations } from "./default-labels";
34
34
  import { isRenderedManifestEntity } from "./manifest-entity";
35
+ import { projectKindForType } from "./project-kinds";
35
36
  import { isEncryptedSecretFileEntity } from "./sops/entity";
37
+ import { isK8sInclude } from "./include/entity";
36
38
  import { isRuleGroup, ruleGroupConfig } from "@intentius/chant-lexicon-prometheus";
37
39
 
38
40
  const require = createRequire(import.meta.url);
@@ -82,6 +84,11 @@ function getGVKMap(): Record<string, GVKEntry> {
82
84
  * Resolve entityType to apiVersion and kind.
83
85
  */
84
86
  function resolveGVK(entityType: string): { apiVersion: string; kind: string } | null {
87
+ // A kind the project generated from its own CRDs (`chant generate`) wins
88
+ // over the packaged map, which knows nothing of it or an older version.
89
+ const projectKind = projectKindForType(entityType);
90
+ if (projectKind) return { apiVersion: projectKind.apiVersion, kind: projectKind.kind };
91
+
85
92
  const gvkMap = getGVKMap();
86
93
 
87
94
  // Search for matching entry by resourceType
@@ -420,6 +427,9 @@ export const k8sSerializer: Serializer = {
420
427
  for (const [name, entity] of entities) {
421
428
  if (isPropertyDeclarable(entity)) continue;
422
429
  if (isDefaultLabels(entity) || isDefaultAnnotations(entity)) continue;
430
+ // A `k8sInclude` declaration is resolved into its documents at
431
+ // `buildRoots()`; the declaration itself emits nothing.
432
+ if (isK8sInclude(entity)) continue;
423
433
 
424
434
  // Committed SOPS ciphertext (epic lex00/iac-cd-bench#6) leaves as a
425
435
  // SIDECAR and never as a document in the primary output. That is the
@@ -0,0 +1,45 @@
1
+ # A vendored operator bundle, as an upstream release would publish it.
2
+ ---
3
+ apiVersion: v1
4
+ kind: Namespace
5
+ metadata:
6
+ name: widget-system
7
+ ---
8
+ ---
9
+ apiVersion: v1
10
+ kind: ConfigMap
11
+ metadata:
12
+ name: widget-config
13
+ namespace: widget-system
14
+ data:
15
+ level: info
16
+ ---
17
+ apiVersion: v1
18
+ kind: ConfigMap
19
+ metadata:
20
+ name: widget-config
21
+ namespace: widget-edge
22
+ data:
23
+ level: debug
24
+ ---
25
+ apiVersion: apps/v1
26
+ kind: Deployment
27
+ metadata:
28
+ name: widget-controller
29
+ namespace: widget-system
30
+ spec:
31
+ replicas: 1
32
+ selector:
33
+ matchLabels:
34
+ app: widget-controller
35
+ template:
36
+ metadata:
37
+ labels:
38
+ app: widget-controller
39
+ spec:
40
+ containers:
41
+ - name: manager
42
+ image: example.com/widget-controller:v0.4.1
43
+ env:
44
+ - name: API_TOKEN
45
+ value: not-a-real-token