@intentius/chant-lexicon-k8s 0.106.4 → 0.108.0

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 (167) hide show
  1. package/dist/codegen/naming.d.ts.map +1 -1
  2. package/dist/composites/catalog.d.ts.map +1 -1
  3. package/dist/composites/index.d.ts +2 -0
  4. package/dist/composites/index.d.ts.map +1 -1
  5. package/dist/composites/otel-collector-shape.d.ts +2 -0
  6. package/dist/composites/otel-collector-shape.d.ts.map +1 -1
  7. package/dist/composites/otel-operator-collector.d.ts +101 -0
  8. package/dist/composites/otel-operator-collector.d.ts.map +1 -0
  9. package/dist/config-schema.d.ts +115 -1
  10. package/dist/config-schema.d.ts.map +1 -1
  11. package/dist/config.d.ts +58 -3
  12. package/dist/config.d.ts.map +1 -1
  13. package/dist/crd/crd-sources.d.ts.map +1 -1
  14. package/dist/crd/loader.d.ts +4 -0
  15. package/dist/crd/loader.d.ts.map +1 -1
  16. package/dist/crd/parser.d.ts +5 -0
  17. package/dist/crd/parser.d.ts.map +1 -1
  18. package/dist/crd/project-codegen.d.ts +33 -0
  19. package/dist/crd/project-codegen.d.ts.map +1 -0
  20. package/dist/generated/index.d.d.ts +172 -2
  21. package/dist/generated/index.d.ts +301 -0
  22. package/dist/generated/index.d.ts.map +1 -1
  23. package/dist/group-namespace.d.ts.map +1 -1
  24. package/dist/import/embedded.d.ts +3 -0
  25. package/dist/import/embedded.d.ts.map +1 -1
  26. package/dist/include/entity.d.ts +73 -0
  27. package/dist/include/entity.d.ts.map +1 -0
  28. package/dist/include/resolve.d.ts +29 -0
  29. package/dist/include/resolve.d.ts.map +1 -0
  30. package/dist/index.d.ts +9 -2
  31. package/dist/index.d.ts.map +1 -1
  32. package/dist/integrity.json +17 -10
  33. package/dist/kustomize/rendered-entity.d.ts +15 -1
  34. package/dist/kustomize/rendered-entity.d.ts.map +1 -1
  35. package/dist/kustomize/root.d.ts +11 -2
  36. package/dist/kustomize/root.d.ts.map +1 -1
  37. package/dist/lint/audit-catalog.d.ts.map +1 -1
  38. package/dist/lint/post-synth/crd-schema-helpers.d.ts +5 -1
  39. package/dist/lint/post-synth/crd-schema-helpers.d.ts.map +1 -1
  40. package/dist/lint/post-synth/index.d.ts.map +1 -1
  41. package/dist/lint/post-synth/monitoring-selection-helpers.d.ts +55 -0
  42. package/dist/lint/post-synth/monitoring-selection-helpers.d.ts.map +1 -0
  43. package/dist/lint/post-synth/otel-placement-helpers.d.ts +16 -0
  44. package/dist/lint/post-synth/otel-placement-helpers.d.ts.map +1 -1
  45. package/dist/lint/post-synth/wk8604.d.ts +6 -0
  46. package/dist/lint/post-synth/wk8604.d.ts.map +1 -1
  47. package/dist/lint/post-synth/wk8605.d.ts.map +1 -1
  48. package/dist/lint/post-synth/wk8606.d.ts +17 -0
  49. package/dist/lint/post-synth/wk8606.d.ts.map +1 -0
  50. package/dist/lint/post-synth/wk8701.d.ts +17 -0
  51. package/dist/lint/post-synth/wk8701.d.ts.map +1 -0
  52. package/dist/lint/post-synth/wk8702.d.ts +17 -0
  53. package/dist/lint/post-synth/wk8702.d.ts.map +1 -0
  54. package/dist/lint/post-synth/wk8703.d.ts +17 -0
  55. package/dist/lint/post-synth/wk8703.d.ts.map +1 -0
  56. package/dist/lint/post-synth/wk8704.d.ts +21 -0
  57. package/dist/lint/post-synth/wk8704.d.ts.map +1 -0
  58. package/dist/lint/post-synth/wk8705.d.ts +18 -0
  59. package/dist/lint/post-synth/wk8705.d.ts.map +1 -0
  60. package/dist/manifest.json +1 -1
  61. package/dist/meta.json +2284 -370
  62. package/dist/okf/index.md +20 -1
  63. package/dist/okf/rules/WK8604.md +6 -2
  64. package/dist/okf/rules/WK8605.md +4 -0
  65. package/dist/okf/rules/WK8606.md +15 -0
  66. package/dist/okf/rules/WK8701.md +18 -0
  67. package/dist/okf/rules/WK8702.md +20 -0
  68. package/dist/okf/rules/WK8703.md +17 -0
  69. package/dist/okf/rules/WK8704.md +22 -0
  70. package/dist/okf/rules/WK8705.md +18 -0
  71. package/dist/okf/types/Alertmanager.md +18 -0
  72. package/dist/okf/types/AlertmanagerConfig.md +18 -0
  73. package/dist/okf/types/ClusterObservability.md +14 -0
  74. package/dist/okf/types/CronJob.md +1 -0
  75. package/dist/okf/types/DaemonSet.md +1 -0
  76. package/dist/okf/types/Instrumentation.md +14 -0
  77. package/dist/okf/types/MonitoringProbe.md +14 -0
  78. package/dist/okf/types/Namespace.md +3 -0
  79. package/dist/okf/types/OpAMPBridge.md +14 -0
  80. package/dist/okf/types/OpenTelemetryCollector.md +19 -0
  81. package/dist/okf/types/Pod.md +1 -0
  82. package/dist/okf/types/PodMonitor.md +20 -0
  83. package/dist/okf/types/Prometheus.md +21 -0
  84. package/dist/okf/types/PrometheusAgent.md +18 -0
  85. package/dist/okf/types/PrometheusRule.md +6 -1
  86. package/dist/okf/types/ScrapeConfig.md +19 -0
  87. package/dist/okf/types/Service.md +1 -0
  88. package/dist/okf/types/ServiceMonitor.md +7 -1
  89. package/dist/okf/types/StatefulSet.md +1 -0
  90. package/dist/okf/types/TargetAllocator.md +14 -0
  91. package/dist/okf/types/ThanosRuler.md +18 -0
  92. package/dist/patch/json-patch.d.ts +51 -0
  93. package/dist/patch/json-patch.d.ts.map +1 -0
  94. package/dist/patch/rendered-patch.d.ts +90 -0
  95. package/dist/patch/rendered-patch.d.ts.map +1 -0
  96. package/dist/plugin.d.ts.map +1 -1
  97. package/dist/project-kinds.d.ts +46 -0
  98. package/dist/project-kinds.d.ts.map +1 -0
  99. package/dist/rules/crd-schema-helpers.ts +10 -2
  100. package/dist/rules/monitoring-selection-helpers.ts +185 -0
  101. package/dist/rules/otel-placement-helpers.ts +61 -1
  102. package/dist/rules/wk8601.ts +1 -1
  103. package/dist/rules/wk8603.ts +1 -1
  104. package/dist/rules/wk8604.ts +8 -2
  105. package/dist/rules/wk8605.ts +5 -3
  106. package/dist/rules/wk8606.ts +27 -0
  107. package/dist/rules/wk8701.ts +37 -0
  108. package/dist/rules/wk8702.ts +43 -0
  109. package/dist/rules/wk8703.ts +37 -0
  110. package/dist/rules/wk8704.ts +134 -0
  111. package/dist/rules/wk8705.ts +45 -0
  112. package/dist/serializer.d.ts.map +1 -1
  113. package/dist/types/index.d.ts +172 -2
  114. package/package.json +3 -3
  115. package/src/codegen/naming.ts +15 -1
  116. package/src/composites/catalog.ts +105 -0
  117. package/src/composites/index.ts +2 -0
  118. package/src/composites/otel-collector-shape.ts +2 -0
  119. package/src/composites/otel-operator-collector.test.ts +267 -0
  120. package/src/composites/otel-operator-collector.ts +221 -0
  121. package/src/config-augmentation.test.ts +28 -0
  122. package/src/config-schema.ts +47 -1
  123. package/src/config.ts +44 -3
  124. package/src/crd/crd-sources.ts +41 -2
  125. package/src/crd/loader.ts +1 -1
  126. package/src/crd/parser.ts +9 -5
  127. package/src/crd/project-codegen.test.ts +239 -0
  128. package/src/crd/project-codegen.ts +327 -0
  129. package/src/generated/index.d.ts +172 -2
  130. package/src/generated/index.ts +303 -2
  131. package/src/generated/lexicon-k8s.json +2284 -370
  132. package/src/generated/operations.json +208 -0
  133. package/src/group-namespace.test.ts +4 -0
  134. package/src/group-namespace.ts +4 -0
  135. package/src/import/embedded.ts +26 -0
  136. package/src/import/operator-collector-roundtrip.test.ts +105 -0
  137. package/src/include/entity.ts +119 -0
  138. package/src/include/include.test.ts +345 -0
  139. package/src/include/resolve.ts +204 -0
  140. package/src/index.ts +25 -2
  141. package/src/kustomize/rendered-entity.ts +43 -1
  142. package/src/kustomize/root.test.ts +39 -0
  143. package/src/kustomize/root.ts +16 -30
  144. package/src/lint/audit-catalog.ts +6 -0
  145. package/src/lint/post-synth/crd-schema-helpers.ts +10 -2
  146. package/src/lint/post-synth/index.ts +12 -0
  147. package/src/lint/post-synth/monitoring-selection-helpers.ts +185 -0
  148. package/src/lint/post-synth/monitoring-selection.test.ts +316 -0
  149. package/src/lint/post-synth/otel-placement-helpers.ts +61 -1
  150. package/src/lint/post-synth/wk8601.ts +1 -1
  151. package/src/lint/post-synth/wk8603.ts +1 -1
  152. package/src/lint/post-synth/wk8604.ts +8 -2
  153. package/src/lint/post-synth/wk8605.ts +5 -3
  154. package/src/lint/post-synth/wk8606.ts +27 -0
  155. package/src/lint/post-synth/wk8701.ts +37 -0
  156. package/src/lint/post-synth/wk8702.ts +43 -0
  157. package/src/lint/post-synth/wk8703.ts +37 -0
  158. package/src/lint/post-synth/wk8704.ts +134 -0
  159. package/src/lint/post-synth/wk8705.ts +45 -0
  160. package/src/patch/json-patch.test.ts +91 -0
  161. package/src/patch/json-patch.ts +189 -0
  162. package/src/patch/rendered-patch.test.ts +143 -0
  163. package/src/patch/rendered-patch.ts +180 -0
  164. package/src/plugin.ts +16 -2
  165. package/src/project-kinds.ts +75 -0
  166. package/src/serializer.ts +10 -0
  167. package/src/testdata/include/bundle.yaml +45 -0
@@ -20,12 +20,57 @@ export const k8sClusterProfileSchema = z.strictObject({
20
20
  context: z.string(),
21
21
  });
22
22
 
23
+ const kinds = z.array(z.string().min(1)).optional();
24
+
25
+ /** A `k8s.crds` entry. Remote sources must carry their pin. */
26
+ export const k8sProjectCrdSourceSchema = z.discriminatedUnion("type", [
27
+ z.strictObject({ type: z.literal("file"), path: z.string().min(1), kinds }),
28
+ z.strictObject({
29
+ type: z.literal("url"),
30
+ url: z.string().url(),
31
+ sha256: z.string().regex(/^(sha256:)?[0-9a-f]{64}$/, "must be the hex sha256 of the URL's content"),
32
+ kinds,
33
+ }),
34
+ z.strictObject({
35
+ type: z.literal("helm"),
36
+ chart: z.string().min(1),
37
+ version: z.string().min(1),
38
+ digest: z.string().optional(),
39
+ chartSubdir: z.string().optional(),
40
+ kinds,
41
+ }),
42
+ ]);
43
+
44
+ const jsonPatchOperationSchema = z.discriminatedUnion("op", [
45
+ z.strictObject({ op: z.literal("add"), path: z.string(), value: z.unknown() }),
46
+ z.strictObject({ op: z.literal("remove"), path: z.string() }),
47
+ z.strictObject({ op: z.literal("replace"), path: z.string(), value: z.unknown() }),
48
+ z.strictObject({ op: z.literal("move"), from: z.string(), path: z.string() }),
49
+ z.strictObject({ op: z.literal("copy"), from: z.string(), path: z.string() }),
50
+ z.strictObject({ op: z.literal("test"), path: z.string(), value: z.unknown() }),
51
+ ]);
52
+
53
+ const renderedSelectorShape = {
54
+ kind: z.string().min(1),
55
+ name: z.string().min(1),
56
+ namespace: z.string().optional(),
57
+ apiVersion: z.string().optional(),
58
+ };
59
+
60
+ /** A `RenderedPatch` (#3566): a selector plus exactly one of `jsonPatch` and `merge`. */
61
+ export const renderedPatchSchema = z.union([
62
+ z.strictObject({ ...renderedSelectorShape, jsonPatch: z.array(jsonPatchOperationSchema), merge: z.never().optional() }),
63
+ z.strictObject({ ...renderedSelectorShape, merge: z.record(z.string(), z.unknown()), jsonPatch: z.never().optional() }),
64
+ ]);
65
+
23
66
  export const k8sConfigSchema = z.strictObject({
24
67
  profiles: z.record(z.string(), k8sClusterProfileSchema).optional(),
25
68
  execCredentialPlugins: z.array(z.string()).optional(),
26
69
  kustomize: z
27
70
  .strictObject({
28
- roots: z.array(z.string()).optional(),
71
+ roots: z
72
+ .array(z.union([z.string(), z.strictObject({ path: z.string(), patches: z.array(renderedPatchSchema).optional() })]))
73
+ .optional(),
29
74
  })
30
75
  .optional(),
31
76
  receipts: z
@@ -33,6 +78,7 @@ export const k8sConfigSchema = z.strictObject({
33
78
  namespace: z.string().optional(),
34
79
  })
35
80
  .optional(),
81
+ crds: z.array(k8sProjectCrdSourceSchema).optional(),
36
82
  });
37
83
 
38
84
  declare module "@intentius/chant/config" {
package/src/config.ts CHANGED
@@ -58,6 +58,7 @@
58
58
  */
59
59
 
60
60
  import type { ChantConfig } from "@intentius/chant/config";
61
+ import type { RenderedPatch } from "./patch/rendered-patch";
61
62
 
62
63
  /** A single environment's cluster binding. */
63
64
  export interface K8sClusterProfile {
@@ -101,15 +102,23 @@ export interface K8sChantConfig {
101
102
  * `chant.config.*`), NOT `sourceDir` — the overlay tree usually lives
102
103
  * beside the typed source, not inside it.
103
104
  *
105
+ * An entry may also be `{ path, patches }`: the patches apply to the
106
+ * rendered documents before they become entities (see `RenderedPatch`).
107
+ *
104
108
  * ```ts
105
109
  * k8s: {
106
- * kustomize: { roots: ["overlays/prod"] },
110
+ * kustomize: {
111
+ * roots: [
112
+ * "overlays/prod",
113
+ * { path: "overlays/edge", patches: [{ kind: "Deployment", name: "web", merge: { spec: { replicas: 2 } } }] },
114
+ * ],
115
+ * },
107
116
  * } satisfies K8sChantConfig
108
117
  * ```
109
118
  */
110
119
  kustomize?: {
111
- /** Kustomization directories to render into the build. */
112
- roots?: string[];
120
+ /** Kustomization directories to render into the build, optionally with patches. */
121
+ roots?: Array<string | { path: string; patches?: RenderedPatch[] }>;
113
122
  };
114
123
 
115
124
  /**
@@ -134,8 +143,40 @@ export interface K8sChantConfig {
134
143
  /** Namespace the receipt ConfigMaps live in. Defaults to `default`. */
135
144
  namespace?: string;
136
145
  };
146
+
147
+ /**
148
+ * CRDs this project generates typed classes from, with `chant generate`.
149
+ *
150
+ * Each source is a CRD file in the repo, a pinned URL, or a pinned Helm
151
+ * chart that ships CRDs; a multi-document file or bundle yields every CRD
152
+ * in it, or only the `kinds` listed. The classes are written to
153
+ * `src/generated/k8s/` (see `codegen.outDir`), committed, and imported like
154
+ * any module. `chant build` fails when a source changed since the classes
155
+ * were generated, and the generated kinds get the same spec checks
156
+ * (WK8501/WK8502) as the CRDs the lexicon ships.
157
+ *
158
+ * Paths are relative to the project root. A URL needs the `sha256` of its
159
+ * content, and a chart its `version`, so generation never depends on the
160
+ * day it ran.
161
+ *
162
+ * ```ts
163
+ * k8s: {
164
+ * crds: [
165
+ * { type: "file", path: "crds/widgets.yaml" },
166
+ * { type: "url", url: "https://example.com/v1.2.0/crds.yaml", sha256: "9f86d0…", kinds: ["Gadget"] },
167
+ * ],
168
+ * } satisfies K8sChantConfig
169
+ * ```
170
+ */
171
+ crds?: K8sProjectCrdSource[];
137
172
  }
138
173
 
174
+ /** One `k8s.crds` entry. `kinds` keeps only the CRDs of those kinds. */
175
+ export type K8sProjectCrdSource =
176
+ | { type: "file"; path: string; kinds?: string[] }
177
+ | { type: "url"; url: string; sha256: string; kinds?: string[] }
178
+ | { type: "helm"; chart: string; version: string; digest?: string; chartSubdir?: string; kinds?: string[] };
179
+
139
180
  declare module "@intentius/chant/config" {
140
181
  interface ChantConfig {
141
182
  k8s?: K8sChantConfig;
@@ -199,17 +199,24 @@ const INFISICAL_OPERATOR_VERSION = "infisical-k8-operator/v0.11.7";
199
199
  const INFISICAL_CRD_BASE = `https://raw.githubusercontent.com/Infisical/kubernetes-operator/${INFISICAL_OPERATOR_VERSION}/config/crd/bases`;
200
200
 
201
201
  /**
202
- * Prometheus Operator CRDs — monitoring.coreos.com/v1
202
+ * Prometheus Operator CRDs — monitoring.coreos.com/v1 and v1alpha1
203
203
  *
204
204
  * Produces (the `monitoring.coreos.com` group maps to the `Monitoring`
205
205
  * namespace):
206
206
  * K8s::Monitoring::ServiceMonitor → apiVersion: monitoring.coreos.com/v1, kind: ServiceMonitor
207
207
  * K8s::Monitoring::PrometheusRule → apiVersion: monitoring.coreos.com/v1, kind: PrometheusRule
208
+ * K8s::Monitoring::Prometheus / Alertmanager / PodMonitor / Probe / ThanosRuler
209
+ * → apiVersion: monitoring.coreos.com/v1
210
+ * K8s::Monitoring::PrometheusAgent / AlertmanagerConfig / ScrapeConfig
211
+ * → apiVersion: monitoring.coreos.com/v1alpha1
212
+ *
213
+ * `Probe` is also the core container probe property type, so the CRD class is
214
+ * `MonitoringProbe` (priorityNames in codegen/naming.ts).
208
215
  *
209
216
  * Operator install: kube-prometheus-stack chart, or
210
217
  * https://github.com/prometheus-operator/prometheus-operator
211
218
  */
212
- const PROM_OPERATOR_VERSION = "v0.79.2";
219
+ const PROM_OPERATOR_VERSION = "v0.94.1";
213
220
  const PROM_OPERATOR_CRD_BASE = `https://raw.githubusercontent.com/prometheus-operator/prometheus-operator/${PROM_OPERATOR_VERSION}/example/prometheus-operator-crd`;
214
221
 
215
222
  /**
@@ -503,6 +510,25 @@ const ACK_EKS_CRD_BASE = `https://raw.githubusercontent.com/aws-controllers-k8s/
503
510
  const GRAFANA_OPERATOR_VERSION = "v5.25.0";
504
511
  const GRAFANA_OPERATOR_CRD_BASE = `https://raw.githubusercontent.com/grafana/grafana-operator/${GRAFANA_OPERATOR_VERSION}/config/crd/bases`;
505
512
 
513
+ /**
514
+ * OpenTelemetry Operator CRDs — opentelemetry.io (#3367)
515
+ *
516
+ * The `opentelemetry.io` group is mapped to the `OpenTelemetry` namespace (see
517
+ * GROUP_NAMESPACE_OVERRIDES in group-namespace.ts). Each CRD is generated at
518
+ * its storage version:
519
+ * K8s::OpenTelemetry::OpenTelemetryCollector → opentelemetry.io/v1beta1 (spec.config is a structured object)
520
+ * K8s::OpenTelemetry::Instrumentation → opentelemetry.io/v1alpha1
521
+ * K8s::OpenTelemetry::TargetAllocator → opentelemetry.io/v1alpha1
522
+ * K8s::OpenTelemetry::OpAMPBridge → opentelemetry.io/v1alpha1
523
+ * K8s::OpenTelemetry::ClusterObservability → opentelemetry.io/v1alpha1 (new in v0.160.0: one CR that
524
+ * sets up the operator's collectors and instrumentation cluster-wide)
525
+ *
526
+ * Operator install: kubectl apply -f
527
+ * https://github.com/open-telemetry/opentelemetry-operator/releases/download/v0.160.0/opentelemetry-operator.yaml
528
+ */
529
+ const OTEL_OPERATOR_VERSION = "v0.160.0";
530
+ const OTEL_OPERATOR_CRD_BASE = `https://raw.githubusercontent.com/open-telemetry/opentelemetry-operator/${OTEL_OPERATOR_VERSION}/config/crd/bases`;
531
+
506
532
  export const CRD_SOURCES: CRDSource[] = [
507
533
  { type: "url", url: `${KUBERAY_CRD_BASE}/ray.io_rayclusters.yaml` },
508
534
  { type: "url", url: `${KUBERAY_CRD_BASE}/ray.io_rayjobs.yaml` },
@@ -519,6 +545,14 @@ export const CRD_SOURCES: CRDSource[] = [
519
545
  { type: "url", url: CERT_MANAGER_CRD_BUNDLE },
520
546
  { type: "url", url: `${PROM_OPERATOR_CRD_BASE}/monitoring.coreos.com_servicemonitors.yaml` },
521
547
  { type: "url", url: `${PROM_OPERATOR_CRD_BASE}/monitoring.coreos.com_prometheusrules.yaml` },
548
+ { type: "url", url: `${PROM_OPERATOR_CRD_BASE}/monitoring.coreos.com_prometheuses.yaml` },
549
+ { type: "url", url: `${PROM_OPERATOR_CRD_BASE}/monitoring.coreos.com_alertmanagers.yaml` },
550
+ { type: "url", url: `${PROM_OPERATOR_CRD_BASE}/monitoring.coreos.com_podmonitors.yaml` },
551
+ { type: "url", url: `${PROM_OPERATOR_CRD_BASE}/monitoring.coreos.com_probes.yaml` },
552
+ { type: "url", url: `${PROM_OPERATOR_CRD_BASE}/monitoring.coreos.com_thanosrulers.yaml` },
553
+ { type: "url", url: `${PROM_OPERATOR_CRD_BASE}/monitoring.coreos.com_prometheusagents.yaml` },
554
+ { type: "url", url: `${PROM_OPERATOR_CRD_BASE}/monitoring.coreos.com_alertmanagerconfigs.yaml` },
555
+ { type: "url", url: `${PROM_OPERATOR_CRD_BASE}/monitoring.coreos.com_scrapeconfigs.yaml` },
522
556
  { type: "url", url: `${CNPG_CRD_BASE}/postgresql.cnpg.io_clusters.yaml` },
523
557
  { type: "url", url: `${CNPG_CRD_BASE}/postgresql.cnpg.io_scheduledbackups.yaml` },
524
558
  { type: "url", url: `${CNPG_CRD_BASE}/postgresql.cnpg.io_backups.yaml` },
@@ -598,4 +632,9 @@ export const CRD_SOURCES: CRDSource[] = [
598
632
  { type: "url", url: `${GRAFANA_OPERATOR_CRD_BASE}/grafana.integreatly.org_grafananotificationpolicyroutes.yaml` },
599
633
  { type: "url", url: `${GRAFANA_OPERATOR_CRD_BASE}/grafana.integreatly.org_grafanamutetimings.yaml` },
600
634
  { type: "url", url: `${GRAFANA_OPERATOR_CRD_BASE}/grafana.integreatly.org_grafananotificationtemplates.yaml` },
635
+ { type: "url", url: `${OTEL_OPERATOR_CRD_BASE}/opentelemetry.io_opentelemetrycollectors.yaml` },
636
+ { type: "url", url: `${OTEL_OPERATOR_CRD_BASE}/opentelemetry.io_instrumentations.yaml` },
637
+ { type: "url", url: `${OTEL_OPERATOR_CRD_BASE}/opentelemetry.io_targetallocators.yaml` },
638
+ { type: "url", url: `${OTEL_OPERATOR_CRD_BASE}/opentelemetry.io_opampbridges.yaml` },
639
+ { type: "url", url: `${OTEL_OPERATOR_CRD_BASE}/opentelemetry.io_clusterobservabilities.yaml` },
601
640
  ];
package/src/crd/loader.ts CHANGED
@@ -40,7 +40,7 @@ export async function loadMultipleCRDs(sources: CRDSource[]): Promise<K8sParseRe
40
40
  /**
41
41
  * Fetch raw CRD YAML content from a source.
42
42
  */
43
- async function fetchCRDContent(source: CRDSource): Promise<string> {
43
+ export async function fetchCRDContent(source: CRDSource): Promise<string> {
44
44
  switch (source.type) {
45
45
  case "file":
46
46
  return loadFromFile(source);
package/src/crd/parser.ts CHANGED
@@ -46,6 +46,14 @@ export function parseCRD(content: string): K8sParseResult[] {
46
46
  return results;
47
47
  }
48
48
 
49
+ /**
50
+ * The version a CRD's types are generated from: the served storage version,
51
+ * else the first served one.
52
+ */
53
+ export function crdTargetVersion(spec: CRDSpec): CRDSpec["versions"][number] | undefined {
54
+ return spec.versions.find((v) => v.storage && v.served) ?? spec.versions.find((v) => v.served);
55
+ }
56
+
49
57
  /**
50
58
  * Parse a CRD spec into K8sParseResult entries.
51
59
  * Extracts one result per served version with storage version preferred.
@@ -54,11 +62,7 @@ export function parseCRDSpec(spec: CRDSpec): K8sParseResult[] {
54
62
  const results: K8sParseResult[] = [];
55
63
  const groupNs = namespaceSegmentForGroup(spec.group);
56
64
 
57
- // Find the storage version (the canonical version)
58
- const storageVersion = spec.versions.find((v) => v.storage && v.served);
59
- // Fall back to any served version
60
- const targetVersion = storageVersion ?? spec.versions.find((v) => v.served);
61
-
65
+ const targetVersion = crdTargetVersion(spec);
62
66
  if (!targetVersion) return results;
63
67
 
64
68
  const typeName = `K8s::${groupNs}::${spec.names.kind}`;
@@ -0,0 +1,239 @@
1
+ /**
2
+ * Project-local CRD classes end to end: a project declares a CRD file under
3
+ * `k8s.crds`, `chant generate` writes typed classes into it, a source file
4
+ * constructs one, the build emits the CRD's apiVersion and kind, the CRD spec
5
+ * checks flag a value the schema rejects, and editing the CRD without
6
+ * regenerating fails the build.
7
+ */
8
+ import { afterAll, beforeEach, describe, expect, test } from "vitest";
9
+ import { mkdirSync, mkdtempSync, readFileSync, rmSync, symlinkSync, writeFileSync } from "node:fs";
10
+ import { tmpdir } from "node:os";
11
+ import { dirname, join, resolve } from "node:path";
12
+ import { fileURLToPath } from "node:url";
13
+ import ts from "typescript";
14
+ import { buildCommand } from "@intentius/chant/cli/commands/build";
15
+ import { loadPlugins } from "@intentius/chant/cli";
16
+ import { loadChantConfig } from "@intentius/chant/config";
17
+ import { checkProjectCodegen, generateProjectCode } from "@intentius/chant/project-codegen";
18
+ import { k8sPlugin } from "../plugin";
19
+ import { clearProjectKinds } from "../project-kinds";
20
+ import { k8sProjectCodegen } from "./project-codegen";
21
+
22
+ const repoRoot = resolve(dirname(fileURLToPath(import.meta.url)), "../../../..");
23
+ const made: string[] = [];
24
+ afterAll(() => {
25
+ for (const dir of made) rmSync(dir, { recursive: true, force: true });
26
+ });
27
+ beforeEach(() => clearProjectKinds());
28
+
29
+ const WIDGET_CRD = `apiVersion: apiextensions.k8s.io/v1
30
+ kind: CustomResourceDefinition
31
+ metadata:
32
+ name: widgets.example.com
33
+ spec:
34
+ group: example.com
35
+ scope: Namespaced
36
+ names: { kind: Widget, plural: widgets }
37
+ versions:
38
+ - name: v1alpha1
39
+ served: true
40
+ storage: false
41
+ schema: { openAPIV3Schema: { type: object } }
42
+ - name: v1
43
+ served: true
44
+ storage: true
45
+ schema:
46
+ openAPIV3Schema:
47
+ type: object
48
+ properties:
49
+ spec:
50
+ type: object
51
+ description: What the widget should be.
52
+ required: [size]
53
+ properties:
54
+ size: { type: integer, description: How many. }
55
+ color: { type: string, enum: [red, blue] }
56
+ labels:
57
+ type: object
58
+ additionalProperties: { type: string }
59
+ "app.kubernetes.io/part-of": { type: string }
60
+ status:
61
+ type: object
62
+ properties:
63
+ ready: { type: boolean }
64
+ ---
65
+ apiVersion: apiextensions.k8s.io/v1
66
+ kind: CustomResourceDefinition
67
+ metadata:
68
+ name: gadgets.example.com
69
+ spec:
70
+ group: example.com
71
+ scope: Cluster
72
+ names: { kind: Gadget, plural: gadgets }
73
+ versions:
74
+ - name: v1
75
+ served: true
76
+ storage: true
77
+ schema:
78
+ openAPIV3Schema:
79
+ type: object
80
+ properties:
81
+ spec: { type: object, properties: { mode: { type: string } } }
82
+ `;
83
+
84
+ const APP = (spec: string) => `import { Widget } from "./generated/k8s";
85
+
86
+ export const widget = new Widget({
87
+ metadata: { name: "w1", labels: { app: "demo" } },
88
+ spec: ${spec},
89
+ });
90
+ `;
91
+
92
+ function project(): string {
93
+ const root = mkdtempSync(join(tmpdir(), "chant-crd-codegen-"));
94
+ made.push(root);
95
+ mkdirSync(join(root, ".git"));
96
+ mkdirSync(join(root, "crds"));
97
+ mkdirSync(join(root, "src"));
98
+ writeFileSync(join(root, "crds", "widgets.yaml"), WIDGET_CRD);
99
+ writeFileSync(
100
+ join(root, "chant.config.ts"),
101
+ `export default {\n lexicons: ["k8s"],\n k8s: { crds: [{ type: "file", path: "crds/widgets.yaml" }] },\n};\n`,
102
+ );
103
+ symlinkSync(join(repoRoot, "node_modules"), join(root, "node_modules"), "dir");
104
+ return root;
105
+ }
106
+
107
+ async function config(root: string): Promise<Record<string, unknown>> {
108
+ return (await loadChantConfig(root)).config as unknown as Record<string, unknown>;
109
+ }
110
+
111
+ async function build(root: string) {
112
+ const src = join(root, "src");
113
+ const plugins = await loadPlugins(["k8s"]);
114
+ const serializers = plugins.map((p) => p.serializer).filter((s) => s.name === "k8s");
115
+ const output = join(root, "k8s.yaml");
116
+ const result = await buildCommand({ path: src, output, format: "yaml", serializers, plugins });
117
+ let yaml = "";
118
+ try {
119
+ yaml = readFileSync(output, "utf8");
120
+ } catch {
121
+ // No output on a failed build.
122
+ }
123
+ return { result, yaml };
124
+ }
125
+
126
+ /** Type-check the project's sources against the real lexicon declarations. */
127
+ let previousProgram: ts.Program | undefined;
128
+
129
+ function typecheck(root: string): string[] {
130
+ const options: ts.CompilerOptions = {
131
+ strict: true,
132
+ noEmit: true,
133
+ skipLibCheck: true,
134
+ target: ts.ScriptTarget.ES2022,
135
+ module: ts.ModuleKind.ESNext,
136
+ moduleResolution: ts.ModuleResolutionKind.Bundler,
137
+ // The workspace packages' sources, as the repo's own typecheck reads them.
138
+ customConditions: ["development"],
139
+ types: [],
140
+ };
141
+ const files = [join(root, "src", "app.ts"), join(root, "src", "generated", "k8s", "index.ts")];
142
+ // Reusing the previous program skips re-parsing the lexicon sources.
143
+ const program = ts.createProgram(files, options, undefined, previousProgram);
144
+ previousProgram = program;
145
+ return files
146
+ .flatMap((f) => [...program.getSyntacticDiagnostics(program.getSourceFile(f)), ...program.getSemanticDiagnostics(program.getSourceFile(f))])
147
+ .map((d) => ts.flattenDiagnosticMessageText(d.messageText, "\n"));
148
+ }
149
+
150
+ describe("project CRD classes (k8s.crds)", () => {
151
+ test("generate, build, spec check, and drift", async () => {
152
+ const root = project();
153
+ const generated = await generateProjectCode(k8sPlugin, root, await config(root));
154
+ expect(generated?.files).toEqual(["index.ts", "kinds.json"]);
155
+ expect(generated?.summary).toEqual(["Gadget (example.com/v1, cluster-scoped)", "Widget (example.com/v1, namespaced)"]);
156
+
157
+ const module = readFileSync(join(root, "src/generated/k8s/index.ts"), "utf8");
158
+ expect(module).toContain("export type WidgetSpec = {");
159
+ expect(module).toContain(" size: number;");
160
+ expect(module).toContain(` color?: "red" | "blue";`);
161
+ expect(module).toContain(` "app.kubernetes.io/part-of"?: string;`);
162
+ expect(module).toContain(" labels?: Record<string, string>;");
163
+ expect(module).toContain(`createResource("K8s::Example::Widget", "k8s"`);
164
+
165
+ // A correct resource builds with the CRD's storage version and kind.
166
+ writeFileSync(join(root, "src", "app.ts"), APP(`{ size: 3, color: "red" }`));
167
+ expect(typecheck(root)).toEqual([]);
168
+ const ok = await build(root);
169
+ expect(ok.result.errors).toEqual([]);
170
+ expect(ok.yaml).toContain("apiVersion: example.com/v1\nkind: Widget");
171
+ expect(ok.yaml).toContain("size: 3");
172
+
173
+ // A spec the CRD rejects fails to typecheck and is flagged by the spec checks.
174
+ writeFileSync(join(root, "src", "app.ts"), APP(`{ size: "three", colour: "red" }`));
175
+ const typeErrors = typecheck(root).join("\n");
176
+ expect(typeErrors).toMatch(/'colour' does not exist|not assignable/);
177
+ const bad = await build(root);
178
+ const findings = [...bad.result.errors, ...bad.result.warnings].join("\n");
179
+ expect(findings).toMatch(/spec\.colour/);
180
+ expect(findings).toMatch(/spec\.size/);
181
+
182
+ // Editing the CRD without regenerating fails the build.
183
+ writeFileSync(join(root, "src", "app.ts"), APP(`{ size: 3 }`));
184
+ writeFileSync(join(root, "crds", "widgets.yaml"), WIDGET_CRD.replace("enum: [red, blue]", "enum: [red, blue, green]"));
185
+ const drifted = await build(root);
186
+ expect(drifted.result.success).toBe(false);
187
+ expect(drifted.result.errors.join("\n")).toMatch(/src\/generated\/k8s is out of date.*chant generate/);
188
+
189
+ await generateProjectCode(k8sPlugin, root, await config(root));
190
+ expect((await build(root)).result.errors).toEqual([]);
191
+ }, 120_000);
192
+
193
+ test("a URL source must be pinned, and its content must match the pin", async () => {
194
+ const root = project();
195
+ const url = "https://example.test/crds.yaml";
196
+ const pin = "0".repeat(64);
197
+ const codegen = k8sProjectCodegen({ fetchUrl: async () => WIDGET_CRD });
198
+ const ctx = (crds: unknown[]) => ({ projectRoot: root, outDir: join(root, "out"), config: { k8s: { crds } } });
199
+
200
+ expect(() => codegen.inputs(ctx([{ type: "url", url }]))).toThrow(/needs a sha256 pin/);
201
+ await expect(codegen.generate(ctx([{ type: "url", url, sha256: pin }]))).rejects.toThrow(/has sha256 [0-9a-f]{64}, but the config pins 0{64}/);
202
+
203
+ const { createHash } = await import("node:crypto");
204
+ const real = createHash("sha256").update(WIDGET_CRD).digest("hex");
205
+ const out = await codegen.generate(ctx([{ type: "url", url, sha256: `sha256:${real}`, kinds: ["Gadget"] }]));
206
+ expect(out.summary).toEqual(["Gadget (example.com/v1, cluster-scoped)"]);
207
+ });
208
+
209
+ test("a helm chart source needs a version", () => {
210
+ const codegen = k8sProjectCodegen();
211
+ const ctx = { projectRoot: "/p", outDir: "/p/out", config: { k8s: { crds: [{ type: "helm", chart: "oci://example.test/c" }] } } };
212
+ expect(() => codegen.inputs(ctx)).toThrow(/needs a version/);
213
+ });
214
+
215
+ test("two kinds of one name from different groups take the group as a prefix", async () => {
216
+ const other = WIDGET_CRD.split("---")[0].replace(/example\.com/g, "acme.io");
217
+ const codegen = k8sProjectCodegen({ fetchUrl: async (u) => (u.includes("acme") ? other : WIDGET_CRD) });
218
+ const { createHash } = await import("node:crypto");
219
+ const sha = (s: string) => createHash("sha256").update(s).digest("hex");
220
+ const out = await codegen.generate({
221
+ projectRoot: "/p",
222
+ outDir: "/p/out",
223
+ config: {
224
+ k8s: {
225
+ crds: [
226
+ { type: "url", url: "https://example.test/a.yaml", sha256: sha(WIDGET_CRD), kinds: ["Widget"] },
227
+ { type: "url", url: "https://acme.test/b.yaml", sha256: sha(other) },
228
+ ],
229
+ },
230
+ },
231
+ });
232
+ expect(out.files["index.ts"]).toMatch(/export const AcmeWidget: new/);
233
+ expect(out.files["index.ts"]).toMatch(/export const ExampleWidget: new/);
234
+ });
235
+
236
+ test("the build's check reports nothing when no CRDs are declared", async () => {
237
+ expect(await checkProjectCodegen(k8sPlugin, "/nonexistent", {})).toEqual({ status: "none" });
238
+ });
239
+ });