@intentius/chant-lexicon-k8s 0.107.1 → 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.
- package/dist/config-schema.d.ts +115 -1
- package/dist/config-schema.d.ts.map +1 -1
- package/dist/config.d.ts +58 -3
- package/dist/config.d.ts.map +1 -1
- package/dist/crd/loader.d.ts +4 -0
- package/dist/crd/loader.d.ts.map +1 -1
- package/dist/crd/parser.d.ts +5 -0
- package/dist/crd/parser.d.ts.map +1 -1
- package/dist/crd/project-codegen.d.ts +33 -0
- package/dist/crd/project-codegen.d.ts.map +1 -0
- package/dist/include/entity.d.ts +73 -0
- package/dist/include/entity.d.ts.map +1 -0
- package/dist/include/resolve.d.ts +29 -0
- package/dist/include/resolve.d.ts.map +1 -0
- package/dist/index.d.ts +7 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/integrity.json +3 -3
- package/dist/kustomize/rendered-entity.d.ts +15 -1
- package/dist/kustomize/rendered-entity.d.ts.map +1 -1
- package/dist/kustomize/root.d.ts +11 -2
- package/dist/kustomize/root.d.ts.map +1 -1
- package/dist/lint/post-synth/crd-schema-helpers.d.ts +5 -1
- package/dist/lint/post-synth/crd-schema-helpers.d.ts.map +1 -1
- package/dist/manifest.json +1 -1
- package/dist/patch/json-patch.d.ts +51 -0
- package/dist/patch/json-patch.d.ts.map +1 -0
- package/dist/patch/rendered-patch.d.ts +90 -0
- package/dist/patch/rendered-patch.d.ts.map +1 -0
- package/dist/plugin.d.ts.map +1 -1
- package/dist/project-kinds.d.ts +46 -0
- package/dist/project-kinds.d.ts.map +1 -0
- package/dist/rules/crd-schema-helpers.ts +10 -2
- package/dist/serializer.d.ts.map +1 -1
- package/package.json +3 -3
- package/src/config-augmentation.test.ts +28 -0
- package/src/config-schema.ts +47 -1
- package/src/config.ts +44 -3
- package/src/crd/loader.ts +1 -1
- package/src/crd/parser.ts +9 -5
- package/src/crd/project-codegen.test.ts +239 -0
- package/src/crd/project-codegen.ts +327 -0
- package/src/include/entity.ts +119 -0
- package/src/include/include.test.ts +345 -0
- package/src/include/resolve.ts +204 -0
- package/src/index.ts +23 -0
- package/src/kustomize/rendered-entity.ts +43 -1
- package/src/kustomize/root.test.ts +39 -0
- package/src/kustomize/root.ts +16 -30
- package/src/lint/post-synth/crd-schema-helpers.ts +10 -2
- package/src/patch/json-patch.test.ts +91 -0
- package/src/patch/json-patch.ts +189 -0
- package/src/patch/rendered-patch.test.ts +143 -0
- package/src/patch/rendered-patch.ts +180 -0
- package/src/plugin.ts +16 -2
- package/src/project-kinds.ts +75 -0
- package/src/serializer.ts +10 -0
- package/src/testdata/include/bundle.yaml +45 -0
|
@@ -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
|
+
});
|
|
@@ -0,0 +1,327 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Project-local CRD classes: the k8s lexicon's `projectCodegen` hook
|
|
3
|
+
* (`chant generate`, core's project-codegen.ts).
|
|
4
|
+
*
|
|
5
|
+
* A project lists CRD sources under `k8s.crds` in `chant.config.ts`. Generation
|
|
6
|
+
* parses each CRD with the same parser the lexicon's own CRD_SOURCES go
|
|
7
|
+
* through (./parser.ts), so the entity type, GVK and spec field schema match
|
|
8
|
+
* what a shipped CRD gets, and writes two files to `<outDir>/k8s/`:
|
|
9
|
+
*
|
|
10
|
+
* - `index.ts`: a typed class per kind. Its props are typed from the CRD's
|
|
11
|
+
* `openAPIV3Schema` (a shipped CRD's `.d.ts` types `spec` as a record; a
|
|
12
|
+
* project's own types it fully). The module registers its kinds with
|
|
13
|
+
* ../project-kinds.ts when imported.
|
|
14
|
+
* - `kinds.json`: each kind's GVK and spec field schema, which a build loads
|
|
15
|
+
* (`load`) so the serializer and the WK8501/WK8502 spec checks know the
|
|
16
|
+
* kinds whatever process imported the module.
|
|
17
|
+
*/
|
|
18
|
+
|
|
19
|
+
import { createHash } from "node:crypto";
|
|
20
|
+
import { existsSync, readFileSync } from "node:fs";
|
|
21
|
+
import { join, resolve } from "node:path";
|
|
22
|
+
import { loadAll } from "js-yaml";
|
|
23
|
+
import { GENERATED_TS_HEADER, type ProjectCodegen, type ProjectCodegenContext } from "@intentius/chant/project-codegen";
|
|
24
|
+
import { jsdocLines, schemaToTypeScript, tsPropertyKey } from "@intentius/chant/codegen/json-schema-to-ts";
|
|
25
|
+
import { fetchWithRetry } from "@intentius/chant/codegen/fetch";
|
|
26
|
+
import type { K8sProjectCrdSource } from "../config";
|
|
27
|
+
import { namespaceSegmentForGroup } from "../group-namespace";
|
|
28
|
+
import { registerProjectKinds, type ProjectKind } from "../project-kinds";
|
|
29
|
+
import { gvkToApiVersion } from "../spec/parse";
|
|
30
|
+
import { fetchCRDContent } from "./loader";
|
|
31
|
+
import { crdTargetVersion, parseCRDSpec } from "./parser";
|
|
32
|
+
import type { CRDSpec } from "./types";
|
|
33
|
+
|
|
34
|
+
/** The registry file written beside the module. */
|
|
35
|
+
export const KINDS_FILE = "kinds.json";
|
|
36
|
+
|
|
37
|
+
/** Fields every resource class handles itself; a CRD's own schema for them is ignored. */
|
|
38
|
+
const RESERVED_FIELDS = new Set(["apiVersion", "kind", "metadata", "status"]);
|
|
39
|
+
|
|
40
|
+
/** How `generate` reaches a source's content. Tests replace these. */
|
|
41
|
+
export interface CrdSourceReaders {
|
|
42
|
+
/** Fetch a URL source's body. Default: `ctx.fetch`, else core's retrying fetch. */
|
|
43
|
+
fetchUrl?: (url: string) => Promise<string>;
|
|
44
|
+
/** Read a Helm chart's CRDs. Default: the lexicon's CRD loader. */
|
|
45
|
+
readChart?: (source: Extract<K8sProjectCrdSource, { type: "helm" }>) => Promise<string>;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/** The hook, with injectable readers. */
|
|
49
|
+
export function k8sProjectCodegen(readers: CrdSourceReaders = {}): ProjectCodegen {
|
|
50
|
+
return {
|
|
51
|
+
inputs: (ctx) => {
|
|
52
|
+
const sources = declaredSources(ctx);
|
|
53
|
+
if (!sources) return undefined;
|
|
54
|
+
return sources.map((source, i) => describeSource(source, i, ctx.projectRoot));
|
|
55
|
+
},
|
|
56
|
+
|
|
57
|
+
async generate(ctx) {
|
|
58
|
+
const sources = declaredSources(ctx) ?? [];
|
|
59
|
+
const fetchUrl =
|
|
60
|
+
readers.fetchUrl ??
|
|
61
|
+
(async (url: string) => {
|
|
62
|
+
const response = ctx.fetch ? await ctx.fetch(url) : await fetchWithRetry(url);
|
|
63
|
+
if (!response.ok) throw new Error(`${url}: HTTP ${response.status}`);
|
|
64
|
+
return response.text();
|
|
65
|
+
});
|
|
66
|
+
const readChart =
|
|
67
|
+
readers.readChart ??
|
|
68
|
+
((s: Extract<K8sProjectCrdSource, { type: "helm" }>) =>
|
|
69
|
+
fetchCRDContent({ type: "helm", chart: s.chart, version: s.version, digest: s.digest, chartSubdir: s.chartSubdir }));
|
|
70
|
+
|
|
71
|
+
const kinds: GeneratedKind[] = [];
|
|
72
|
+
for (const [i, source] of sources.entries()) {
|
|
73
|
+
describeSource(source, i, ctx.projectRoot); // validates the pin before any fetch
|
|
74
|
+
let content: string;
|
|
75
|
+
if (source.type === "file") {
|
|
76
|
+
content = readFileSync(resolve(ctx.projectRoot, source.path), "utf8");
|
|
77
|
+
} else if (source.type === "url") {
|
|
78
|
+
content = await fetchUrl(source.url);
|
|
79
|
+
const actual = sha256(content);
|
|
80
|
+
if (actual !== normalizeSha(source.sha256)) {
|
|
81
|
+
throw new Error(
|
|
82
|
+
`k8s.crds[${i}]: ${source.url} has sha256 ${actual}, but the config pins ${normalizeSha(source.sha256)}. ` +
|
|
83
|
+
"Check the URL points at a fixed release, then update the pin.",
|
|
84
|
+
);
|
|
85
|
+
}
|
|
86
|
+
} else {
|
|
87
|
+
content = await readChart(source);
|
|
88
|
+
}
|
|
89
|
+
const found = crdKinds(content, source.kinds);
|
|
90
|
+
if (found.length === 0) {
|
|
91
|
+
throw new Error(`k8s.crds[${i}] (${sourceLabel(source)}) holds no CustomResourceDefinition${source.kinds ? ` of kind ${source.kinds.join(", ")}` : ""}`);
|
|
92
|
+
}
|
|
93
|
+
kinds.push(...found);
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
assignClassNames(kinds);
|
|
97
|
+
return {
|
|
98
|
+
files: { "index.ts": renderModule(kinds), [KINDS_FILE]: renderKinds(kinds) },
|
|
99
|
+
summary: kinds.map((k) => `${k.className} (${k.apiVersion}, ${k.scope === "Cluster" ? "cluster-scoped" : "namespaced"})`),
|
|
100
|
+
};
|
|
101
|
+
},
|
|
102
|
+
|
|
103
|
+
load(ctx) {
|
|
104
|
+
const path = join(ctx.outDir, KINDS_FILE);
|
|
105
|
+
if (!existsSync(path)) return;
|
|
106
|
+
registerProjectKinds(JSON.parse(readFileSync(path, "utf8")) as ProjectKind[]);
|
|
107
|
+
},
|
|
108
|
+
};
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
function declaredSources(ctx: ProjectCodegenContext): K8sProjectCrdSource[] | undefined {
|
|
112
|
+
const k8s = ctx.config.k8s as { crds?: K8sProjectCrdSource[] } | undefined;
|
|
113
|
+
return k8s?.crds && k8s.crds.length > 0 ? k8s.crds : undefined;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/**
|
|
117
|
+
* A source as a JSON value for the drift digest: a file by the hash of its
|
|
118
|
+
* content, a remote source by its pin. Throws on an unpinned remote source
|
|
119
|
+
* or a missing file.
|
|
120
|
+
*/
|
|
121
|
+
function describeSource(source: K8sProjectCrdSource, i: number, projectRoot: string): Record<string, unknown> {
|
|
122
|
+
const kinds = source.kinds ? { kinds: [...source.kinds].sort() } : {};
|
|
123
|
+
switch (source.type) {
|
|
124
|
+
case "file": {
|
|
125
|
+
const path = resolve(projectRoot, source.path);
|
|
126
|
+
if (!existsSync(path)) throw new Error(`k8s.crds[${i}]: CRD file not found: ${source.path}`);
|
|
127
|
+
return { type: "file", path: source.path, sha256: sha256(readFileSync(path)), ...kinds };
|
|
128
|
+
}
|
|
129
|
+
case "url":
|
|
130
|
+
if (typeof source.sha256 !== "string" || !/^(sha256:)?[0-9a-f]{64}$/.test(source.sha256)) {
|
|
131
|
+
throw new Error(
|
|
132
|
+
`k8s.crds[${i}]: ${source.url} needs a sha256 pin of its content. An unpinned URL makes the generated classes depend on when they were generated.`,
|
|
133
|
+
);
|
|
134
|
+
}
|
|
135
|
+
return { type: "url", url: source.url, sha256: normalizeSha(source.sha256), ...kinds };
|
|
136
|
+
case "helm":
|
|
137
|
+
if (!source.version) {
|
|
138
|
+
throw new Error(`k8s.crds[${i}]: chart ${source.chart} needs a version. An unpinned chart makes the generated classes depend on when they were generated.`);
|
|
139
|
+
}
|
|
140
|
+
return {
|
|
141
|
+
type: "helm",
|
|
142
|
+
chart: source.chart,
|
|
143
|
+
version: source.version,
|
|
144
|
+
...(source.digest ? { digest: source.digest } : {}),
|
|
145
|
+
...(source.chartSubdir ? { chartSubdir: source.chartSubdir } : {}),
|
|
146
|
+
...kinds,
|
|
147
|
+
};
|
|
148
|
+
default:
|
|
149
|
+
throw new Error(`k8s.crds[${i}]: unsupported source type ${JSON.stringify((source as { type?: unknown }).type)}`);
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
function sourceLabel(source: K8sProjectCrdSource): string {
|
|
154
|
+
return source.type === "file" ? source.path : source.type === "url" ? source.url : `${source.chart} ${source.version}`;
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
function sha256(content: string | Buffer): string {
|
|
158
|
+
return createHash("sha256").update(content).digest("hex");
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
function normalizeSha(pin: string): string {
|
|
162
|
+
return pin.replace(/^sha256:/, "");
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
interface GeneratedKind {
|
|
166
|
+
resourceType: string;
|
|
167
|
+
apiVersion: string;
|
|
168
|
+
kind: string;
|
|
169
|
+
group: string;
|
|
170
|
+
scope: "Namespaced" | "Cluster";
|
|
171
|
+
attributes: Array<{ name: string; tsType: string }>;
|
|
172
|
+
specSchema?: ProjectKind["specSchema"];
|
|
173
|
+
schema?: Record<string, unknown>;
|
|
174
|
+
className: string;
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
/** Every CRD in a (multi-document) YAML text, filtered to `allow` when given. */
|
|
178
|
+
function crdKinds(content: string, allow: string[] | undefined): GeneratedKind[] {
|
|
179
|
+
const docs: unknown[] = [];
|
|
180
|
+
loadAll(content, (doc) => docs.push(doc));
|
|
181
|
+
const out: GeneratedKind[] = [];
|
|
182
|
+
for (const doc of docs) {
|
|
183
|
+
if (!doc || typeof doc !== "object") continue;
|
|
184
|
+
const d = doc as { kind?: unknown; spec?: CRDSpec };
|
|
185
|
+
if (d.kind !== "CustomResourceDefinition" || !d.spec?.group || !d.spec.names?.kind || !d.spec.versions) continue;
|
|
186
|
+
if (allow && allow.length > 0 && !allow.includes(d.spec.names.kind)) continue;
|
|
187
|
+
const [parsed] = parseCRDSpec(d.spec);
|
|
188
|
+
const version = crdTargetVersion(d.spec);
|
|
189
|
+
if (!parsed || !version) continue;
|
|
190
|
+
out.push({
|
|
191
|
+
resourceType: parsed.resource.typeName,
|
|
192
|
+
apiVersion: gvkToApiVersion(parsed.gvk),
|
|
193
|
+
kind: parsed.gvk.kind,
|
|
194
|
+
group: d.spec.group,
|
|
195
|
+
scope: d.spec.scope ?? "Namespaced",
|
|
196
|
+
attributes: parsed.resource.attributes,
|
|
197
|
+
...(parsed.specSchema ? { specSchema: parsed.specSchema } : {}),
|
|
198
|
+
schema: version.schema?.openAPIV3Schema as Record<string, unknown> | undefined,
|
|
199
|
+
className: parsed.gvk.kind,
|
|
200
|
+
});
|
|
201
|
+
}
|
|
202
|
+
return out;
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
/**
|
|
206
|
+
* Class names are the kind. Two kinds of the same name from different groups
|
|
207
|
+
* both take the group's namespace segment as a prefix (`CertManagerCertificate`);
|
|
208
|
+
* the same group and kind twice is an error.
|
|
209
|
+
*/
|
|
210
|
+
function assignClassNames(kinds: GeneratedKind[]): void {
|
|
211
|
+
const seen = new Set<string>();
|
|
212
|
+
for (const k of kinds) {
|
|
213
|
+
const key = `${k.group}/${k.kind}`;
|
|
214
|
+
if (seen.has(key)) throw new Error(`k8s.crds declares ${k.kind} (${k.group}) more than once`);
|
|
215
|
+
seen.add(key);
|
|
216
|
+
}
|
|
217
|
+
const byKind = new Map<string, GeneratedKind[]>();
|
|
218
|
+
for (const k of kinds) byKind.set(k.kind, [...(byKind.get(k.kind) ?? []), k]);
|
|
219
|
+
for (const group of byKind.values()) {
|
|
220
|
+
if (group.length < 2) continue;
|
|
221
|
+
for (const k of group) k.className = `${namespaceSegmentForGroup(k.group).replace(/[^A-Za-z0-9]/g, "")}${k.kind}`;
|
|
222
|
+
}
|
|
223
|
+
kinds.sort((a, b) => a.className.localeCompare(b.className));
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
function renderKinds(kinds: GeneratedKind[]): string {
|
|
227
|
+
const entries: ProjectKind[] = kinds.map((k) => ({
|
|
228
|
+
resourceType: k.resourceType,
|
|
229
|
+
apiVersion: k.apiVersion,
|
|
230
|
+
kind: k.kind,
|
|
231
|
+
...(k.specSchema ? { specSchema: k.specSchema } : {}),
|
|
232
|
+
}));
|
|
233
|
+
return JSON.stringify(entries, null, 2) + "\n";
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
/**
|
|
237
|
+
* The metadata a manifest author sets. Declared in the module rather than
|
|
238
|
+
* imported: the lexicon's `ObjectMeta` export is a runtime constructor, and
|
|
239
|
+
* its typed declaration is not reachable from every install.
|
|
240
|
+
*/
|
|
241
|
+
const OBJECT_META = [
|
|
242
|
+
"/** Standard object metadata: the fields a manifest sets. */",
|
|
243
|
+
"export interface ObjectMeta {",
|
|
244
|
+
" name?: string;",
|
|
245
|
+
" generateName?: string;",
|
|
246
|
+
" namespace?: string;",
|
|
247
|
+
" labels?: Record<string, string>;",
|
|
248
|
+
" annotations?: Record<string, string>;",
|
|
249
|
+
" finalizers?: string[];",
|
|
250
|
+
" ownerReferences?: Array<{",
|
|
251
|
+
" apiVersion: string;",
|
|
252
|
+
" kind: string;",
|
|
253
|
+
" name: string;",
|
|
254
|
+
" uid: string;",
|
|
255
|
+
" controller?: boolean;",
|
|
256
|
+
" blockOwnerDeletion?: boolean;",
|
|
257
|
+
" }>;",
|
|
258
|
+
"}",
|
|
259
|
+
];
|
|
260
|
+
|
|
261
|
+
function renderModule(kinds: GeneratedKind[]): string {
|
|
262
|
+
const lines: string[] = [
|
|
263
|
+
GENERATED_TS_HEADER,
|
|
264
|
+
"// Classes for the custom resources k8s.crds declares in chant.config.",
|
|
265
|
+
'import type { Declarable } from "@intentius/chant";',
|
|
266
|
+
'import { createResource } from "@intentius/chant/runtime";',
|
|
267
|
+
'import { registerProjectKinds } from "@intentius/chant-lexicon-k8s";',
|
|
268
|
+
"",
|
|
269
|
+
"registerProjectKinds([",
|
|
270
|
+
...kinds.map((k) => ` ${JSON.stringify({ resourceType: k.resourceType, apiVersion: k.apiVersion, kind: k.kind })},`),
|
|
271
|
+
"]);",
|
|
272
|
+
"",
|
|
273
|
+
...OBJECT_META,
|
|
274
|
+
];
|
|
275
|
+
|
|
276
|
+
for (const k of kinds) {
|
|
277
|
+
const name = k.className;
|
|
278
|
+
const properties = (k.schema?.properties ?? {}) as Record<string, Record<string, unknown>>;
|
|
279
|
+
const required = new Set((k.schema?.required as string[] | undefined) ?? []);
|
|
280
|
+
const fields = Object.keys(properties).filter((f) => !RESERVED_FIELDS.has(f));
|
|
281
|
+
|
|
282
|
+
const members: string[] = [" /** Standard object's metadata. */", " metadata?: ObjectMeta;"];
|
|
283
|
+
for (const field of fields) {
|
|
284
|
+
const typeName = `${name}${pascal(field)}`;
|
|
285
|
+
const { type, declarations } = schemaToTypeScript(properties[field], {
|
|
286
|
+
openByDefault: false,
|
|
287
|
+
namePrefix: typeName,
|
|
288
|
+
});
|
|
289
|
+
for (const d of declarations) {
|
|
290
|
+
lines.push("", ...jsdocLines(d.description, ""), `export type ${d.name} = ${d.type};`);
|
|
291
|
+
}
|
|
292
|
+
lines.push(
|
|
293
|
+
"",
|
|
294
|
+
`/** The \`${field}\` of a ${k.kind} (${k.apiVersion}). */`,
|
|
295
|
+
`export type ${typeName} = ${type};`,
|
|
296
|
+
);
|
|
297
|
+
members.push(...jsdocLines(properties[field].description, " "));
|
|
298
|
+
members.push(` ${tsPropertyKey(field)}${required.has(field) ? "" : "?"}: ${typeName};`);
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
const attrMap = Object.fromEntries(k.attributes.map((a) => [a.name, a.name]));
|
|
302
|
+
lines.push(
|
|
303
|
+
"",
|
|
304
|
+
`/** Props for a ${k.kind}, a custom resource of ${k.apiVersion}. */`,
|
|
305
|
+
`export interface ${name}Props {`,
|
|
306
|
+
...members,
|
|
307
|
+
"}",
|
|
308
|
+
"",
|
|
309
|
+
`/** A ${k.kind} (${k.apiVersion}, ${k.scope === "Cluster" ? "cluster-scoped" : "namespaced"}). */`,
|
|
310
|
+
`export interface ${name} extends Declarable {`,
|
|
311
|
+
...k.attributes.map((a) => ` readonly ${a.name}: ${a.tsType};`),
|
|
312
|
+
"}",
|
|
313
|
+
"",
|
|
314
|
+
`export const ${name}: new (props: ${name}Props) => ${name} = createResource(${JSON.stringify(k.resourceType)}, "k8s", ${JSON.stringify(attrMap)}) as never;`,
|
|
315
|
+
);
|
|
316
|
+
}
|
|
317
|
+
lines.push("");
|
|
318
|
+
return lines.join("\n");
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
function pascal(name: string): string {
|
|
322
|
+
return name
|
|
323
|
+
.split(/[^A-Za-z0-9]+/)
|
|
324
|
+
.filter(Boolean)
|
|
325
|
+
.map((p) => p.charAt(0).toUpperCase() + p.slice(1))
|
|
326
|
+
.join("");
|
|
327
|
+
}
|
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `k8sInclude`: bring a plain multi-document YAML file or pinned URL into a
|
|
3
|
+
* build as it is (#3566 item 4).
|
|
4
|
+
*
|
|
5
|
+
* Before this, the way to ship a vendored manifest bundle (an operator's
|
|
6
|
+
* install.yaml, a CRD bundle) through chant was a kustomization directory
|
|
7
|
+
* listing it as its only resource. `k8sInclude` declares the file or URL
|
|
8
|
+
* directly. Its documents become the same verbatim manifest entities a
|
|
9
|
+
* kustomize build root produces (`../manifest-entity.ts`), so they get
|
|
10
|
+
* default labels and ownership stamping, post-synth checks, and
|
|
11
|
+
* `lifecycle diff --live` like any declared resource.
|
|
12
|
+
*
|
|
13
|
+
* This module is the declaration only, with no filesystem or network access,
|
|
14
|
+
* so the factory stays pure and folds under `--sandbox`. The bytes are read
|
|
15
|
+
* at `buildRoots()`, the build's one impure seam, in `./resolve.ts`, the same
|
|
16
|
+
* split `declareSecret({ provenance: "committed-encrypted" })` uses.
|
|
17
|
+
*
|
|
18
|
+
* The declaration itself never reaches the output: the serializer skips it,
|
|
19
|
+
* and it carries no `props`, so the live read paths never ask a cluster
|
|
20
|
+
* about it.
|
|
21
|
+
*/
|
|
22
|
+
import { DECLARABLE_MARKER, type Declarable } from "@intentius/chant/declarable";
|
|
23
|
+
import type { RenderedPatch } from "../patch/rendered-patch";
|
|
24
|
+
|
|
25
|
+
/** Marks a `k8sInclude` declaration. */
|
|
26
|
+
export const K8S_INCLUDE_MARKER = Symbol.for("chant.k8s.include");
|
|
27
|
+
|
|
28
|
+
export const K8S_INCLUDE_ENTITY_TYPE = "chant:k8s:include";
|
|
29
|
+
|
|
30
|
+
/** Annotation stamped on every included document, valued with its source. */
|
|
31
|
+
export const INCLUDE_SOURCE_ANNOTATION = "chant.intentius.io/include-source";
|
|
32
|
+
|
|
33
|
+
const DIGEST_RE = /^sha256:[0-9a-f]{64}$/;
|
|
34
|
+
|
|
35
|
+
export interface K8sIncludeProps {
|
|
36
|
+
/**
|
|
37
|
+
* A local file path, relative to the project root (the directory holding
|
|
38
|
+
* `chant.config.*`), or an `https://` / `http://` URL.
|
|
39
|
+
*/
|
|
40
|
+
source: string;
|
|
41
|
+
/**
|
|
42
|
+
* `sha256:<64 hex>` digest of the source's bytes. Required for a URL: the
|
|
43
|
+
* fetched bytes must match it, and the digest keys the local cache, so
|
|
44
|
+
* only the first build needs the network. Optional for a local file; when
|
|
45
|
+
* set, the file must match it too.
|
|
46
|
+
*/
|
|
47
|
+
digest?: string;
|
|
48
|
+
/** Patches applied to the documents before they become entities. */
|
|
49
|
+
patches?: RenderedPatch[];
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
export interface K8sIncludeDeclaration extends Declarable {
|
|
53
|
+
readonly lexicon: "k8s";
|
|
54
|
+
readonly entityType: typeof K8S_INCLUDE_ENTITY_TYPE;
|
|
55
|
+
readonly [K8S_INCLUDE_MARKER]: true;
|
|
56
|
+
readonly source: string;
|
|
57
|
+
readonly digest?: string;
|
|
58
|
+
readonly patches?: RenderedPatch[];
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
export function isK8sInclude(value: unknown): value is K8sIncludeDeclaration {
|
|
62
|
+
return (
|
|
63
|
+
typeof value === "object" &&
|
|
64
|
+
value !== null &&
|
|
65
|
+
(value as Record<symbol, unknown>)[K8S_INCLUDE_MARKER] === true
|
|
66
|
+
);
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** True for an `http://` or `https://` source. */
|
|
70
|
+
export function isRemoteSource(source: string): boolean {
|
|
71
|
+
return /^https?:\/\//i.test(source);
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/**
|
|
75
|
+
* Declare a local or pinned remote multi-document YAML to include in the
|
|
76
|
+
* build.
|
|
77
|
+
*
|
|
78
|
+
* @example
|
|
79
|
+
* ```ts
|
|
80
|
+
* import { k8sInclude } from "@intentius/chant-lexicon-k8s";
|
|
81
|
+
*
|
|
82
|
+
* export const certManager = k8sInclude({
|
|
83
|
+
* source: "https://github.com/cert-manager/cert-manager/releases/download/v1.16.2/cert-manager.yaml",
|
|
84
|
+
* digest: "sha256:...",
|
|
85
|
+
* });
|
|
86
|
+
*
|
|
87
|
+
* export const legacy = k8sInclude({ source: "manifests/legacy.yaml" });
|
|
88
|
+
* ```
|
|
89
|
+
*/
|
|
90
|
+
export function k8sInclude(props: K8sIncludeProps): K8sIncludeDeclaration {
|
|
91
|
+
const source = props?.source;
|
|
92
|
+
if (typeof source !== "string" || source.length === 0) {
|
|
93
|
+
throw new Error("k8sInclude: `source` must be a non-empty path or URL");
|
|
94
|
+
}
|
|
95
|
+
if (/^[a-z][a-z0-9+.-]*:\/\//i.test(source) && !isRemoteSource(source)) {
|
|
96
|
+
throw new Error(`k8sInclude("${source}"): only local paths and http(s) URLs are supported`);
|
|
97
|
+
}
|
|
98
|
+
if (props.digest !== undefined && !DIGEST_RE.test(props.digest)) {
|
|
99
|
+
throw new Error(
|
|
100
|
+
`k8sInclude("${source}"): digest ${JSON.stringify(props.digest)} is not of the form "sha256:<64 lowercase hex>"`,
|
|
101
|
+
);
|
|
102
|
+
}
|
|
103
|
+
if (isRemoteSource(source) && props.digest === undefined) {
|
|
104
|
+
throw new Error(
|
|
105
|
+
`k8sInclude("${source}"): a URL source must be pinned with \`digest: "sha256:<hex>"\`. ` +
|
|
106
|
+
`Compute it from a copy you have reviewed, e.g. \`curl -sL <url> | shasum -a 256\`.`,
|
|
107
|
+
);
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
return {
|
|
111
|
+
lexicon: "k8s",
|
|
112
|
+
entityType: K8S_INCLUDE_ENTITY_TYPE,
|
|
113
|
+
source,
|
|
114
|
+
...(props.digest !== undefined ? { digest: props.digest } : {}),
|
|
115
|
+
...(props.patches !== undefined ? { patches: JSON.parse(JSON.stringify(props.patches)) as RenderedPatch[] } : {}),
|
|
116
|
+
[DECLARABLE_MARKER]: true,
|
|
117
|
+
[K8S_INCLUDE_MARKER]: true,
|
|
118
|
+
};
|
|
119
|
+
}
|