pepr 0.52.2-nightly.1 → 0.52.2-nightly.2

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/src/cli/build.ts DELETED
@@ -1,375 +0,0 @@
1
- // SPDX-License-Identifier: Apache-2.0
2
- // SPDX-FileCopyrightText: 2023-Present The Pepr Authors
3
-
4
- import { execFileSync } from "child_process";
5
- import { BuildContext, BuildOptions, analyzeMetafile } from "esbuild";
6
- import { promises as fs } from "fs";
7
- import { basename, dirname, extname, resolve } from "path";
8
- import { Assets } from "../lib/assets/assets";
9
- import { dependencies, version } from "./init/templates";
10
- import { Command } from "commander";
11
- import { Option } from "commander";
12
- import { parseTimeout } from "../lib/helpers";
13
- import { peprFormat } from "./format";
14
- import { ModuleConfig } from "../lib/types";
15
- import {
16
- watchForChanges,
17
- determineRbacMode,
18
- assignImage,
19
- createOutputDirectory,
20
- handleValidCapabilityNames,
21
- handleCustomImageBuild,
22
- validImagePullSecret,
23
- generateYamlAndWriteToDisk,
24
- } from "./build.helpers";
25
- import { Reloader } from "./types";
26
-
27
- const peprTS = "pepr.ts";
28
- let outputDir: string = "dist";
29
- type PeprNestedFields = Pick<
30
- ModuleConfig,
31
- | "uuid"
32
- | "onError"
33
- | "webhookTimeout"
34
- | "customLabels"
35
- | "alwaysIgnore"
36
- | "env"
37
- | "rbac"
38
- | "rbacMode"
39
- > & {
40
- peprVersion: string;
41
- };
42
-
43
- type PeprConfig = Omit<ModuleConfig, keyof PeprNestedFields> & {
44
- pepr: PeprNestedFields & {
45
- includedFiles: string[];
46
- };
47
- description: string;
48
- version: string;
49
- };
50
-
51
- type LoadModuleReturn = {
52
- cfg: PeprConfig;
53
- entryPointPath: string;
54
- modulePath: string;
55
- name: string;
56
- path: string;
57
- uuid: string;
58
- };
59
-
60
- type BuildModuleReturn = {
61
- ctx: BuildContext<BuildOptions>;
62
- path: string;
63
- cfg: PeprConfig;
64
- uuid: string;
65
- };
66
-
67
- export default function (program: Command): void {
68
- program
69
- .command("build")
70
- .description("Build a Pepr Module for deployment")
71
- .addOption(
72
- new Option("-M, --rbac-mode <mode>", "Override module config and set RBAC mode.").choices([
73
- "admin",
74
- "scoped",
75
- ]),
76
- )
77
- .addOption(
78
- new Option(
79
- "-I, --registry-info <registry/username>",
80
- "Provide the image registry and username for building and pushing a custom WASM container. Requires authentication. Conflicts with --custom-image and --registry. Builds and pushes `'<registry/username>/custom-pepr-controller:<current-version>'`.",
81
- ).conflicts(["customImage", "registry"]),
82
- )
83
- .option("-P, --with-pull-secret <name>", "Use image pull secret for controller Deployment.", "")
84
- .addOption(
85
- new Option(
86
- "-c, --custom-name <name>",
87
- "Set name for zarf component and service monitors in helm charts.",
88
- ),
89
- )
90
- .option("-e, --entry-point <file>", "Specify the entry point file to build with.", peprTS)
91
- .addOption(
92
- new Option(
93
- "-i, --custom-image <image>",
94
- "Specify a custom image with version for deployments. Conflicts with --registry-info and --registry. Example: 'docker.io/username/custom-pepr-controller:v1.0.0'",
95
- ).conflicts(["registryInfo", "registry"]),
96
- )
97
- .option(
98
- "-n, --no-embed",
99
- "Disable embedding of deployment files into output module. Useful when creating library modules intended solely for reuse/distribution via NPM.",
100
- )
101
- .option("-o, --output <directory>", "Set output directory.", "dist")
102
- .addOption(
103
- new Option(
104
- "-r, --registry <GitHub|Iron Bank>",
105
- "Container registry: Choose container registry for deployment manifests. Conflicts with --custom-image and --registry-info.",
106
- )
107
- .conflicts(["customImage", "registryInfo"])
108
- .choices(["GitHub", "Iron Bank"]),
109
- )
110
- .option(
111
- "-t, --timeout <seconds>",
112
- "How long the API server should wait for a webhook to respond before treating the call as a failure.",
113
- parseTimeout,
114
- )
115
- .addOption(
116
- new Option("-z, --zarf <manifest|chart>", "Set Zarf package type")
117
- .choices(["manifest", "chart"])
118
- .default("manifest"),
119
- )
120
- .action(async opts => {
121
- outputDir = await createOutputDirectory(opts.output);
122
-
123
- // Build the module
124
- const buildModuleResult = await buildModule(undefined, opts.entryPoint, opts.embed);
125
-
126
- const { cfg, path } = buildModuleResult!;
127
- // override the name if provided
128
- if (opts.customName) {
129
- process.env.PEPR_CUSTOM_BUILD_NAME = opts.customName;
130
- }
131
-
132
- const image = assignImage({
133
- customImage: opts.customImage,
134
- registryInfo: opts.registryInfo,
135
- peprVersion: cfg.pepr.peprVersion,
136
- registry: opts.registry,
137
- });
138
-
139
- // Check if there is a custom timeout defined
140
- if (opts.timeout !== undefined) {
141
- cfg.pepr.webhookTimeout = opts.timeout;
142
- }
143
-
144
- if (opts.registryInfo !== undefined) {
145
- console.info(`Including ${cfg.pepr.includedFiles.length} files in controller image.`);
146
- // for journey test to make sure the image is built
147
-
148
- // only actually build/push if there are files to include
149
- await handleCustomImageBuild(
150
- cfg.pepr.includedFiles,
151
- cfg.pepr.peprVersion,
152
- cfg.description,
153
- image,
154
- );
155
- }
156
-
157
- // If building without embedding, exit after building
158
- if (!opts.embed) {
159
- console.info(`Module built successfully at ${path}`);
160
- return;
161
- }
162
-
163
- // Generate a secret for the module
164
- const assets = new Assets(
165
- {
166
- ...cfg.pepr,
167
- appVersion: cfg.version,
168
- description: cfg.description,
169
- alwaysIgnore: {
170
- namespaces: cfg.pepr.alwaysIgnore?.namespaces,
171
- },
172
- // Can override the rbacMode with the CLI option
173
- rbacMode: determineRbacMode(opts, cfg),
174
- },
175
- path,
176
- opts.withPullSecret === "" ? [] : [opts.withPullSecret],
177
- );
178
-
179
- if (image !== "") assets.image = image;
180
-
181
- // Ensure imagePullSecret is valid
182
- validImagePullSecret(opts.withPullSecret);
183
-
184
- handleValidCapabilityNames(assets.capabilities);
185
- await generateYamlAndWriteToDisk({
186
- uuid: cfg.pepr.uuid,
187
- outputDir,
188
- imagePullSecret: opts.withPullSecret,
189
- zarf: opts.zarf,
190
- assets,
191
- });
192
- });
193
- }
194
-
195
- // Create a list of external libraries to exclude from the bundle, these are already stored in the container
196
- const externalLibs = Object.keys(dependencies);
197
-
198
- // Add the pepr library to the list of external libraries
199
- externalLibs.push("pepr");
200
-
201
- // Add the kubernetes client to the list of external libraries as it is pulled in by kubernetes-fluent-client
202
- externalLibs.push("@kubernetes/client-node");
203
-
204
- export async function loadModule(entryPoint = peprTS): Promise<LoadModuleReturn> {
205
- // Resolve path to the module / files
206
- const entryPointPath = resolve(".", entryPoint);
207
- const modulePath = dirname(entryPointPath);
208
- const cfgPath = resolve(modulePath, "package.json");
209
-
210
- // Ensure the module's package.json and entrypoint files exist
211
- try {
212
- await fs.access(cfgPath);
213
- await fs.access(entryPointPath);
214
- } catch {
215
- console.error(
216
- `Could not find ${cfgPath} or ${entryPointPath} in the current directory. Please run this command from the root of your module's directory.`,
217
- );
218
- process.exit(1);
219
- }
220
-
221
- // Read the module's UUID from the package.json file
222
- const moduleText = await fs.readFile(cfgPath, { encoding: "utf-8" });
223
- const cfg = JSON.parse(moduleText);
224
- const { uuid } = cfg.pepr;
225
- const name = `pepr-${uuid}.js`;
226
-
227
- // Set the Pepr version from the current running version
228
- cfg.pepr.peprVersion = version;
229
-
230
- // Exit if the module's UUID could not be found
231
- if (!uuid) {
232
- throw new Error("Could not load the uuid in package.json");
233
- }
234
-
235
- return {
236
- cfg,
237
- entryPointPath,
238
- modulePath,
239
- name,
240
- path: resolve(outputDir, name),
241
- uuid,
242
- };
243
- }
244
-
245
- export async function buildModule(
246
- reloader?: Reloader,
247
- entryPoint = peprTS,
248
- embed = true,
249
- ): Promise<BuildModuleReturn | void> {
250
- try {
251
- const { cfg, modulePath, path, uuid } = await loadModule(entryPoint);
252
-
253
- await checkFormat();
254
- // Resolve node_modules folder (in support of npm workspaces!)
255
- const npmRoot = execFileSync("npm", ["root"]).toString().trim();
256
-
257
- // Run `tsc` to validate the module's types & output sourcemaps
258
- const args = ["--project", `${modulePath}/tsconfig.json`, "--outdir", outputDir];
259
- execFileSync(`${npmRoot}/.bin/tsc`, args);
260
-
261
- // Common build options for all builds
262
- const ctxCfg: BuildOptions = {
263
- bundle: true,
264
- entryPoints: [entryPoint],
265
- external: externalLibs,
266
- format: "cjs",
267
- keepNames: true,
268
- legalComments: "external",
269
- metafile: true,
270
- minify: true,
271
- outfile: path,
272
- plugins: [
273
- {
274
- name: "reload-server",
275
- setup(build): void | Promise<void> {
276
- build.onEnd(async r => {
277
- // Print the build size analysis
278
- if (r?.metafile) {
279
- console.info(await analyzeMetafile(r.metafile));
280
- }
281
-
282
- // If we're in dev mode, call the reloader function
283
- if (reloader) {
284
- await reloader(r);
285
- }
286
- });
287
- },
288
- },
289
- ],
290
- platform: "node",
291
- sourcemap: true,
292
- treeShaking: true,
293
- };
294
-
295
- if (reloader) {
296
- // Only minify the code if we're not in dev mode
297
- ctxCfg.minify = false;
298
- }
299
-
300
- // If not embedding (i.e. making a library module to be distro'd via NPM)
301
- if (!embed) {
302
- // Don't minify
303
- ctxCfg.minify = false;
304
-
305
- // Preserve the original file name
306
- ctxCfg.outfile = resolve(outputDir, basename(entryPoint, extname(entryPoint))) + ".js";
307
-
308
- // Don't bundle
309
- ctxCfg.packages = "external";
310
-
311
- // Don't tree shake
312
- ctxCfg.treeShaking = false;
313
- }
314
-
315
- const ctx = await watchForChanges(ctxCfg, reloader);
316
-
317
- return { ctx, path, cfg, uuid };
318
- } catch (e) {
319
- handleModuleBuildError(e);
320
- }
321
- }
322
-
323
- interface BuildModuleResult {
324
- stdout?: Buffer;
325
- stderr: Buffer;
326
- }
327
-
328
- function handleModuleBuildError(e: BuildModuleResult): void {
329
- console.error(`Error building module:`, e);
330
-
331
- if (!e.stdout) process.exit(1); // Exit with a non-zero exit code on any other error
332
-
333
- const out = e.stdout.toString() as string;
334
- const err = e.stderr.toString();
335
-
336
- console.info(out);
337
- console.error(err);
338
-
339
- // Check for version conflicts
340
- if (out.includes("Types have separate declarations of a private property '_name'.")) {
341
- // Try to find the conflicting package
342
- const pgkErrMatch = /error TS2322: .*? 'import\("\/.*?\/node_modules\/(.*?)\/node_modules/g;
343
- out.matchAll(pgkErrMatch);
344
-
345
- // Look for package conflict errors
346
- const conflicts = [...out.matchAll(pgkErrMatch)];
347
-
348
- // If the regex didn't match, leave a generic error
349
- if (conflicts.length < 1) {
350
- console.info(
351
- `\n\tOne or more imported Pepr Capabilities seem to be using an incompatible version of Pepr.\n\tTry updating your Pepr Capabilities to their latest versions.`,
352
- "Version Conflict",
353
- );
354
- }
355
-
356
- // Otherwise, loop through each conflicting package and print an error
357
- conflicts.forEach(match => {
358
- console.info(
359
- `\n\tPackage '${match[1]}' seems to be incompatible with your current version of Pepr.\n\tTry updating to the latest version.`,
360
- "Version Conflict",
361
- );
362
- });
363
- }
364
- }
365
-
366
- async function checkFormat(): Promise<void> {
367
- const validFormat = await peprFormat(true);
368
-
369
- if (!validFormat) {
370
- console.info(
371
- "\x1b[33m%s\x1b[0m",
372
- "Formatting errors were found. The build will continue, but you may want to run `npx pepr format` to address any issues.",
373
- );
374
- }
375
- }