@intentius/chant-lexicon-docker 0.124.98 → 0.124.100

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 (241) hide show
  1. package/dist/codegen/docs-cli.d.ts +0 -1
  2. package/dist/codegen/docs.d.ts +0 -1
  3. package/dist/codegen/generate-cli.d.ts +0 -1
  4. package/dist/codegen/generate-compose.d.ts +0 -1
  5. package/dist/codegen/generate-dockerfile.d.ts +0 -1
  6. package/dist/codegen/generate.d.ts +0 -1
  7. package/dist/codegen/naming.d.ts +0 -1
  8. package/dist/codegen/package.d.ts +0 -1
  9. package/dist/codegen/patches.d.ts +0 -1
  10. package/dist/codegen/versions.d.ts +0 -1
  11. package/dist/compose-key.d.ts +0 -1
  12. package/dist/composites/catalog.d.ts +0 -1
  13. package/dist/composites/docker-otel-collector.d.ts +0 -1
  14. package/dist/composites/docker-web-service.d.ts +0 -1
  15. package/dist/composites/index.d.ts +0 -1
  16. package/dist/coverage.d.ts +0 -1
  17. package/dist/default-labels.d.ts +0 -1
  18. package/dist/detect.d.ts +0 -1
  19. package/dist/dockerfile-order.d.ts +0 -1
  20. package/dist/export-resources.d.ts +0 -1
  21. package/dist/generated/index.d.ts +0 -1
  22. package/dist/generated/runtime.d.ts +0 -1
  23. package/dist/import/adapter.d.ts +0 -1
  24. package/dist/import/adapter.js +4 -2
  25. package/dist/import/embedded.d.ts +0 -1
  26. package/dist/import/engine.d.ts +0 -1
  27. package/dist/import/generator.d.ts +9 -2
  28. package/dist/import/generator.js +23 -1
  29. package/dist/import/live-export.d.ts +0 -1
  30. package/dist/import/parser.d.ts +0 -1
  31. package/dist/import/testdata/tar.d.ts +0 -1
  32. package/dist/index.d.ts +0 -1
  33. package/dist/integrity.json +2 -2
  34. package/dist/interpolation.d.ts +0 -1
  35. package/dist/lint/audit-catalog.d.ts +0 -1
  36. package/dist/lint/audit-lineage.d.ts +0 -1
  37. package/dist/lint/post-synth/add-url-checksum.d.ts +0 -1
  38. package/dist/lint/post-synth/apt-no-recommends.d.ts +0 -1
  39. package/dist/lint/post-synth/apt-update-alone.d.ts +0 -1
  40. package/dist/lint/post-synth/cache-busting-copy.d.ts +0 -1
  41. package/dist/lint/post-synth/copy-from-stage.d.ts +0 -1
  42. package/dist/lint/post-synth/docker-helpers.d.ts +0 -1
  43. package/dist/lint/post-synth/index.d.ts +0 -1
  44. package/dist/lint/post-synth/no-latest-image.d.ts +0 -1
  45. package/dist/lint/post-synth/no-root-user.d.ts +0 -1
  46. package/dist/lint/post-synth/prefer-copy.d.ts +0 -1
  47. package/dist/lint/post-synth/relative-workdir.d.ts +0 -1
  48. package/dist/lint/post-synth/repeated-cmd.d.ts +0 -1
  49. package/dist/lint/post-synth/root-after-user.d.ts +0 -1
  50. package/dist/lint/post-synth/ssh-port-exposed.d.ts +0 -1
  51. package/dist/lint/post-synth/unused-global-arg.d.ts +0 -1
  52. package/dist/lint/post-synth/unused-volume.d.ts +0 -1
  53. package/dist/lint/rules/data/deprecated-images.d.ts +0 -1
  54. package/dist/lint/rules/data/known-base-images.d.ts +0 -1
  55. package/dist/lint/rules/index.d.ts +0 -1
  56. package/dist/lint/rules/no-latest-tag.d.ts +0 -1
  57. package/dist/lint/rules/per-kind-order.d.ts +0 -1
  58. package/dist/list-artifacts.d.ts +0 -1
  59. package/dist/lsp/completions.d.ts +0 -1
  60. package/dist/lsp/hover.d.ts +0 -1
  61. package/dist/manifest.json +1 -1
  62. package/dist/package-cli.d.ts +0 -1
  63. package/dist/plugin.d.ts +0 -1
  64. package/dist/serializer.d.ts +0 -1
  65. package/dist/spec/fetch-compose.d.ts +0 -1
  66. package/dist/spec/fetch-engine.d.ts +0 -1
  67. package/dist/spec/parse-compose.d.ts +0 -1
  68. package/dist/spec/parse-engine.d.ts +0 -1
  69. package/dist/validate-cli.d.ts +0 -1
  70. package/dist/validate.d.ts +0 -1
  71. package/dist/variables.d.ts +0 -1
  72. package/package.json +8 -9
  73. package/dist/codegen/docs-cli.d.ts.map +0 -1
  74. package/dist/codegen/docs.d.ts.map +0 -1
  75. package/dist/codegen/generate-cli.d.ts.map +0 -1
  76. package/dist/codegen/generate-compose.d.ts.map +0 -1
  77. package/dist/codegen/generate-dockerfile.d.ts.map +0 -1
  78. package/dist/codegen/generate.d.ts.map +0 -1
  79. package/dist/codegen/naming.d.ts.map +0 -1
  80. package/dist/codegen/package.d.ts.map +0 -1
  81. package/dist/codegen/patches.d.ts.map +0 -1
  82. package/dist/codegen/versions.d.ts.map +0 -1
  83. package/dist/compose-key.d.ts.map +0 -1
  84. package/dist/composites/catalog.d.ts.map +0 -1
  85. package/dist/composites/docker-otel-collector.d.ts.map +0 -1
  86. package/dist/composites/docker-web-service.d.ts.map +0 -1
  87. package/dist/composites/index.d.ts.map +0 -1
  88. package/dist/coverage.d.ts.map +0 -1
  89. package/dist/default-labels.d.ts.map +0 -1
  90. package/dist/detect.d.ts.map +0 -1
  91. package/dist/dockerfile-order.d.ts.map +0 -1
  92. package/dist/export-resources.d.ts.map +0 -1
  93. package/dist/generated/index.d.ts.map +0 -1
  94. package/dist/generated/runtime.d.ts.map +0 -1
  95. package/dist/import/adapter.d.ts.map +0 -1
  96. package/dist/import/embedded.d.ts.map +0 -1
  97. package/dist/import/engine.d.ts.map +0 -1
  98. package/dist/import/generator.d.ts.map +0 -1
  99. package/dist/import/live-export.d.ts.map +0 -1
  100. package/dist/import/parser.d.ts.map +0 -1
  101. package/dist/import/testdata/tar.d.ts.map +0 -1
  102. package/dist/index.d.ts.map +0 -1
  103. package/dist/interpolation.d.ts.map +0 -1
  104. package/dist/lint/audit-catalog.d.ts.map +0 -1
  105. package/dist/lint/audit-lineage.d.ts.map +0 -1
  106. package/dist/lint/post-synth/add-url-checksum.d.ts.map +0 -1
  107. package/dist/lint/post-synth/apt-no-recommends.d.ts.map +0 -1
  108. package/dist/lint/post-synth/apt-update-alone.d.ts.map +0 -1
  109. package/dist/lint/post-synth/cache-busting-copy.d.ts.map +0 -1
  110. package/dist/lint/post-synth/copy-from-stage.d.ts.map +0 -1
  111. package/dist/lint/post-synth/docker-helpers.d.ts.map +0 -1
  112. package/dist/lint/post-synth/index.d.ts.map +0 -1
  113. package/dist/lint/post-synth/no-latest-image.d.ts.map +0 -1
  114. package/dist/lint/post-synth/no-root-user.d.ts.map +0 -1
  115. package/dist/lint/post-synth/prefer-copy.d.ts.map +0 -1
  116. package/dist/lint/post-synth/relative-workdir.d.ts.map +0 -1
  117. package/dist/lint/post-synth/repeated-cmd.d.ts.map +0 -1
  118. package/dist/lint/post-synth/root-after-user.d.ts.map +0 -1
  119. package/dist/lint/post-synth/ssh-port-exposed.d.ts.map +0 -1
  120. package/dist/lint/post-synth/unused-global-arg.d.ts.map +0 -1
  121. package/dist/lint/post-synth/unused-volume.d.ts.map +0 -1
  122. package/dist/lint/rules/data/deprecated-images.d.ts.map +0 -1
  123. package/dist/lint/rules/data/known-base-images.d.ts.map +0 -1
  124. package/dist/lint/rules/index.d.ts.map +0 -1
  125. package/dist/lint/rules/no-latest-tag.d.ts.map +0 -1
  126. package/dist/lint/rules/per-kind-order.d.ts.map +0 -1
  127. package/dist/list-artifacts.d.ts.map +0 -1
  128. package/dist/lsp/completions.d.ts.map +0 -1
  129. package/dist/lsp/hover.d.ts.map +0 -1
  130. package/dist/package-cli.d.ts.map +0 -1
  131. package/dist/plugin.d.ts.map +0 -1
  132. package/dist/serializer.d.ts.map +0 -1
  133. package/dist/spec/fetch-compose.d.ts.map +0 -1
  134. package/dist/spec/fetch-engine.d.ts.map +0 -1
  135. package/dist/spec/parse-compose.d.ts.map +0 -1
  136. package/dist/spec/parse-engine.d.ts.map +0 -1
  137. package/dist/validate-cli.d.ts.map +0 -1
  138. package/dist/validate.d.ts.map +0 -1
  139. package/dist/variables.d.ts.map +0 -1
  140. package/src/codegen/__snapshots__/okf.test.ts.snap +0 -555
  141. package/src/codegen/docs-cli.ts +0 -10
  142. package/src/codegen/docs.ts +0 -171
  143. package/src/codegen/generate-cli.ts +0 -36
  144. package/src/codegen/generate-compose.ts +0 -21
  145. package/src/codegen/generate-dockerfile.ts +0 -21
  146. package/src/codegen/generate.test.ts +0 -115
  147. package/src/codegen/generate.ts +0 -258
  148. package/src/codegen/naming.test.ts +0 -81
  149. package/src/codegen/naming.ts +0 -54
  150. package/src/codegen/okf.test.ts +0 -36
  151. package/src/codegen/package.ts +0 -59
  152. package/src/codegen/patches.ts +0 -42
  153. package/src/codegen/versions.ts +0 -46
  154. package/src/compose-key.ts +0 -31
  155. package/src/composites/catalog.test.ts +0 -39
  156. package/src/composites/catalog.ts +0 -118
  157. package/src/composites/docker-otel-collector.ts +0 -83
  158. package/src/composites/docker-web-service.test.ts +0 -34
  159. package/src/composites/docker-web-service.ts +0 -75
  160. package/src/composites/index.ts +0 -9
  161. package/src/coverage.test.ts +0 -33
  162. package/src/coverage.ts +0 -54
  163. package/src/default-labels.test.ts +0 -85
  164. package/src/default-labels.ts +0 -72
  165. package/src/detect.ts +0 -7
  166. package/src/dockerfile-order.ts +0 -20
  167. package/src/docs-examples.test.ts +0 -141
  168. package/src/export-resources.ts +0 -90
  169. package/src/generated/index.d.ts +0 -407
  170. package/src/generated/index.ts +0 -410
  171. package/src/generated/runtime.ts +0 -4
  172. package/src/import/adapter.ts +0 -99
  173. package/src/import/embedded-live.test.ts +0 -250
  174. package/src/import/embedded.ts +0 -83
  175. package/src/import/engine.ts +0 -107
  176. package/src/import/generator.test.ts +0 -134
  177. package/src/import/generator.ts +0 -202
  178. package/src/import/live-export.test.ts +0 -271
  179. package/src/import/live-export.ts +0 -359
  180. package/src/import/parser.test.ts +0 -137
  181. package/src/import/parser.ts +0 -269
  182. package/src/import/roundtrip.test.ts +0 -257
  183. package/src/import/testdata/configs-secrets.yaml +0 -15
  184. package/src/import/testdata/full.yaml +0 -43
  185. package/src/import/testdata/names-and-fields.yaml +0 -44
  186. package/src/import/testdata/simple.yaml +0 -9
  187. package/src/import/testdata/tar.ts +0 -24
  188. package/src/import/testdata/webapp.yaml +0 -41
  189. package/src/index.ts +0 -32
  190. package/src/interpolation.test.ts +0 -41
  191. package/src/interpolation.ts +0 -76
  192. package/src/lint/audit-catalog.ts +0 -28
  193. package/src/lint/audit-lineage.ts +0 -48
  194. package/src/lint/post-synth/add-url-checksum.ts +0 -38
  195. package/src/lint/post-synth/apt-no-recommends.ts +0 -43
  196. package/src/lint/post-synth/apt-update-alone.ts +0 -39
  197. package/src/lint/post-synth/cache-busting-copy.ts +0 -65
  198. package/src/lint/post-synth/copy-from-stage.ts +0 -54
  199. package/src/lint/post-synth/docker-helpers.ts +0 -194
  200. package/src/lint/post-synth/index.ts +0 -33
  201. package/src/lint/post-synth/no-latest-image.ts +0 -36
  202. package/src/lint/post-synth/no-root-user.ts +0 -38
  203. package/src/lint/post-synth/post-synth.test.ts +0 -330
  204. package/src/lint/post-synth/prefer-copy.ts +0 -53
  205. package/src/lint/post-synth/relative-workdir.ts +0 -38
  206. package/src/lint/post-synth/repeated-cmd.ts +0 -35
  207. package/src/lint/post-synth/root-after-user.ts +0 -44
  208. package/src/lint/post-synth/ssh-port-exposed.ts +0 -68
  209. package/src/lint/post-synth/unused-global-arg.ts +0 -38
  210. package/src/lint/post-synth/unused-volume.ts +0 -49
  211. package/src/lint/rules/data/deprecated-images.ts +0 -28
  212. package/src/lint/rules/data/known-base-images.ts +0 -20
  213. package/src/lint/rules/index.ts +0 -6
  214. package/src/lint/rules/no-latest-tag.ts +0 -63
  215. package/src/lint/rules/per-kind-order.ts +0 -130
  216. package/src/lint/rules/rules.test.ts +0 -170
  217. package/src/list-artifacts.test.ts +0 -141
  218. package/src/list-artifacts.ts +0 -164
  219. package/src/lsp/completions.test.ts +0 -40
  220. package/src/lsp/completions.ts +0 -21
  221. package/src/lsp/hover.test.ts +0 -35
  222. package/src/lsp/hover.ts +0 -39
  223. package/src/package-cli.ts +0 -25
  224. package/src/plugin.test.ts +0 -121
  225. package/src/plugin.ts +0 -268
  226. package/src/serializer.test.ts +0 -545
  227. package/src/serializer.ts +0 -444
  228. package/src/skills/chant-docker-patterns.md +0 -222
  229. package/src/skills/chant-docker.md +0 -156
  230. package/src/spec/fetch-compose.ts +0 -35
  231. package/src/spec/fetch-engine.ts +0 -25
  232. package/src/spec/parse-compose.ts +0 -195
  233. package/src/spec/parse-engine.ts +0 -59
  234. package/src/typecheck.e2e.test.ts +0 -125
  235. package/src/typed-props.test.ts +0 -60
  236. package/src/validate-cli.ts +0 -19
  237. package/src/validate.test.ts +0 -16
  238. package/src/validate.ts +0 -44
  239. package/src/variables.test.ts +0 -32
  240. package/src/variables.ts +0 -47
  241. /package/{src → dist}/generated/lexicon-docker.json +0 -0
@@ -1,202 +0,0 @@
1
- /**
2
- * Docker IR → TypeScript source generator.
3
- *
4
- * Converts parsed IR to valid chant TypeScript source code.
5
- */
6
-
7
- import { EmbeddedImportScope, isEmbeddedReference, renderEmbeddedReference, type EmbeddedReference } from "@intentius/chant/import/embedded";
8
- import type { DockerIR, ServiceIR, VolumeIR, NetworkIR, ConfigIR, SecretIR, DockerfileIR } from "./parser";
9
-
10
- export interface GenerateResult {
11
- source: string;
12
- warnings: string[];
13
- }
14
-
15
- /**
16
- * Generator for Docker entities — IR → TypeScript chant source.
17
- */
18
- export class DockerGenerator {
19
- generate(entities: DockerIR[]): GenerateResult {
20
- const warnings: string[] = [];
21
- const imports = new Set<string>();
22
- const lines: string[] = [];
23
- const names = new ExportNames();
24
-
25
- // Export names first, so the imports an embedded reference needs (#3373)
26
- // never take one.
27
- const exportNames = entities.map((e) => (e.kind === "dockerfile" ? sanitizeName(e.name) : names.take(e.name, e.kind)));
28
- const scope = new EmbeddedImportScope("", [...RESERVED, ...exportNames]);
29
-
30
- entities.forEach((entity, i) => {
31
- if (entity.kind === "dockerfile") {
32
- imports.add("Dockerfile");
33
- lines.push(generateDockerfile(entity, warnings));
34
- return;
35
- }
36
- const ctor = CONSTRUCTORS[entity.kind];
37
- imports.add(ctor);
38
- const exportName = exportNames[i]!;
39
- const expr = `new ${ctor}(${propsLiteral(entity, scope)})`;
40
- // An export name that differs from the compose key would rename the
41
- // key on build, and every reference to it by name would dangle, so
42
- // the key is set explicitly (#3937).
43
- if (exportName === entity.name) {
44
- lines.push(`export const ${exportName} = ${expr};`);
45
- } else {
46
- imports.add("composeKey");
47
- lines.push(`export const ${exportName} = composeKey(${JSON.stringify(entity.name)}, ${expr});`);
48
- }
49
- });
50
-
51
- const importLine = `import { ${[...imports].sort().join(", ")} } from "@intentius/chant-lexicon-docker";`;
52
- const source = [importLine, ...scope.lines(), "", ...lines].join("\n");
53
-
54
- return { source, warnings };
55
- }
56
- }
57
-
58
- const CONSTRUCTORS = {
59
- service: "Service",
60
- volume: "Volume",
61
- network: "Network",
62
- config: "DockerConfig",
63
- secret: "DockerSecret",
64
- } as const;
65
-
66
- function propsLiteral(entity: ServiceIR | VolumeIR | NetworkIR | ConfigIR | SecretIR, scope: EmbeddedImportScope): string {
67
- // Embedded references (a config's `content` another lexicon imported) are
68
- // rendered as expressions in place of a placeholder string.
69
- const refs: EmbeddedReference[] = [];
70
- const props = withPlaceholders(entity.props, refs) as Record<string, unknown>;
71
- let out: string;
72
- if (entity.kind === "service" || refs.length > 0) {
73
- out = JSON.stringify(props, null, 2).replace(/"([a-z_][a-z0-9_]*)":/g, "$1:");
74
- } else {
75
- out = Object.keys(props).length > 0 ? JSON.stringify(props) : "{}";
76
- }
77
- refs.forEach((ref, i) => {
78
- out = out.replace(JSON.stringify(placeholder(i)), () => renderEmbeddedReference(ref, scope, 2));
79
- });
80
- return out;
81
- }
82
-
83
- function placeholder(i: number): string {
84
- return `\u0000chant-embedded-${i}\u0000`;
85
- }
86
-
87
- function withPlaceholders(value: unknown, refs: EmbeddedReference[]): unknown {
88
- if (isEmbeddedReference(value)) {
89
- refs.push(value);
90
- return placeholder(refs.length - 1);
91
- }
92
- if (Array.isArray(value)) return value.map((v) => withPlaceholders(v, refs));
93
- if (value && typeof value === "object") {
94
- return Object.fromEntries(Object.entries(value as Record<string, unknown>).map(([k, v]) => [k, withPlaceholders(v, refs)]));
95
- }
96
- return value;
97
- }
98
-
99
- /** Words an export cannot be named, and the names the generated file imports. */
100
- const RESERVED = new Set([
101
- "break", "case", "catch", "class", "const", "continue", "debugger", "default", "delete", "do",
102
- "else", "enum", "export", "extends", "false", "finally", "for", "function", "if", "import", "in",
103
- "instanceof", "new", "null", "return", "super", "switch", "this", "throw", "true", "try", "typeof",
104
- "var", "void", "while", "with", "yield", "let", "static", "implements", "interface", "package",
105
- "private", "protected", "public", "await", "arguments", "eval", "undefined", "NaN", "Infinity",
106
- "Service", "Volume", "Network", "DockerConfig", "DockerSecret", "Dockerfile", "composeKey",
107
- ]);
108
-
109
- /**
110
- * Export names for compose keys: identifiers, unique within the file. A key
111
- * shared by two kinds (a service and a volume both named `db`) gives the
112
- * second one a kind suffix (`dbVolume`).
113
- */
114
- class ExportNames {
115
- private readonly used = new Set<string>();
116
-
117
- take(key: string, kind: string): string {
118
- const base = sanitizeName(key);
119
- const suffixed = `${base}${kind[0]!.toUpperCase()}${kind.slice(1)}`;
120
- for (const c of [base, suffixed]) {
121
- if (!RESERVED.has(c) && !this.used.has(c)) {
122
- this.used.add(c);
123
- return c;
124
- }
125
- }
126
- for (let i = 2; ; i++) {
127
- const c = `${suffixed}${i}`;
128
- if (!this.used.has(c)) {
129
- this.used.add(c);
130
- return c;
131
- }
132
- }
133
- }
134
- }
135
-
136
- /** The instructions a step can name; anything else (MAINTAINER) is left as a comment. */
137
- const STEP_KEYS = new Set([
138
- "arg", "env", "workdir", "user", "run", "copy", "add", "expose", "volume",
139
- "label", "entrypoint", "cmd", "healthcheck", "shell", "stopsignal", "onbuild",
140
- ]);
141
-
142
- /**
143
- * A Dockerfile always imports as `steps`, one per instruction in source
144
- * order, so building the import gives the same instructions in the same
145
- * order (the per-kind fields would reorder them).
146
- */
147
- function generateDockerfile(df: DockerfileIR, warnings: string[]): string {
148
- const out: string[] = [`export const ${sanitizeName(df.name)} = new Dockerfile({`];
149
- if (df.globalArgs?.length) out.push(` globalArgs: [${df.globalArgs.map((a) => JSON.stringify(a)).join(", ")}],`);
150
-
151
- const steps = (stage: DockerfileIR["stages"][number], indent: string): void => {
152
- out.push(`${indent}steps: [`);
153
- for (const { instruction, value } of stage.instructions) {
154
- const key = instruction.toLowerCase();
155
- if (STEP_KEYS.has(key)) {
156
- out.push(`${indent} { ${key}: ${quote(value)} },`);
157
- } else {
158
- warnings.push(`Dockerfile ${df.name}: ${instruction} has no step and was left as a comment`);
159
- out.push(`${indent} // ${instruction} ${value.replace(/\n/g, " ")}`);
160
- }
161
- }
162
- out.push(`${indent}],`);
163
- };
164
-
165
- if (df.stages.length === 1) {
166
- const stage = df.stages[0]!;
167
- out.push(` from: ${JSON.stringify(stage.from)},`);
168
- if (stage.as) out.push(` as: ${JSON.stringify(stage.as)},`);
169
- steps(stage, " ");
170
- } else {
171
- out.push(` stages: [`);
172
- for (const stage of df.stages) {
173
- out.push(` {`);
174
- out.push(` from: ${JSON.stringify(stage.from)},`);
175
- if (stage.as) out.push(` as: ${JSON.stringify(stage.as)},`);
176
- steps(stage, " ");
177
- out.push(` },`);
178
- }
179
- out.push(` ],`);
180
- }
181
- out.push(`});`);
182
- return out.join("\n");
183
- }
184
-
185
- /** A string literal, single-quoted when that avoids escaping double quotes (exec form: `'["node", "a.js"]'`). */
186
- function quote(value: string): string {
187
- if (value.includes('"') && !/['\\\n]/.test(value)) return `'${value}'`;
188
- return JSON.stringify(value);
189
- }
190
-
191
- /**
192
- * A TypeScript identifier for a compose key: kebab, snake and dotted keys
193
- * become camelCase, other characters are dropped, and a leading digit gets
194
- * an underscore.
195
- */
196
- function sanitizeName(name: string): string {
197
- let id = name.replace(/[^A-Za-z0-9$]+([A-Za-z0-9])/g, (_, c: string) => c.toUpperCase());
198
- id = id.replace(/[^A-Za-z0-9_$]/g, "");
199
- if (id === "") id = "entity";
200
- if (/^[0-9]/.test(id)) id = `_${id}`;
201
- return id;
202
- }
@@ -1,271 +0,0 @@
1
- /**
2
- * docker live export (#4388): a compose project read from a fake Engine API
3
- * is mapped back to the compose document it was created from, and
4
- * `chant import --from` regenerates its services.
5
- */
6
-
7
- import { describe, expect, test, vi } from "vitest";
8
- import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "fs";
9
- import { join, resolve } from "path";
10
- import { liveImportFromPlugins } from "@intentius/chant/cli/commands/import";
11
- import type { LexiconPlugin } from "@intentius/chant/lexicon";
12
- import { dockerPlugin } from "../plugin";
13
- import { exportResources, projectFor } from "../export-resources";
14
- import { engineAddress, readTar, singleFileText, type DockerEngine } from "./engine";
15
- import {
16
- composeFromLive,
17
- configCandidates,
18
- serviceContainers,
19
- type ContainerInspect,
20
- type ImageInspect,
21
- type LiveService,
22
- } from "./live-export";
23
- import { tarOf } from "./testdata/tar";
24
-
25
- const pkgDir = resolve(import.meta.dirname, "../..");
26
-
27
- const compose = (project: string, service: string, extra: Record<string, string> = {}) => ({
28
- "com.docker.compose.project": project,
29
- "com.docker.compose.service": service,
30
- "com.docker.compose.container-number": "1",
31
- "com.docker.compose.oneoff": "False",
32
- ...extra,
33
- });
34
-
35
- const PG_IMAGE: ImageInspect = {
36
- Config: {
37
- Cmd: ["postgres"],
38
- Entrypoint: ["docker-entrypoint.sh"],
39
- Env: ["PATH=/usr/bin", "PGDATA=/var/lib/postgresql/data"],
40
- Labels: null,
41
- },
42
- };
43
-
44
- const db: ContainerInspect = {
45
- Id: "db1",
46
- Config: {
47
- Image: "postgres:16-alpine",
48
- Cmd: ["postgres"],
49
- Entrypoint: ["docker-entrypoint.sh"],
50
- Env: ["POSTGRES_DB=app", "PATH=/usr/bin", "PGDATA=/var/lib/postgresql/data"],
51
- Labels: compose("shop", "db", { "app.kubernetes.io/managed-by": "chant" }),
52
- Healthcheck: { Test: ["CMD", "pg_isready"], Interval: 5e9, Timeout: 2e9, Retries: 5 },
53
- },
54
- HostConfig: { PortBindings: {}, RestartPolicy: { Name: "no" } },
55
- Mounts: [{ Type: "volume", Name: "shop_pgdata", Destination: "/var/lib/postgresql/data", RW: true }],
56
- NetworkSettings: { Networks: { shop_default: {} } },
57
- };
58
-
59
- const API_IMAGE: ImageInspect = { Config: { Cmd: ["node", "server.js"], Env: ["NODE_ENV=production"], WorkingDir: "/app" } };
60
-
61
- const api: ContainerInspect = {
62
- Id: "api1",
63
- Config: {
64
- Image: "shop/api:1.0",
65
- Cmd: ["node", "server.js", "--settings=/etc/api/settings.json"],
66
- Env: ["NODE_ENV=production", "DATABASE_URL=postgres://db/app"],
67
- Labels: compose("shop", "api", { "com.docker.compose.depends_on": "db:service_healthy:false", team: "web" }),
68
- WorkingDir: "/app",
69
- },
70
- HostConfig: {
71
- PortBindings: { "8080/tcp": [{ HostIp: "", HostPort: "8080" }, { HostIp: "::", HostPort: "8080" }], "9000/udp": [{ HostIp: "127.0.0.1", HostPort: "9000" }] },
72
- RestartPolicy: { Name: "on-failure", MaximumRetryCount: 3 },
73
- },
74
- Mounts: [
75
- { Type: "bind", Source: "/srv/shop/static", Destination: "/app/static", RW: false },
76
- { Type: "volume", Name: "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef", Destination: "/tmp/cache", RW: true },
77
- { Type: "volume", Name: "shared-logs", Destination: "/var/log/api", RW: true },
78
- ],
79
- NetworkSettings: { Networks: { shop_default: {}, shop_backend: {} } },
80
- };
81
-
82
- const SETTINGS = '{ "feature": true }\n';
83
-
84
- function fakeEngine(): { engine: DockerEngine; paths: string[] } {
85
- const paths: string[] = [];
86
- const ok = (body: unknown) => ({ status: 200, body: Buffer.from(JSON.stringify(body)) });
87
- const engine: DockerEngine = async (path) => {
88
- paths.push(path);
89
- const url = new URL(`http://docker${path}`);
90
- if (url.pathname === "/containers/json") {
91
- return ok([
92
- { Id: "api1", Labels: api.Config!.Labels },
93
- { Id: "db1", Labels: db.Config!.Labels },
94
- { Id: "api2", Labels: { ...api.Config!.Labels!, "com.docker.compose.container-number": "2" } },
95
- { Id: "run1", Labels: { ...api.Config!.Labels!, "com.docker.compose.oneoff": "True" } },
96
- ]);
97
- }
98
- if (url.pathname === "/containers/api1/json") return ok(api);
99
- if (url.pathname === "/containers/db1/json") return ok(db);
100
- if (url.pathname === `/images/${encodeURIComponent("shop/api:1.0")}/json`) return ok(API_IMAGE);
101
- if (url.pathname === "/images/postgres:16-alpine/json") return ok(PG_IMAGE);
102
- if (url.pathname === "/containers/api1/archive" && url.searchParams.get("path") === "/etc/api/settings.json") {
103
- return { status: 200, body: tarOf(["settings.json", SETTINGS]) };
104
- }
105
- return { status: 404, body: Buffer.from('{"message":"no such thing"}') };
106
- };
107
- return { engine, paths };
108
- }
109
-
110
- describe("serviceContainers", () => {
111
- test("one container per service, the lowest number, no one-off runs, only the project's", () => {
112
- const got = serviceContainers("shop", [
113
- { Id: "b", Labels: compose("shop", "api", { "com.docker.compose.container-number": "2" }) },
114
- { Id: "a", Labels: compose("shop", "api") },
115
- { Id: "r", Labels: compose("shop", "api", { "com.docker.compose.oneoff": "True" }) },
116
- { Id: "x", Labels: compose("other", "web") },
117
- { Id: "n", Labels: null },
118
- ]);
119
- expect([...got]).toEqual([["api", "a"]]);
120
- });
121
- });
122
-
123
- describe("configCandidates", () => {
124
- test("absolute file paths the command names, outside every mount", () => {
125
- expect(
126
- configCandidates({
127
- Config: {
128
- Entrypoint: ["/otelcol-contrib"],
129
- Cmd: ["--config=/etc/otel/config.yaml", "--set", "x=1", "file:/etc/b.yml", "/data/in.csv", "/usr/bin/run", "--config=/etc/otel/config.yaml"],
130
- },
131
- Mounts: [{ Type: "volume", Name: "v", Destination: "/data" }],
132
- }),
133
- ).toEqual(["/etc/otel/config.yaml", "/etc/b.yml"]);
134
- });
135
- });
136
-
137
- describe("composeFromLive", () => {
138
- const live = (name: string, container: ContainerInspect, image: ImageInspect, files: Record<string, string> = {}): LiveService => ({
139
- name,
140
- container,
141
- image,
142
- files,
143
- });
144
-
145
- test("drops what the image supplies and what compose writes, and keeps what was declared", () => {
146
- const doc = composeFromLive("shop", [live("api", api, API_IMAGE, { "/etc/api/settings.json": SETTINGS }), live("db", db, PG_IMAGE)]);
147
- expect(doc).toEqual({
148
- services: {
149
- api: {
150
- image: "shop/api:1.0",
151
- command: ["node", "server.js", "--settings=/etc/api/settings.json"],
152
- environment: { DATABASE_URL: "postgres://db/app" },
153
- labels: { team: "web" },
154
- ports: ["8080:8080", "127.0.0.1:9000:9000/udp"],
155
- restart: "on-failure:3",
156
- depends_on: { db: { condition: "service_healthy" } },
157
- volumes: ["/srv/shop/static:/app/static:ro", "/tmp/cache", "shared-logs:/var/log/api"],
158
- networks: ["default", "backend"],
159
- configs: [{ source: "api-settings", target: "/etc/api/settings.json" }],
160
- },
161
- db: {
162
- image: "postgres:16-alpine",
163
- environment: { POSTGRES_DB: "app" },
164
- labels: { "app.kubernetes.io/managed-by": "chant" },
165
- healthcheck: { test: ["CMD", "pg_isready"], interval: "5s", timeout: "2s", retries: 5 },
166
- volumes: ["pgdata:/var/lib/postgresql/data"],
167
- },
168
- },
169
- volumes: { "shared-logs": { external: true }, pgdata: {} },
170
- networks: { backend: {} },
171
- configs: { "api-settings": { content: SETTINGS } },
172
- });
173
- });
174
-
175
- test("verbatim keeps what the image supplies, never compose's labels", () => {
176
- const doc = composeFromLive("shop", [live("db", db, PG_IMAGE)], { verbatim: true });
177
- const svc = (doc.services as Record<string, Record<string, unknown>>).db!;
178
- expect(svc.command).toEqual(["postgres"]);
179
- expect(svc.entrypoint).toEqual(["docker-entrypoint.sh"]);
180
- expect(svc.environment).toEqual({ POSTGRES_DB: "app", PATH: "/usr/bin", PGDATA: "/var/lib/postgresql/data" });
181
- expect(svc.labels).toEqual({ "app.kubernetes.io/managed-by": "chant" });
182
- });
183
- });
184
-
185
- describe("exportResources against a fake Engine", () => {
186
- test("reads the project's services and the config files their commands name", async () => {
187
- const { engine, paths } = fakeEngine();
188
- const ir = await exportResources({ environment: "shop" }, engine);
189
- expect(ir.resources.map((r) => `${r.type}/${r.logicalId}`)).toEqual([
190
- "service/api",
191
- "service/db",
192
- "volume/shared-logs",
193
- "volume/pgdata",
194
- "network/backend",
195
- "config/api-settings",
196
- ]);
197
- expect(paths.filter((p) => p.includes("/archive"))).toEqual([`/containers/api1/archive?path=${encodeURIComponent("/etc/api/settings.json")}`]);
198
- expect(paths.some((p) => p.includes("api2") || p.includes("run1"))).toBe(false);
199
- });
200
-
201
- test("owned keeps only services with chant's marker, and says why", async () => {
202
- const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
203
- try {
204
- const { engine, paths } = fakeEngine();
205
- const ir = await exportResources({ environment: "shop", owned: true }, engine);
206
- expect(ir.resources.map((r) => `${r.type}/${r.logicalId}`)).toEqual(["service/db", "volume/pgdata"]);
207
- expect(paths.some((p) => p.includes("/archive"))).toBe(false);
208
- expect(warn).toHaveBeenCalledTimes(1);
209
- } finally {
210
- warn.mockRestore();
211
- }
212
- });
213
-
214
- test("the selector narrows by type and name", async () => {
215
- const { engine } = fakeEngine();
216
- const ir = await exportResources({ environment: "shop", selector: { type: "service", name: "db" } }, engine);
217
- expect(ir.resources.map((r) => r.logicalId)).toEqual(["db"]);
218
- });
219
-
220
- test("COMPOSE_PROJECT_NAME names the project, else the environment", () => {
221
- const prev = process.env.COMPOSE_PROJECT_NAME;
222
- try {
223
- delete process.env.COMPOSE_PROJECT_NAME;
224
- expect(projectFor("staging")).toBe("staging");
225
- process.env.COMPOSE_PROJECT_NAME = "shop";
226
- expect(projectFor("staging")).toBe("shop");
227
- } finally {
228
- if (prev === undefined) delete process.env.COMPOSE_PROJECT_NAME;
229
- else process.env.COMPOSE_PROJECT_NAME = prev;
230
- }
231
- });
232
-
233
- test("a failed listing is an error, not an empty project", async () => {
234
- const engine: DockerEngine = async () => ({ status: 500, body: Buffer.from("daemon down") });
235
- await expect(exportResources({ environment: "shop" }, engine)).rejects.toThrow(/compose project shop failed \(500\): daemon down/);
236
- });
237
-
238
- test("chant import --from regenerates the project's services", async () => {
239
- const dir = mkdtempSync(join(pkgDir, ".roundtrip-tmp-"));
240
- try {
241
- writeFileSync(join(dir, "package.json"), '{ "name": "docker-live", "private": true, "type": "module" }\n');
242
- const { engine } = fakeEngine();
243
- const plugin: LexiconPlugin = { ...dockerPlugin, exportResources: (options) => exportResources(options, engine) };
244
- const result = await liveImportFromPlugins([plugin], { environment: "shop", output: join(dir, "src"), lexicon: "docker", force: true });
245
- expect(result.error).toBeUndefined();
246
- expect(result.success).toBe(true);
247
- const main = result.generatedFiles.map((f) => readFileSync(join(dir, "src", f), "utf-8")).join("\n");
248
- expect(main).toContain("export const api = new Service(");
249
- expect(main).toContain('image: "postgres:16-alpine"');
250
- expect(main).toContain('composeKey("api-settings", new DockerConfig(');
251
- expect(main).toContain(JSON.stringify(SETTINGS));
252
- } finally {
253
- rmSync(dir, { recursive: true, force: true });
254
- }
255
- });
256
- });
257
-
258
- describe("engine", () => {
259
- test("DOCKER_HOST: unix socket, plain tcp, else the default socket", () => {
260
- expect(engineAddress("unix:///run/user/1000/docker.sock")).toEqual({ socketPath: "/run/user/1000/docker.sock" });
261
- expect(engineAddress("tcp://10.0.0.5:2375")).toEqual({ host: "10.0.0.5", port: 2375 });
262
- expect(engineAddress("")).toEqual({ socketPath: "/var/run/docker.sock" });
263
- expect(() => engineAddress("ssh://me@host")).toThrow(/not a unix:\/\/ or tcp:\/\//);
264
- });
265
-
266
- test("an archive of one text file gives its text; a directory, several files or bytes do not", () => {
267
- expect(singleFileText(tarOf(["config.yaml", "a: 1\n"]))).toBe("a: 1\n");
268
- expect(singleFileText(tarOf(["conf.d/", null], ["conf.d/a.yaml", "a: 1\n"]))).toBeUndefined();
269
- expect(readTar(tarOf(["x", "y".repeat(700)]))[0]!.data.length).toBe(700);
270
- });
271
- });