pepr 0.42.0 → 0.42.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (55) hide show
  1. package/dist/cli/build.d.ts +1 -0
  2. package/dist/cli/build.d.ts.map +1 -1
  3. package/dist/cli/build.helpers.d.ts +66 -0
  4. package/dist/cli/build.helpers.d.ts.map +1 -1
  5. package/dist/cli/monitor.d.ts +23 -0
  6. package/dist/cli/monitor.d.ts.map +1 -1
  7. package/dist/cli.js +341 -283
  8. package/dist/controller.js +1 -1
  9. package/dist/lib/assets/destroy.d.ts.map +1 -1
  10. package/dist/lib/assets/helm.d.ts +1 -1
  11. package/dist/lib/assets/helm.d.ts.map +1 -1
  12. package/dist/lib/assets/index.d.ts.map +1 -1
  13. package/dist/lib/assets/pods.d.ts +5 -19
  14. package/dist/lib/assets/pods.d.ts.map +1 -1
  15. package/dist/lib/assets/webhooks.d.ts.map +1 -1
  16. package/dist/lib/assets/yaml.d.ts.map +1 -1
  17. package/dist/lib/capability.d.ts.map +1 -1
  18. package/dist/lib/controller/index.d.ts.map +1 -1
  19. package/dist/lib/controller/store.d.ts +0 -1
  20. package/dist/lib/controller/store.d.ts.map +1 -1
  21. package/dist/lib/controller/storeCache.d.ts +1 -0
  22. package/dist/lib/controller/storeCache.d.ts.map +1 -1
  23. package/dist/lib/mutate-request.d.ts +2 -2
  24. package/dist/lib/mutate-request.d.ts.map +1 -1
  25. package/dist/lib/queue.d.ts.map +1 -1
  26. package/dist/lib/storage.d.ts +4 -4
  27. package/dist/lib/storage.d.ts.map +1 -1
  28. package/dist/lib/utils.d.ts.map +1 -1
  29. package/dist/lib/validate-processor.d.ts +4 -1
  30. package/dist/lib/validate-processor.d.ts.map +1 -1
  31. package/dist/lib/watch-processor.d.ts.map +1 -1
  32. package/dist/lib.js +136 -109
  33. package/dist/lib.js.map +3 -3
  34. package/package.json +1 -1
  35. package/src/cli/build.helpers.ts +180 -0
  36. package/src/cli/build.ts +85 -133
  37. package/src/cli/monitor.ts +108 -65
  38. package/src/lib/assets/deploy.ts +6 -6
  39. package/src/lib/assets/destroy.ts +1 -1
  40. package/src/lib/assets/helm.ts +6 -6
  41. package/src/lib/assets/index.ts +22 -22
  42. package/src/lib/assets/pods.ts +10 -5
  43. package/src/lib/assets/webhooks.ts +1 -1
  44. package/src/lib/assets/yaml.ts +12 -9
  45. package/src/lib/capability.ts +21 -10
  46. package/src/lib/controller/index.ts +9 -7
  47. package/src/lib/controller/store.ts +23 -10
  48. package/src/lib/controller/storeCache.ts +10 -1
  49. package/src/lib/mutate-request.ts +11 -11
  50. package/src/lib/queue.ts +12 -4
  51. package/src/lib/storage.ts +33 -24
  52. package/src/lib/utils.ts +5 -5
  53. package/src/lib/validate-processor.ts +47 -39
  54. package/src/lib/watch-processor.ts +11 -7
  55. package/src/sdk/cosign.ts +4 -4
package/dist/cli.js CHANGED
@@ -86,26 +86,10 @@ var banner = `\x1B[107;40m\x1B[38;5;m \x1B[38;5;m \x1B[38;5;m \x1B[38;5;m \x1B[3
86
86
  `;
87
87
 
88
88
  // src/cli/build.ts
89
- var import_child_process2 = require("child_process");
90
- var import_esbuild = require("esbuild");
91
- var import_fs8 = require("fs");
92
- var import_path2 = require("path");
93
-
94
- // src/lib/included-files.ts
95
- var import_fs = require("fs");
96
- async function createDockerfile(version3, description, includedFiles) {
97
- const file = `
98
- # Use an official Node.js runtime as the base image
99
- FROM ghcr.io/defenseunicorns/pepr/controller:v${version3}
100
-
101
- LABEL description="${description}"
102
-
103
- # Add the included files to the image
104
- ${includedFiles.map((f) => `ADD ${f} ${f}`).join("\n")}
105
-
106
- `;
107
- await import_fs.promises.writeFile("Dockerfile.controller", file, { encoding: "utf-8" });
108
- }
89
+ var import_child_process3 = require("child_process");
90
+ var import_esbuild2 = require("esbuild");
91
+ var import_fs9 = require("fs");
92
+ var import_path3 = require("path");
109
93
 
110
94
  // src/lib/assets/index.ts
111
95
  var import_crypto3 = __toESM(require("crypto"));
@@ -170,7 +154,7 @@ function genCert(key, name2, issuer) {
170
154
 
171
155
  // src/lib/assets/deploy.ts
172
156
  var import_crypto = __toESM(require("crypto"));
173
- var import_fs2 = require("fs");
157
+ var import_fs = require("fs");
174
158
  var import_kubernetes_fluent_client3 = require("kubernetes-fluent-client");
175
159
 
176
160
  // src/lib/telemetry/logger.ts
@@ -633,7 +617,7 @@ function replaceString(str, stringA, stringB) {
633
617
  }
634
618
 
635
619
  // src/lib/assets/pods.ts
636
- function namespace(namespaceLabels) {
620
+ function getNamespace(namespaceLabels) {
637
621
  if (namespaceLabels) {
638
622
  return {
639
623
  apiVersion: "v1",
@@ -653,7 +637,7 @@ function namespace(namespaceLabels) {
653
637
  };
654
638
  }
655
639
  }
656
- function watcher(assets, hash, buildTimestamp, imagePullSecret) {
640
+ function getWatcher(assets, hash, buildTimestamp, imagePullSecret) {
657
641
  const { name: name2, image, capabilities, config } = assets;
658
642
  let hasSchedule = false;
659
643
  const app = `${name2}-watcher`;
@@ -797,7 +781,7 @@ function watcher(assets, hash, buildTimestamp, imagePullSecret) {
797
781
  }
798
782
  return deploy2;
799
783
  }
800
- function deployment(assets, hash, buildTimestamp, imagePullSecret) {
784
+ function getDeployment(assets, hash, buildTimestamp, imagePullSecret) {
801
785
  const { name: name2, image, config } = assets;
802
786
  const app = name2;
803
787
  const deploy2 = {
@@ -938,7 +922,7 @@ function deployment(assets, hash, buildTimestamp, imagePullSecret) {
938
922
  }
939
923
  return deploy2;
940
924
  }
941
- function moduleSecret(name2, data, hash) {
925
+ function getModuleSecret(name2, data, hash) {
942
926
  const compressed = (0, import_zlib.gzipSync)(data);
943
927
  const path = `module-${hash}.js.gz`;
944
928
  const compressedData = compressed.toString("base64");
@@ -1235,7 +1219,7 @@ async function deployImagePullSecret(imagePullSecret, name2) {
1235
1219
  try {
1236
1220
  await (0, import_kubernetes_fluent_client3.K8s)(import_kubernetes_fluent_client3.kind.Namespace).Get("pepr-system");
1237
1221
  } catch {
1238
- await (0, import_kubernetes_fluent_client3.K8s)(import_kubernetes_fluent_client3.kind.Namespace).Apply(namespace());
1222
+ await (0, import_kubernetes_fluent_client3.K8s)(import_kubernetes_fluent_client3.kind.Namespace).Apply(getNamespace());
1239
1223
  }
1240
1224
  try {
1241
1225
  await (0, import_kubernetes_fluent_client3.K8s)(import_kubernetes_fluent_client3.kind.Secret).Apply(
@@ -1261,7 +1245,7 @@ async function deploy(assets, force, webhookTimeout) {
1261
1245
  logger_default.info("Establishing connection to Kubernetes");
1262
1246
  const { name: name2, host, path } = assets;
1263
1247
  logger_default.info("Applying pepr-system namespace");
1264
- await (0, import_kubernetes_fluent_client3.K8s)(import_kubernetes_fluent_client3.kind.Namespace).Apply(namespace(assets.config.customLabels?.namespace));
1248
+ await (0, import_kubernetes_fluent_client3.K8s)(import_kubernetes_fluent_client3.kind.Namespace).Apply(getNamespace(assets.config.customLabels?.namespace));
1265
1249
  const mutateWebhook = await webhookConfig(assets, "mutate", webhookTimeout);
1266
1250
  if (mutateWebhook) {
1267
1251
  logger_default.info("Applying mutating webhook");
@@ -1283,7 +1267,7 @@ async function deploy(assets, force, webhookTimeout) {
1283
1267
  if (host) {
1284
1268
  return;
1285
1269
  }
1286
- const code = await import_fs2.promises.readFile(path);
1270
+ const code = await import_fs.promises.readFile(path);
1287
1271
  const hash = import_crypto.default.createHash("sha256").update(code).digest("hex");
1288
1272
  if (code.length < 1) {
1289
1273
  throw new Error("No code provided");
@@ -1313,7 +1297,7 @@ async function setupRBAC(name2, capabilities, force, config) {
1313
1297
  async function setupController(assets, code, hash, force) {
1314
1298
  const { name: name2 } = assets;
1315
1299
  logger_default.info("Applying module secret");
1316
- const mod = moduleSecret(name2, code, hash);
1300
+ const mod = getModuleSecret(name2, code, hash);
1317
1301
  await (0, import_kubernetes_fluent_client3.K8s)(import_kubernetes_fluent_client3.kind.Secret).Apply(mod, { force });
1318
1302
  logger_default.info("Applying controller service");
1319
1303
  const svc = service(name2);
@@ -1325,11 +1309,11 @@ async function setupController(assets, code, hash, force) {
1325
1309
  const apiToken = apiTokenSecret(name2, assets.apiToken);
1326
1310
  await (0, import_kubernetes_fluent_client3.K8s)(import_kubernetes_fluent_client3.kind.Secret).Apply(apiToken, { force });
1327
1311
  logger_default.info("Applying deployment");
1328
- const dep = deployment(assets, hash, assets.buildTimestamp);
1312
+ const dep = getDeployment(assets, hash, assets.buildTimestamp);
1329
1313
  await (0, import_kubernetes_fluent_client3.K8s)(import_kubernetes_fluent_client3.kind.Deployment).Apply(dep, { force });
1330
1314
  }
1331
1315
  async function setupWatcher(assets, hash, force) {
1332
- const watchDeployment = watcher(assets, hash, assets.buildTimestamp);
1316
+ const watchDeployment = getWatcher(assets, hash, assets.buildTimestamp);
1333
1317
  if (watchDeployment) {
1334
1318
  logger_default.info("Applying watcher deployment");
1335
1319
  await (0, import_kubernetes_fluent_client3.K8s)(import_kubernetes_fluent_client3.kind.Deployment).Apply(watchDeployment, { force });
@@ -1342,7 +1326,7 @@ async function setupWatcher(assets, hash, force) {
1342
1326
  // src/lib/assets/loader.ts
1343
1327
  var import_child_process = require("child_process");
1344
1328
  function loadCapabilities(path) {
1345
- return new Promise((resolve5, reject) => {
1329
+ return new Promise((resolve6, reject) => {
1346
1330
  const program2 = (0, import_child_process.fork)(path, {
1347
1331
  env: {
1348
1332
  ...process.env,
@@ -1356,7 +1340,7 @@ function loadCapabilities(path) {
1356
1340
  for (const capability of capabilities) {
1357
1341
  console.info(`Registered Pepr Capability "${capability.name}"`);
1358
1342
  }
1359
- resolve5(capabilities);
1343
+ resolve6(capabilities);
1360
1344
  });
1361
1345
  program2.on("error", (error) => {
1362
1346
  reject(error);
@@ -1367,7 +1351,7 @@ function loadCapabilities(path) {
1367
1351
  // src/lib/assets/yaml.ts
1368
1352
  var import_client_node = require("@kubernetes/client-node");
1369
1353
  var import_crypto2 = __toESM(require("crypto"));
1370
- var import_fs3 = require("fs");
1354
+ var import_fs2 = require("fs");
1371
1355
  async function overridesFile({ hash, name: name2, image, config, apiToken, capabilities }, path) {
1372
1356
  const rbacOverrides = clusterRole(name2, capabilities, config.rbacMode, config.rbac).rules;
1373
1357
  const overrides = {
@@ -1518,7 +1502,7 @@ async function overridesFile({ hash, name: name2, image, config, apiToken, capab
1518
1502
  }
1519
1503
  }
1520
1504
  };
1521
- await import_fs3.promises.writeFile(path, (0, import_client_node.dumpYaml)(overrides, { noRefs: true, forceQuotes: true }));
1505
+ await import_fs2.promises.writeFile(path, (0, import_client_node.dumpYaml)(overrides, { noRefs: true, forceQuotes: true }));
1522
1506
  }
1523
1507
  function zarfYaml({ name: name2, image, config }, path) {
1524
1508
  const zarfCfg = {
@@ -1575,22 +1559,22 @@ function zarfYamlChart({ name: name2, image, config }, path) {
1575
1559
  }
1576
1560
  async function allYaml(assets, imagePullSecret) {
1577
1561
  const { name: name2, tls, apiToken, path, config } = assets;
1578
- const code = await import_fs3.promises.readFile(path);
1562
+ const code = await import_fs2.promises.readFile(path);
1579
1563
  assets.hash = import_crypto2.default.createHash("sha256").update(code).digest("hex");
1580
1564
  const mutateWebhook = await webhookConfig(assets, "mutate", assets.config.webhookTimeout);
1581
1565
  const validateWebhook = await webhookConfig(assets, "validate", assets.config.webhookTimeout);
1582
- const watchDeployment = watcher(assets, assets.hash, assets.buildTimestamp, imagePullSecret);
1566
+ const watchDeployment = getWatcher(assets, assets.hash, assets.buildTimestamp, imagePullSecret);
1583
1567
  const resources = [
1584
- namespace(assets.config.customLabels?.namespace),
1568
+ getNamespace(assets.config.customLabels?.namespace),
1585
1569
  clusterRole(name2, assets.capabilities, config.rbacMode, config.rbac),
1586
1570
  clusterRoleBinding(name2),
1587
1571
  serviceAccount(name2),
1588
1572
  apiTokenSecret(name2, apiToken),
1589
1573
  tlsSecret(name2, tls),
1590
- deployment(assets, assets.hash, assets.buildTimestamp, imagePullSecret),
1574
+ getDeployment(assets, assets.hash, assets.buildTimestamp, imagePullSecret),
1591
1575
  service(name2),
1592
1576
  watcherService(name2),
1593
- moduleSecret(name2, code, assets.hash),
1577
+ getModuleSecret(name2, code, assets.hash),
1594
1578
  storeRole(name2),
1595
1579
  storeRoleBinding(name2)
1596
1580
  ];
@@ -1623,7 +1607,7 @@ function clusterRoleTemplate() {
1623
1607
  {{- end }}
1624
1608
  `;
1625
1609
  }
1626
- function nsTemplate() {
1610
+ function namespaceTemplate() {
1627
1611
  return `
1628
1612
  apiVersion: v1
1629
1613
  kind: Namespace
@@ -1860,16 +1844,16 @@ function serviceMonitorTemplate(name2) {
1860
1844
  }
1861
1845
 
1862
1846
  // src/lib/assets/index.ts
1863
- var import_fs5 = require("fs");
1847
+ var import_fs4 = require("fs");
1864
1848
 
1865
1849
  // src/lib/filesystemService.ts
1866
- var import_fs4 = require("fs");
1850
+ var import_fs3 = require("fs");
1867
1851
  async function createDirectoryIfNotExists(path) {
1868
1852
  try {
1869
- await import_fs4.promises.access(path);
1853
+ await import_fs3.promises.access(path);
1870
1854
  } catch (error) {
1871
1855
  if (error.code === "ENOENT") {
1872
- await import_fs4.promises.mkdir(path, { recursive: true });
1856
+ await import_fs3.promises.mkdir(path, { recursive: true });
1873
1857
  } else {
1874
1858
  throw error;
1875
1859
  }
@@ -1972,10 +1956,10 @@ var Assets = class {
1972
1956
  await Promise.all(
1973
1957
  Object.values(helm.dirs).sort((l, r) => l.split("/").length - r.split("/").length).map(async (dir) => await createDirectoryIfNotExists(dir))
1974
1958
  );
1975
- const code = await import_fs5.promises.readFile(this.path);
1959
+ const code = await import_fs4.promises.readFile(this.path);
1976
1960
  const pairs = [
1977
1961
  [helm.files.chartYaml, () => dedent(chartYaml(this.config.uuid, this.config.description || ""))],
1978
- [helm.files.namespaceYaml, () => dedent(nsTemplate())],
1962
+ [helm.files.namespaceYaml, () => dedent(namespaceTemplate())],
1979
1963
  [helm.files.watcherServiceYaml, () => toYaml(watcherService(this.name))],
1980
1964
  [helm.files.admissionServiceYaml, () => toYaml(service(this.name))],
1981
1965
  [helm.files.tlsSecretYaml, () => toYaml(tlsSecret(this.name, this.tls))],
@@ -1985,28 +1969,28 @@ var Assets = class {
1985
1969
  [helm.files.clusterRoleYaml, () => dedent(clusterRoleTemplate())],
1986
1970
  [helm.files.clusterRoleBindingYaml, () => toYaml(clusterRoleBinding(this.name))],
1987
1971
  [helm.files.serviceAccountYaml, () => toYaml(serviceAccount(this.name))],
1988
- [helm.files.moduleSecretYaml, () => toYaml(moduleSecret(this.name, code, this.hash))]
1972
+ [helm.files.moduleSecretYaml, () => toYaml(getModuleSecret(this.name, code, this.hash))]
1989
1973
  ];
1990
- await Promise.all(pairs.map(async ([file, content]) => await import_fs5.promises.writeFile(file, content())));
1974
+ await Promise.all(pairs.map(async ([file, content]) => await import_fs4.promises.writeFile(file, content())));
1991
1975
  await overridesFile(this, helm.files.valuesYaml);
1992
1976
  const [mutateWebhook, validateWebhook] = await Promise.all([
1993
1977
  webhookConfig(this, "mutate", this.config.webhookTimeout),
1994
1978
  webhookConfig(this, "validate", this.config.webhookTimeout)
1995
1979
  ]);
1996
1980
  if (validateWebhook || mutateWebhook) {
1997
- await import_fs5.promises.writeFile(helm.files.admissionDeploymentYaml, dedent(admissionDeployTemplate(this.buildTimestamp)));
1998
- await import_fs5.promises.writeFile(helm.files.admissionServiceMonitorYaml, dedent(serviceMonitorTemplate("admission")));
1981
+ await import_fs4.promises.writeFile(helm.files.admissionDeploymentYaml, dedent(admissionDeployTemplate(this.buildTimestamp)));
1982
+ await import_fs4.promises.writeFile(helm.files.admissionServiceMonitorYaml, dedent(serviceMonitorTemplate("admission")));
1999
1983
  }
2000
1984
  if (mutateWebhook) {
2001
- await import_fs5.promises.writeFile(helm.files.mutationWebhookYaml, createWebhookYaml(this, mutateWebhook));
1985
+ await import_fs4.promises.writeFile(helm.files.mutationWebhookYaml, createWebhookYaml(this, mutateWebhook));
2002
1986
  }
2003
1987
  if (validateWebhook) {
2004
- await import_fs5.promises.writeFile(helm.files.validationWebhookYaml, createWebhookYaml(this, validateWebhook));
1988
+ await import_fs4.promises.writeFile(helm.files.validationWebhookYaml, createWebhookYaml(this, validateWebhook));
2005
1989
  }
2006
- const watchDeployment = watcher(this, this.hash, this.buildTimestamp);
1990
+ const watchDeployment = getWatcher(this, this.hash, this.buildTimestamp);
2007
1991
  if (watchDeployment) {
2008
- await import_fs5.promises.writeFile(helm.files.watcherDeploymentYaml, dedent(watcherDeployTemplate(this.buildTimestamp)));
2009
- await import_fs5.promises.writeFile(helm.files.watcherServiceMonitorYaml, dedent(serviceMonitorTemplate("watcher")));
1992
+ await import_fs4.promises.writeFile(helm.files.watcherDeploymentYaml, dedent(watcherDeployTemplate(this.buildTimestamp)));
1993
+ await import_fs4.promises.writeFile(helm.files.watcherServiceMonitorYaml, dedent(serviceMonitorTemplate("watcher")));
2010
1994
  }
2011
1995
  } catch (err) {
2012
1996
  console.error(`Error generating helm chart: ${err.message}`);
@@ -2222,7 +2206,7 @@ var gitIgnore = "# Ignore node_modules and Pepr build artifacts\nnode_modules\nd
2222
2206
  var readmeMd = '# Pepr Module\n\nThis is a Pepr Module. [Pepr](https://github.com/defenseunicorns/pepr) is a type-safe Kubernetes middleware system.\n\nThe `capabilities` directory contains all the capabilities for this module. By default,\na capability is a single typescript file in the format of `capability-name.ts` that is\nimported in the root `pepr.ts` file as `import { HelloPepr } from "./capabilities/hello-pepr";`.\nBecause this is typescript, you can organize this however you choose, e.g. creating a sub-folder\nper-capability or common logic in shared files or folders.\n\nExample Structure:\n\n```\nModule Root\n\u251C\u2500\u2500 package.json\n\u251C\u2500\u2500 pepr.ts\n\u2514\u2500\u2500 capabilities\n \u251C\u2500\u2500 example-one.ts\n \u251C\u2500\u2500 example-three.ts\n \u2514\u2500\u2500 example-two.ts\n```\n';
2223
2207
  var peprTS = 'import { PeprModule } from "pepr";\n// cfg loads your pepr configuration from package.json\nimport cfg from "./package.json";\n\n// HelloPepr is a demo capability that is included with Pepr. Comment or delete the line below to remove it.\nimport { HelloPepr } from "./capabilities/hello-pepr";\n\n/**\n * This is the main entrypoint for this Pepr module. It is run when the module is started.\n * This is where you register your Pepr configurations and capabilities.\n */\nnew PeprModule(cfg, [\n // "HelloPepr" is a demo capability that is included with Pepr. Comment or delete the line below to remove it.\n HelloPepr,\n\n // Your additional capabilities go here\n]);\n';
2224
2208
  var helloPeprTS = 'import {\n Capability,\n K8s,\n Log,\n PeprMutateRequest,\n RegisterKind,\n a,\n fetch,\n fetchStatus,\n kind,\n} from "pepr";\nimport { MockAgent, setGlobalDispatcher } from "undici";\n\n/**\n * The HelloPepr Capability is an example capability to demonstrate some general concepts of Pepr.\n * To test this capability you run `pepr dev`and then run the following command:\n * `kubectl apply -f capabilities/hello-pepr.samples.yaml`\n */\nexport const HelloPepr = new Capability({\n name: "hello-pepr",\n description: "A simple example capability to show how things work.",\n namespaces: ["pepr-demo", "pepr-demo-2"],\n});\n\n// Use the \'When\' function to create a new action, use \'Store\' to persist data\nconst { When, Store } = HelloPepr;\n\n/**\n * ---------------------------------------------------------------------------------------------------\n * Mutate Action (Namespace) *\n * ---------------------------------------------------------------------------------------------------\n *\n * This action removes the label `remove-me` when a Namespace is created.\n * Note we don\'t need to specify the namespace here, because we\'ve already specified\n * it in the Capability definition above.\n */\nWhen(a.Namespace)\n .IsCreated()\n .Mutate(ns => ns.RemoveLabel("remove-me"));\n\n/**\n * ---------------------------------------------------------------------------------------------------\n * Watch Action with K8s SSA (Namespace) *\n * ---------------------------------------------------------------------------------------------------\n *\n * This action watches for the `pepr-demo-2` namespace to be created, then creates a ConfigMap with\n * the name `pepr-ssa-demo` and adds the namespace UID to the ConfigMap data. Because Pepr uses\n * server-side apply for this operation, the ConfigMap will be created or updated if it already exists.\n */\nWhen(a.Namespace)\n .IsCreated()\n .WithName("pepr-demo-2")\n .Watch(async ns => {\n Log.info("Namespace pepr-demo-2 was created.");\n\n try {\n // Apply the ConfigMap using K8s server-side apply\n await K8s(kind.ConfigMap).Apply({\n metadata: {\n name: "pepr-ssa-demo",\n namespace: "pepr-demo-2",\n },\n data: {\n "ns-uid": ns.metadata.uid,\n },\n });\n } catch (error) {\n // You can use the Log object to log messages to the Pepr controller pod\n Log.error(error, "Failed to apply ConfigMap using server-side apply.");\n }\n\n // You can share data between actions using the Store, including between different types of actions\n Store.setItem("watch-data", "This data was stored by a Watch Action.");\n });\n\n/**\n * ---------------------------------------------------------------------------------------------------\n * Mutate Action (CM Example 1) *\n * ---------------------------------------------------------------------------------------------------\n *\n * This is a single action. They can be in the same file or put imported from other files.\n * In this example, when a ConfigMap is created with the name `example-1`, then add a label and annotation.\n *\n * Equivalent to manually running:\n * `kubectl label configmap example-1 pepr=was-here`\n * `kubectl annotate configmap example-1 pepr.dev=annotations-work-too`\n */\nWhen(a.ConfigMap)\n .IsCreated()\n .WithName("example-1")\n .Mutate(request => {\n request\n .SetLabel("pepr", "was-here")\n .SetAnnotation("pepr.dev", "annotations-work-too");\n\n // Use the Store to persist data between requests and Pepr controller pods\n Store.setItem("example-1", "was-here");\n\n // This data is written asynchronously and can be read back via `Store.getItem()` or `Store.subscribe()`\n Store.setItem("example-1-data", JSON.stringify(request.Raw.data));\n });\n\n/**\n * ---------------------------------------------------------------------------------------------------\n * Mutate & Validate Actions (CM Example 2) *\n * ---------------------------------------------------------------------------------------------------\n *\n * This combines 3 different types of actions: \'Mutate\', \'Validate\', and \'Watch\'. The order\n * of the actions is required, but each action is optional. In this example, when a ConfigMap is created\n * with the name `example-2`, then add a label and annotation, validate that the ConfigMap has the label\n * `pepr`, and log the request.\n */\nWhen(a.ConfigMap)\n .IsCreated()\n .WithName("example-2")\n .Mutate(request => {\n // This Mutate Action will mutate the request before it is persisted to the cluster\n\n // Use `request.Merge()` to merge the new data with the existing data\n request.Merge({\n metadata: {\n labels: {\n pepr: "was-here",\n },\n annotations: {\n "pepr.dev": "annotations-work-too",\n },\n },\n });\n })\n .Validate(request => {\n // This Validate Action will validate the request before it is persisted to the cluster\n\n // Approve the request if the ConfigMap has the label \'pepr\'\n if (request.HasLabel("pepr")) {\n return request.Approve();\n }\n\n // Otherwise, deny the request with an error message (optional)\n return request.Deny("ConfigMap must have label \'pepr\'");\n })\n .Watch((cm, phase) => {\n // This Watch Action will watch the ConfigMap after it has been persisted to the cluster\n Log.info(cm, `ConfigMap was ${phase} with the name example-2`);\n });\n\n/**\n * ---------------------------------------------------------------------------------------------------\n * Mutate Action (CM Example 2a) *\n * ---------------------------------------------------------------------------------------------------\n *\n * This action shows a simple validation that will deny any ConfigMap that has the\n * annotation `evil`. Note that the `Deny()` function takes an optional second parameter that is a\n * user-defined status code to return.\n */\nWhen(a.ConfigMap)\n .IsCreated()\n .Validate(request => {\n if (request.HasAnnotation("evil")) {\n return request.Deny("No evil CM annotations allowed.", 400);\n }\n\n return request.Approve();\n });\n\n/**\n * ---------------------------------------------------------------------------------------------------\n * Mutate Action (CM Example 3) *\n * ---------------------------------------------------------------------------------------------------\n *\n * This action combines different styles. Unlike the previous actions, this one will look\n * for any ConfigMap in the `pepr-demo` namespace that has the label `change=by-label` during either\n * CREATE or UPDATE. Note that all conditions added such as `WithName()`, `WithLabel()`, `InNamespace()`,\n * are ANDs so all conditions must be true for the request to be processed.\n */\nWhen(a.ConfigMap)\n .IsCreatedOrUpdated()\n .WithLabel("change", "by-label")\n .Mutate(request => {\n // The K8s object e are going to mutate\n const cm = request.Raw;\n\n // Get the username and uid of the K8s request\n const { username, uid } = request.Request.userInfo;\n\n // Store some data about the request in the configmap\n cm.data["username"] = username;\n cm.data["uid"] = uid;\n\n // You can still mix other ways of making changes too\n request.SetAnnotation("pepr.dev", "making-waves");\n });\n\n// This action validates the label `change=by-label` is deleted\nWhen(a.ConfigMap)\n .IsDeleted()\n .WithLabel("change", "by-label")\n .Validate(request => {\n // Log and then always approve the request\n Log.info("CM with label \'change=by-label\' was deleted.");\n return request.Approve();\n });\n\n/**\n * ---------------------------------------------------------------------------------------------------\n * Mutate Action (CM Example 4) *\n * ---------------------------------------------------------------------------------------------------\n *\n * This action show how you can use the `Mutate()` function without an inline function.\n * This is useful if you want to keep your actions small and focused on a single task,\n * or if you want to reuse the same function in multiple actions.\n */\nWhen(a.ConfigMap).IsCreated().WithName("example-4").Mutate(example4Cb);\n\n// This function uses the complete type definition, but is not required.\nfunction example4Cb(cm: PeprMutateRequest<a.ConfigMap>) {\n cm.SetLabel("pepr.dev/first", "true");\n cm.SetLabel("pepr.dev/second", "true");\n cm.SetLabel("pepr.dev/third", "true");\n}\n\n/**\n * ---------------------------------------------------------------------------------------------------\n * Mutate Action (CM Example 4a) *\n * ---------------------------------------------------------------------------------------------------\n *\n * This is the same as Example 4, except this only operates on a CM in the `pepr-demo-2` namespace.\n * Note because the Capability defines namespaces, the namespace specified here must be one of those.\n * Alternatively, you can remove the namespace from the Capability definition and specify it here.\n */\nWhen(a.ConfigMap)\n .IsCreated()\n .InNamespace("pepr-demo-2")\n .WithName("example-4a")\n .Mutate(example4Cb);\n\n/**\n * ---------------------------------------------------------------------------------------------------\n * Mutate Action (CM Example 5) *\n * ---------------------------------------------------------------------------------------------------\n *\n * This action is a bit more complex. It will look for any ConfigMap in the `pepr-demo`\n * namespace that has the label `chuck-norris` during CREATE. When it finds one, it will fetch a\n * random Chuck Norris joke from the API and add it to the ConfigMap. This is a great example of how\n * you can use Pepr to make changes to your K8s objects based on external data.\n *\n * Note the use of the `async` keyword. This is required for any action that uses `await` or `fetch()`.\n *\n * Also note we are passing a type to the `fetch()` function. This is optional, but it will help you\n * avoid mistakes when working with the data returned from the API. You can also use the `as` keyword to\n * cast the data returned from the API.\n *\n * These are equivalent:\n * ```ts\n * const joke = await fetch<TheChuckNorrisJoke>("https://icanhazdadjoke.com/");\n * const joke = await fetch("https://icanhazdadjoke.com/") as TheChuckNorrisJoke;\n * ```\n *\n * Alternatively, you can drop the type completely:\n *\n * ```ts\n * fetch("https://icanhazdadjoke.com")\n * ```\n */\ninterface TheChuckNorrisJoke {\n id: string;\n joke: string;\n status: number;\n}\n\nWhen(a.ConfigMap)\n .IsCreatedOrUpdated()\n .WithLabel("chuck-norris")\n .Mutate(cm => cm.SetLabel("got-jokes", "true"))\n .Watch(async cm => {\n const jokeURL = "https://icanhazdadjoke.com";\n\n const mockAgent: MockAgent = new MockAgent();\n setGlobalDispatcher(mockAgent);\n const mockClient = mockAgent.get(jokeURL);\n mockClient.intercept({ path: "/", method: "GET" }).reply(\n 200,\n {\n id: "R7UfaahVfFd",\n joke: "Funny joke goes here.",\n status: 200,\n },\n {\n headers: {\n "Content-Type": "application/json; charset=utf-8",\n },\n },\n );\n\n // Try/catch is not needed as a response object will always be returned\n const response = await fetch<TheChuckNorrisJoke>(jokeURL, {\n headers: {\n Accept: "application/json",\n },\n });\n\n // Instead, check the `response.ok` field\n if (response.ok) {\n const { joke } = response.data;\n // Add Joke to the Store\n await Store.setItemAndWait(jokeURL, joke);\n // Add the Chuck Norris joke to the configmap\n try {\n await K8s(kind.ConfigMap).Apply({\n metadata: {\n name: cm.metadata.name,\n namespace: cm.metadata.namespace,\n },\n data: {\n "chuck-says": Store.getItem(jokeURL),\n },\n });\n } catch (error) {\n Log.error(error, "Failed to apply ConfigMap using server-side apply.", {\n cm,\n });\n }\n }\n\n // You can also assert on different HTTP response codes\n if (response.status === fetchStatus.NOT_FOUND) {\n // Do something else\n return;\n }\n });\n\n/**\n * ---------------------------------------------------------------------------------------------------\n * Mutate Action (Secret Base64 Handling) *\n * ---------------------------------------------------------------------------------------------------\n *\n * The K8s JS client provides incomplete support for base64 encoding/decoding handling for secrets,\n * unlike the GO client. To make this less painful, Pepr automatically handles base64 encoding/decoding\n * secret data before and after the action is executed.\n */\nWhen(a.Secret)\n .IsCreated()\n .WithName("secret-1")\n .Mutate(request => {\n const secret = request.Raw;\n\n // This will be encoded at the end of all processing back to base64: "Y2hhbmdlLXdpdGhvdXQtZW5jb2Rpbmc="\n secret.data.magic = "change-without-encoding";\n\n // You can modify the data directly, and it will be encoded at the end of all processing\n secret.data.example += " - modified by Pepr";\n });\n\n/**\n * ---------------------------------------------------------------------------------------------------\n * Mutate Action (Untyped Custom Resource) *\n * ---------------------------------------------------------------------------------------------------\n *\n * Out of the box, Pepr supports all the standard Kubernetes objects. However, you can also create\n * your own types. This is useful if you are working with an Operator that creates custom resources.\n * There are two ways to do this, the first is to use the `When()` function with a `GenericKind`,\n * the second is to create a new class that extends `GenericKind` and use the `RegisterKind()` function.\n *\n * This example shows how to use the `When()` function with a `GenericKind`. Note that you\n * must specify the `group`, `version`, and `kind` of the object (if applicable). This is how Pepr knows\n * if the action should be triggered or not. Since we are using a `GenericKind`,\n * Pepr will not be able to provide any intellisense for the object, so you will need to refer to the\n * Kubernetes API documentation for the object you are working with.\n *\n * You will need to wait for the CRD in `hello-pepr.samples.yaml` to be created, then you can apply\n *\n * ```yaml\n * apiVersion: pepr.dev/v1\n * kind: Unicorn\n * metadata:\n * name: example-1\n * namespace: pepr-demo\n * spec:\n * message: replace-me\n * counter: 0\n * ```\n */\nWhen(a.GenericKind, {\n group: "pepr.dev",\n version: "v1",\n kind: "Unicorn",\n})\n .IsCreated()\n .WithName("example-1")\n .Mutate(request => {\n request.Merge({\n spec: {\n message: "Hello Pepr without type data!",\n counter: Math.random(),\n },\n });\n });\n\n/**\n * ---------------------------------------------------------------------------------------------------\n * Mutate Action (Typed Custom Resource) *\n * ---------------------------------------------------------------------------------------------------\n *\n * This example shows how to use the `RegisterKind()` function to create a new type. This is useful\n * if you are working with an Operator that creates custom resources and you want to have intellisense\n * for the object. Note that you must specify the `group`, `version`, and `kind` of the object (if applicable)\n * as this is how Pepr knows if the action should be triggered or not.\n *\n * Once you register a new Kind with Pepr, you can use the `When()` function with the new Kind. Ideally,\n * you should register custom Kinds at the top of your Capability file or Pepr Module so they are available\n * to all actions, but we are putting it here for demonstration purposes.\n *\n * You will need to wait for the CRD in `hello-pepr.samples.yaml` to be created, then you can apply\n *\n * ```yaml\n * apiVersion: pepr.dev/v1\n * kind: Unicorn\n * metadata:\n * name: example-2\n * namespace: pepr-demo\n * spec:\n * message: replace-me\n * counter: 0\n * ```*\n */\nclass UnicornKind extends a.GenericKind {\n spec: {\n /**\n * JSDoc comments can be added to explain more details about the field.\n *\n * @example\n * ```ts\n * request.Raw.spec.message = "Hello Pepr!";\n * ```\n * */\n message: string;\n counter: number;\n };\n}\n\nRegisterKind(UnicornKind, {\n group: "pepr.dev",\n version: "v1",\n kind: "Unicorn",\n});\n\nWhen(UnicornKind)\n .IsCreated()\n .WithName("example-2")\n .Mutate(request => {\n request.Merge({\n spec: {\n message: "Hello Pepr with type data!",\n counter: Math.random(),\n },\n });\n });\n\n/**\n * A callback function that is called once the Pepr Store is fully loaded.\n */\nStore.onReady(data => {\n Log.info(data, "Pepr Store Ready");\n});\n';
2225
- var packageJSON = { name: "pepr", description: "Kubernetes application engine", author: "Defense Unicorns", homepage: "https://github.com/defenseunicorns/pepr", license: "Apache-2.0", bin: "dist/cli.js", repository: "defenseunicorns/pepr", engines: { node: ">=18.0.0" }, files: ["/dist", "/src", "!src/**/*.test.ts", "!dist/**/*.test.d.ts*"], version: "0.42.0", main: "dist/lib.js", types: "dist/lib.d.ts", scripts: { ci: "npm ci", "gen-data-json": "node hack/build-template-data.js", prebuild: "rm -fr dist/* && npm run gen-data-json", version: "node scripts/set-version.js", build: "tsc && node build.mjs && npm pack", "build:image": "npm run build && docker buildx build --output type=docker --tag pepr:dev .", test: "npm run test:unit && npm run test:journey", "test:unit": "npm run gen-data-json && jest src --coverage --detectOpenHandles --coverageDirectory=./coverage --testPathIgnorePatterns='cosign.e2e.test.ts'", "test:journey": "npm run test:journey:k3d && npm run build && npm run test:journey:image && npm run test:journey:run", "test:journey:prep": "if [ ! -d ./pepr-upgrade-test ]; then git clone https://github.com/defenseunicorns/pepr-upgrade-test.git ; fi", "test:journey-wasm": "npm run test:journey:k3d && npm run build && npm run test:journey:image && npm run test:journey:run-wasm", "test:journey:k3d": "k3d cluster delete pepr-dev && k3d cluster create pepr-dev --k3s-arg '--debug@server:0' --wait && kubectl rollout status deployment -n kube-system", "test:journey:image": "docker buildx build --output type=docker --tag pepr:dev . && k3d image import pepr:dev -c pepr-dev", "test:journey:run": "jest --detectOpenHandles journey/entrypoint.test.ts && npm run test:journey:prep && npm run test:journey:upgrade", "test:journey:run-wasm": "jest --detectOpenHandles journey/entrypoint-wasm.test.ts", "test:journey:upgrade": "npm run test:journey:k3d && npm run test:journey:image && jest --detectOpenHandles journey/pepr-upgrade.test.ts", "format:check": "eslint src && prettier src --check", "format:fix": "eslint src --fix && prettier src --write", prepare: `if [ "$NODE_ENV" != 'production' ]; then husky; fi` }, dependencies: { "@types/ramda": "0.30.2", express: "4.21.2", "fast-json-patch": "3.1.1", "follow-redirects": "1.15.9", "http-status-codes": "^2.3.0", "json-pointer": "^0.6.2", "kubernetes-fluent-client": "3.3.7", pino: "9.5.0", "pino-pretty": "13.0.0", "prom-client": "15.1.3", ramda: "0.30.1", sigstore: "3.0.0" }, devDependencies: { "@commitlint/cli": "19.6.0", "@commitlint/config-conventional": "19.6.0", "@fast-check/jest": "^2.0.1", "@jest/globals": "29.7.0", "@types/eslint": "9.6.1", "@types/express": "5.0.0", "@types/follow-redirects": "1.14.4", "@types/json-pointer": "^1.0.34", "@types/node": "22.x.x", "@types/node-forge": "1.3.11", "@types/uuid": "10.0.0", "fast-check": "^3.19.0", husky: "^9.1.6", jest: "29.7.0", "js-yaml": "^4.1.0", "ts-jest": "29.2.5", undici: "^7.0.1" }, peerDependencies: { "@types/prompts": "2.4.9", "@typescript-eslint/eslint-plugin": "7.18.0", "@typescript-eslint/parser": "7.18.0", commander: "12.1.0", esbuild: "0.23.0", eslint: "8.57.0", "node-forge": "1.3.1", prettier: "3.3.3", prompts: "2.4.2", typescript: "5.3.3", uuid: "10.0.0" } };
2209
+ var packageJSON = { name: "pepr", description: "Kubernetes application engine", author: "Defense Unicorns", homepage: "https://github.com/defenseunicorns/pepr", license: "Apache-2.0", bin: "dist/cli.js", repository: "defenseunicorns/pepr", engines: { node: ">=18.0.0" }, files: ["/dist", "/src", "!src/**/*.test.ts", "!dist/**/*.test.d.ts*"], version: "0.42.1", main: "dist/lib.js", types: "dist/lib.d.ts", scripts: { ci: "npm ci", "gen-data-json": "node hack/build-template-data.js", prebuild: "rm -fr dist/* && npm run gen-data-json", version: "node scripts/set-version.js", build: "tsc && node build.mjs && npm pack", "build:image": "npm run build && docker buildx build --output type=docker --tag pepr:dev .", test: "npm run test:unit && npm run test:journey", "test:unit": "npm run gen-data-json && jest src --coverage --detectOpenHandles --coverageDirectory=./coverage --testPathIgnorePatterns='cosign.e2e.test.ts'", "test:journey": "npm run test:journey:k3d && npm run build && npm run test:journey:image && npm run test:journey:run", "test:journey:prep": "if [ ! -d ./pepr-upgrade-test ]; then git clone https://github.com/defenseunicorns/pepr-upgrade-test.git ; fi", "test:journey-wasm": "npm run test:journey:k3d && npm run build && npm run test:journey:image && npm run test:journey:run-wasm", "test:journey:k3d": "k3d cluster delete pepr-dev && k3d cluster create pepr-dev --k3s-arg '--debug@server:0' --wait && kubectl rollout status deployment -n kube-system", "test:journey:image": "docker buildx build --output type=docker --tag pepr:dev . && k3d image import pepr:dev -c pepr-dev", "test:journey:run": "jest --detectOpenHandles journey/entrypoint.test.ts && npm run test:journey:prep && npm run test:journey:upgrade", "test:journey:run-wasm": "jest --detectOpenHandles journey/entrypoint-wasm.test.ts", "test:journey:upgrade": "npm run test:journey:k3d && npm run test:journey:image && jest --detectOpenHandles journey/pepr-upgrade.test.ts", "format:check": "eslint src && prettier src --check", "format:fix": "eslint src --fix && prettier src --write", prepare: `if [ "$NODE_ENV" != 'production' ]; then husky; fi` }, dependencies: { "@types/ramda": "0.30.2", express: "4.21.2", "fast-json-patch": "3.1.1", "follow-redirects": "1.15.9", "http-status-codes": "^2.3.0", "json-pointer": "^0.6.2", "kubernetes-fluent-client": "3.3.7", pino: "9.5.0", "pino-pretty": "13.0.0", "prom-client": "15.1.3", ramda: "0.30.1", sigstore: "3.0.0" }, devDependencies: { "@commitlint/cli": "19.6.0", "@commitlint/config-conventional": "19.6.0", "@fast-check/jest": "^2.0.1", "@jest/globals": "29.7.0", "@types/eslint": "9.6.1", "@types/express": "5.0.0", "@types/follow-redirects": "1.14.4", "@types/json-pointer": "^1.0.34", "@types/node": "22.x.x", "@types/node-forge": "1.3.11", "@types/uuid": "10.0.0", "fast-check": "^3.19.0", husky: "^9.1.6", jest: "29.7.0", "js-yaml": "^4.1.0", "ts-jest": "29.2.5", undici: "^7.0.1" }, peerDependencies: { "@types/prompts": "2.4.9", "@typescript-eslint/eslint-plugin": "7.18.0", "@typescript-eslint/parser": "7.18.0", commander: "12.1.0", esbuild: "0.23.0", eslint: "8.57.0", "node-forge": "1.3.1", prettier: "3.3.3", prompts: "2.4.2", typescript: "5.3.3", uuid: "10.0.0" } };
2226
2210
 
2227
2211
  // src/templates/pepr.code-snippets.json
2228
2212
  var pepr_code_snippets_default = {
@@ -2281,7 +2265,7 @@ var tsconfig_module_default = {
2281
2265
  };
2282
2266
 
2283
2267
  // src/cli/init/utils.ts
2284
- var import_fs6 = require("fs");
2268
+ var import_fs5 = require("fs");
2285
2269
  function sanitizeName(name2) {
2286
2270
  if (typeof name2 !== "string") {
2287
2271
  throw TypeError(
@@ -2295,7 +2279,7 @@ function sanitizeName(name2) {
2295
2279
  }
2296
2280
  async function createDir(dir) {
2297
2281
  try {
2298
- await import_fs6.promises.mkdir(dir);
2282
+ await import_fs5.promises.mkdir(dir);
2299
2283
  } catch (err) {
2300
2284
  if (err && err.code === "EEXIST") {
2301
2285
  throw new Error(`Directory ${dir} already exists`);
@@ -2308,7 +2292,7 @@ function write(path, data) {
2308
2292
  if (typeof data !== "string") {
2309
2293
  data = JSON.stringify(data, null, 2);
2310
2294
  }
2311
- return import_fs6.promises.writeFile(path, data);
2295
+ return import_fs5.promises.writeFile(path, data);
2312
2296
  }
2313
2297
 
2314
2298
  // src/cli/init/templates.ts
@@ -2404,9 +2388,12 @@ var eslint = {
2404
2388
  data: eslintrc_template_default
2405
2389
  };
2406
2390
 
2391
+ // src/cli/build.ts
2392
+ var import_commander = require("commander");
2393
+
2407
2394
  // src/cli/format.ts
2408
2395
  var import_eslint = require("eslint");
2409
- var import_fs7 = require("fs");
2396
+ var import_fs6 = require("fs");
2410
2397
  var import_prettier = require("prettier");
2411
2398
  function format_default(program2) {
2412
2399
  program2.command("format").description("Lint and format this Pepr module").option("-v, --validate-only", "Do not modify files, only validate formatting").action(async (opts) => {
@@ -2439,14 +2426,14 @@ async function peprFormat(validateOnly) {
2439
2426
  await import_eslint.ESLint.outputFixes(results);
2440
2427
  }
2441
2428
  for (const { filePath } of results) {
2442
- const content = await import_fs7.promises.readFile(filePath, "utf8");
2429
+ const content = await import_fs6.promises.readFile(filePath, "utf8");
2443
2430
  const cfg = await (0, import_prettier.resolveConfig)(filePath);
2444
2431
  const formatted = await (0, import_prettier.format)(content, { filepath: filePath, ...cfg });
2445
2432
  if (validateOnly && formatted !== content) {
2446
2433
  hasFailure = true;
2447
2434
  console.error(`File ${filePath} is not formatted correctly`);
2448
2435
  } else {
2449
- await import_fs7.promises.writeFile(filePath, formatted);
2436
+ await import_fs6.promises.writeFile(filePath, formatted);
2450
2437
  }
2451
2438
  }
2452
2439
  return !hasFailure;
@@ -2457,10 +2444,27 @@ async function peprFormat(validateOnly) {
2457
2444
  }
2458
2445
  }
2459
2446
 
2460
- // src/cli/build.ts
2461
- var import_commander = require("commander");
2447
+ // src/lib/included-files.ts
2448
+ var import_fs7 = require("fs");
2449
+ async function createDockerfile(version3, description, includedFiles) {
2450
+ const file = `
2451
+ # Use an official Node.js runtime as the base image
2452
+ FROM ghcr.io/defenseunicorns/pepr/controller:v${version3}
2453
+
2454
+ LABEL description="${description}"
2455
+
2456
+ # Add the included files to the image
2457
+ ${includedFiles.map((f) => `ADD ${f} ${f}`).join("\n")}
2458
+
2459
+ `;
2460
+ await import_fs7.promises.writeFile("Dockerfile.controller", file, { encoding: "utf-8" });
2461
+ }
2462
2462
 
2463
2463
  // src/cli/build.helpers.ts
2464
+ var import_child_process2 = require("child_process");
2465
+ var import_esbuild = require("esbuild");
2466
+ var import_path2 = require("path");
2467
+ var import_fs8 = require("fs");
2464
2468
  function determineRbacMode(opts, cfg) {
2465
2469
  if (opts.rbacMode) {
2466
2470
  return opts.rbacMode;
@@ -2470,6 +2474,93 @@ function determineRbacMode(opts, cfg) {
2470
2474
  }
2471
2475
  return cfg.pepr.rbacMode || "admin";
2472
2476
  }
2477
+ async function handleCustomOutputDir(outputDir2) {
2478
+ const defaultOutputDir = "dist";
2479
+ if (outputDir2) {
2480
+ try {
2481
+ await createDirectoryIfNotExists(outputDir2);
2482
+ return outputDir2;
2483
+ } catch (error) {
2484
+ console.error(`Error creating output directory: ${error.message}`);
2485
+ process.exit(1);
2486
+ }
2487
+ }
2488
+ return defaultOutputDir;
2489
+ }
2490
+ function checkIronBankImage(registry, image, peprVersion) {
2491
+ return registry === "Iron Bank" ? `registry1.dso.mil/ironbank/opensource/defenseunicorns/pepr/controller:v${peprVersion}` : image;
2492
+ }
2493
+ function validImagePullSecret(imagePullSecretName) {
2494
+ if (imagePullSecretName) {
2495
+ const error = "Invalid imagePullSecret. Please provide a valid name as defined in RFC 1123.";
2496
+ if (sanitizeResourceName(imagePullSecretName) !== imagePullSecretName) {
2497
+ console.error(error);
2498
+ process.exit(1);
2499
+ }
2500
+ }
2501
+ }
2502
+ function handleCustomImage(customImage, registry) {
2503
+ let defaultImage = "";
2504
+ if (customImage) {
2505
+ if (registry) {
2506
+ console.error(`Custom Image and registry cannot be used together.`);
2507
+ process.exit(1);
2508
+ }
2509
+ defaultImage = customImage;
2510
+ }
2511
+ return defaultImage;
2512
+ }
2513
+ async function handleCustomImageBuild(includedFiles, peprVersion, description, image) {
2514
+ if (includedFiles.length > 0) {
2515
+ await createDockerfile(peprVersion, description, includedFiles);
2516
+ (0, import_child_process2.execSync)(`docker build --tag ${image} -f Dockerfile.controller .`, {
2517
+ stdio: "inherit"
2518
+ });
2519
+ (0, import_child_process2.execSync)(`docker push ${image}`, { stdio: "inherit" });
2520
+ }
2521
+ }
2522
+ function handleEmbedding(embed, path) {
2523
+ if (!embed) {
2524
+ console.info(`\u2705 Module built successfully at ${path}`);
2525
+ return;
2526
+ }
2527
+ }
2528
+ function handleValidCapabilityNames(capabilities) {
2529
+ try {
2530
+ validateCapabilityNames(capabilities);
2531
+ } catch (e) {
2532
+ console.error(`Error loading capability:`, e);
2533
+ process.exit(1);
2534
+ }
2535
+ }
2536
+ async function watchForChanges(ctxCfg, reloader) {
2537
+ const ctx = await (0, import_esbuild.context)(ctxCfg);
2538
+ if (reloader) {
2539
+ await ctx.watch();
2540
+ } else {
2541
+ await ctx.rebuild();
2542
+ await ctx.dispose();
2543
+ }
2544
+ return ctx;
2545
+ }
2546
+ async function generateYamlAndWriteToDisk(obj) {
2547
+ const { uuid, imagePullSecret, outputDir: outputDir2, assets, zarf } = obj;
2548
+ const yamlFile = `pepr-module-${uuid}.yaml`;
2549
+ const chartPath = `${uuid}-chart`;
2550
+ const yamlPath = (0, import_path2.resolve)(outputDir2, yamlFile);
2551
+ const yaml = await assets.allYaml(imagePullSecret);
2552
+ const zarfPath = (0, import_path2.resolve)(outputDir2, "zarf.yaml");
2553
+ let localZarf = "";
2554
+ if (zarf === "chart") {
2555
+ localZarf = assets.zarfYamlChart(chartPath);
2556
+ } else {
2557
+ localZarf = assets.zarfYaml(yamlFile);
2558
+ }
2559
+ await import_fs8.promises.writeFile(yamlPath, yaml);
2560
+ await import_fs8.promises.writeFile(zarfPath, localZarf);
2561
+ await assets.generateHelmChart(outputDir2);
2562
+ console.info(`\u2705 K8s resource for the module saved to ${yamlPath}`);
2563
+ }
2473
2564
 
2474
2565
  // src/cli/build.ts
2475
2566
  var peprTS2 = "pepr.ts";
@@ -2509,46 +2600,22 @@ function build_default(program2) {
2509
2600
  ["admin", "scoped"]
2510
2601
  )
2511
2602
  ).action(async (opts) => {
2512
- if (opts.outputDir) {
2513
- outputDir = opts.outputDir;
2514
- createDirectoryIfNotExists(outputDir).catch((error) => {
2515
- console.error(`Error creating output directory: ${error.message}`);
2516
- process.exit(1);
2517
- });
2518
- }
2603
+ outputDir = await handleCustomOutputDir(opts.outputDir);
2519
2604
  const buildModuleResult = await buildModule(void 0, opts.entryPoint, opts.embed);
2520
2605
  if (buildModuleResult?.cfg && buildModuleResult.path && buildModuleResult.uuid) {
2521
2606
  const { cfg, path, uuid } = buildModuleResult;
2522
2607
  const { includedFiles } = cfg.pepr;
2523
- let image = "";
2524
- if (opts.customImage) {
2525
- if (opts.registry) {
2526
- console.error(`Custom Image and registry cannot be used together.`);
2527
- process.exit(1);
2528
- }
2529
- image = opts.customImage;
2530
- }
2608
+ let image = handleCustomImage(opts.customImage, opts.registry);
2531
2609
  if (opts.timeout !== void 0) {
2532
2610
  cfg.pepr.webhookTimeout = opts.timeout;
2533
2611
  }
2534
2612
  if (opts.registryInfo !== void 0) {
2535
2613
  console.info(`Including ${includedFiles.length} files in controller image.`);
2536
2614
  image = `${opts.registryInfo}/custom-pepr-controller:${cfg.pepr.peprVersion}`;
2537
- if (includedFiles.length > 0) {
2538
- await createDockerfile(cfg.pepr.peprVersion, cfg.description, includedFiles);
2539
- (0, import_child_process2.execSync)(`docker build --tag ${image} -f Dockerfile.controller .`, {
2540
- stdio: "inherit"
2541
- });
2542
- (0, import_child_process2.execSync)(`docker push ${image}`, { stdio: "inherit" });
2543
- }
2544
- }
2545
- if (!opts.embed) {
2546
- console.info(`\u2705 Module built successfully at ${path}`);
2547
- return;
2548
- }
2549
- if (opts.version) {
2550
- cfg.pepr.peprVersion = opts.version;
2615
+ await handleCustomImageBuild(includedFiles, cfg.pepr.peprVersion, cfg.description, image);
2551
2616
  }
2617
+ handleEmbedding(opts.embed, path);
2618
+ opts.version ? cfg.pepr.peprVersion = opts.version : null;
2552
2619
  const assets = new Assets(
2553
2620
  {
2554
2621
  ...cfg.pepr,
@@ -2559,46 +2626,17 @@ function build_default(program2) {
2559
2626
  },
2560
2627
  path
2561
2628
  );
2562
- if (opts?.registry === "Iron Bank") {
2563
- console.info(
2564
- `
2565
- This command assumes the latest release. Pepr's Iron Bank image release cycle is dictated by renovate and is typically released a few days after the GitHub release.
2566
- As an alternative you may consider custom --custom-image to target a specific image and version.`
2567
- );
2568
- image = `registry1.dso.mil/ironbank/opensource/defenseunicorns/pepr/controller:v${cfg.pepr.peprVersion}`;
2569
- }
2570
- if (image !== "") {
2571
- assets.image = image;
2572
- }
2573
- if (opts.withPullSecret) {
2574
- if (sanitizeResourceName(opts.withPullSecret) !== opts.withPullSecret) {
2575
- console.error(
2576
- "Invalid imagePullSecret. Please provide a valid name as defined in RFC 1123."
2577
- );
2578
- process.exit(1);
2579
- }
2580
- }
2581
- const yamlFile = `pepr-module-${uuid}.yaml`;
2582
- const chartPath = `${uuid}-chart`;
2583
- const yamlPath = (0, import_path2.resolve)(outputDir, yamlFile);
2584
- const yaml = await assets.allYaml(opts.withPullSecret);
2585
- try {
2586
- validateCapabilityNames(assets.capabilities);
2587
- } catch (e) {
2588
- console.error(`Error loading capability:`, e);
2589
- process.exit(1);
2590
- }
2591
- const zarfPath = (0, import_path2.resolve)(outputDir, "zarf.yaml");
2592
- let zarf = "";
2593
- if (opts.zarf === "chart") {
2594
- zarf = assets.zarfYamlChart(chartPath);
2595
- } else {
2596
- zarf = assets.zarfYaml(yamlFile);
2597
- }
2598
- await import_fs8.promises.writeFile(yamlPath, yaml);
2599
- await import_fs8.promises.writeFile(zarfPath, zarf);
2600
- await assets.generateHelmChart(outputDir);
2601
- console.info(`\u2705 K8s resource for the module saved to ${yamlPath}`);
2629
+ image = checkIronBankImage(opts.registry, image, cfg.pepr.peprVersion);
2630
+ image !== "" ? assets.image = image : null;
2631
+ validImagePullSecret(opts.withPullSecret);
2632
+ handleValidCapabilityNames(assets.capabilities);
2633
+ await generateYamlAndWriteToDisk({
2634
+ uuid,
2635
+ outputDir,
2636
+ imagePullSecret: opts.withPullSecret,
2637
+ zarf: opts.zarf,
2638
+ assets
2639
+ });
2602
2640
  }
2603
2641
  });
2604
2642
  }
@@ -2606,19 +2644,19 @@ var externalLibs = Object.keys(dependencies);
2606
2644
  externalLibs.push("pepr");
2607
2645
  externalLibs.push("@kubernetes/client-node");
2608
2646
  async function loadModule(entryPoint = peprTS2) {
2609
- const entryPointPath = (0, import_path2.resolve)(".", entryPoint);
2610
- const modulePath = (0, import_path2.dirname)(entryPointPath);
2611
- const cfgPath = (0, import_path2.resolve)(modulePath, "package.json");
2647
+ const entryPointPath = (0, import_path3.resolve)(".", entryPoint);
2648
+ const modulePath = (0, import_path3.dirname)(entryPointPath);
2649
+ const cfgPath = (0, import_path3.resolve)(modulePath, "package.json");
2612
2650
  try {
2613
- await import_fs8.promises.access(cfgPath);
2614
- await import_fs8.promises.access(entryPointPath);
2651
+ await import_fs9.promises.access(cfgPath);
2652
+ await import_fs9.promises.access(entryPointPath);
2615
2653
  } catch (e) {
2616
2654
  console.error(
2617
2655
  `Could not find ${cfgPath} or ${entryPointPath} in the current directory. Please run this command from the root of your module's directory.`
2618
2656
  );
2619
2657
  process.exit(1);
2620
2658
  }
2621
- const moduleText = await import_fs8.promises.readFile(cfgPath, { encoding: "utf-8" });
2659
+ const moduleText = await import_fs9.promises.readFile(cfgPath, { encoding: "utf-8" });
2622
2660
  const cfg = JSON.parse(moduleText);
2623
2661
  const { uuid } = cfg.pepr;
2624
2662
  const name2 = `pepr-${uuid}.js`;
@@ -2631,23 +2669,17 @@ async function loadModule(entryPoint = peprTS2) {
2631
2669
  entryPointPath,
2632
2670
  modulePath,
2633
2671
  name: name2,
2634
- path: (0, import_path2.resolve)(outputDir, name2),
2672
+ path: (0, import_path3.resolve)(outputDir, name2),
2635
2673
  uuid
2636
2674
  };
2637
2675
  }
2638
2676
  async function buildModule(reloader, entryPoint = peprTS2, embed = true) {
2639
2677
  try {
2640
2678
  const { cfg, modulePath, path, uuid } = await loadModule(entryPoint);
2641
- const validFormat = await peprFormat(true);
2642
- if (!validFormat) {
2643
- console.log(
2644
- "\x1B[33m%s\x1B[0m",
2645
- "Formatting errors were found. The build will continue, but you may want to run `npx pepr format` to address any issues."
2646
- );
2647
- }
2648
- const npmRoot = (0, import_child_process2.execFileSync)("npm", ["root"]).toString().trim();
2679
+ await checkFormat();
2680
+ const npmRoot = (0, import_child_process3.execFileSync)("npm", ["root"]).toString().trim();
2649
2681
  const args = ["--project", `${modulePath}/tsconfig.json`, "--outdir", outputDir];
2650
- (0, import_child_process2.execFileSync)(`${npmRoot}/.bin/tsc`, args);
2682
+ (0, import_child_process3.execFileSync)(`${npmRoot}/.bin/tsc`, args);
2651
2683
  const ctxCfg = {
2652
2684
  bundle: true,
2653
2685
  entryPoints: [entryPoint],
@@ -2664,7 +2696,7 @@ async function buildModule(reloader, entryPoint = peprTS2, embed = true) {
2664
2696
  setup(build) {
2665
2697
  build.onEnd(async (r) => {
2666
2698
  if (r?.metafile) {
2667
- console.log(await (0, import_esbuild.analyzeMetafile)(r.metafile));
2699
+ console.log(await (0, import_esbuild2.analyzeMetafile)(r.metafile));
2668
2700
  }
2669
2701
  if (reloader) {
2670
2702
  await reloader(r);
@@ -2682,46 +2714,52 @@ async function buildModule(reloader, entryPoint = peprTS2, embed = true) {
2682
2714
  }
2683
2715
  if (!embed) {
2684
2716
  ctxCfg.minify = false;
2685
- ctxCfg.outfile = (0, import_path2.resolve)(outputDir, (0, import_path2.basename)(entryPoint, (0, import_path2.extname)(entryPoint))) + ".js";
2717
+ ctxCfg.outfile = (0, import_path3.resolve)(outputDir, (0, import_path3.basename)(entryPoint, (0, import_path3.extname)(entryPoint))) + ".js";
2686
2718
  ctxCfg.packages = "external";
2687
2719
  ctxCfg.treeShaking = false;
2688
2720
  }
2689
- const ctx = await (0, import_esbuild.context)(ctxCfg);
2690
- if (reloader) {
2691
- await ctx.watch();
2692
- } else {
2693
- await ctx.rebuild();
2694
- await ctx.dispose();
2695
- }
2721
+ const ctx = await watchForChanges(ctxCfg, reloader);
2696
2722
  return { ctx, path, cfg, uuid };
2697
2723
  } catch (e) {
2698
- console.error(`Error building module:`, e);
2699
- if (!e.stdout) process.exit(1);
2700
- const out = e.stdout.toString();
2701
- const err = e.stderr.toString();
2702
- console.log(out);
2703
- console.error(err);
2704
- if (out.includes("Types have separate declarations of a private property '_name'.")) {
2705
- const pgkErrMatch = /error TS2322: .*? 'import\("\/.*?\/node_modules\/(.*?)\/node_modules/g;
2706
- out.matchAll(pgkErrMatch);
2707
- const conflicts = [...out.matchAll(pgkErrMatch)];
2708
- if (conflicts.length < 1) {
2709
- console.info(
2710
- `
2724
+ handleModuleBuildError(e);
2725
+ }
2726
+ }
2727
+ function handleModuleBuildError(e) {
2728
+ console.error(`Error building module:`, e);
2729
+ if (!e.stdout) process.exit(1);
2730
+ const out = e.stdout.toString();
2731
+ const err = e.stderr.toString();
2732
+ console.log(out);
2733
+ console.error(err);
2734
+ if (out.includes("Types have separate declarations of a private property '_name'.")) {
2735
+ const pgkErrMatch = /error TS2322: .*? 'import\("\/.*?\/node_modules\/(.*?)\/node_modules/g;
2736
+ out.matchAll(pgkErrMatch);
2737
+ const conflicts = [...out.matchAll(pgkErrMatch)];
2738
+ if (conflicts.length < 1) {
2739
+ console.info(
2740
+ `
2711
2741
  One or more imported Pepr Capabilities seem to be using an incompatible version of Pepr.
2712
2742
  Try updating your Pepr Capabilities to their latest versions.`,
2713
- "Version Conflict"
2714
- );
2715
- }
2716
- conflicts.forEach((match) => {
2717
- console.info(
2718
- `
2743
+ "Version Conflict"
2744
+ );
2745
+ }
2746
+ conflicts.forEach((match) => {
2747
+ console.info(
2748
+ `
2719
2749
  Package '${match[1]}' seems to be incompatible with your current version of Pepr.
2720
2750
  Try updating to the latest version.`,
2721
- "Version Conflict"
2722
- );
2723
- });
2724
- }
2751
+ "Version Conflict"
2752
+ );
2753
+ });
2754
+ }
2755
+ }
2756
+ async function checkFormat() {
2757
+ const validFormat = await peprFormat(true);
2758
+ if (!validFormat) {
2759
+ console.log(
2760
+ "\x1B[33m%s\x1B[0m",
2761
+ "Formatting errors were found. The build will continue, but you may want to run `npx pepr format` to address any issues."
2762
+ );
2725
2763
  }
2726
2764
  }
2727
2765
 
@@ -2730,19 +2768,19 @@ var import_prompts = __toESM(require("prompts"));
2730
2768
 
2731
2769
  // src/lib/deploymentChecks.ts
2732
2770
  var import_kubernetes_fluent_client4 = require("kubernetes-fluent-client");
2733
- async function checkDeploymentStatus(namespace2) {
2734
- const deployments = await (0, import_kubernetes_fluent_client4.K8s)(import_kubernetes_fluent_client4.kind.Deployment).InNamespace(namespace2).Get();
2771
+ async function checkDeploymentStatus(namespace) {
2772
+ const deployments = await (0, import_kubernetes_fluent_client4.K8s)(import_kubernetes_fluent_client4.kind.Deployment).InNamespace(namespace).Get();
2735
2773
  let status = false;
2736
2774
  let readyCount = 0;
2737
- for (const deployment2 of deployments.items) {
2738
- const readyReplicas = deployment2.status?.readyReplicas ? deployment2.status?.readyReplicas : 0;
2739
- if (deployment2.status?.readyReplicas !== deployment2.spec?.replicas) {
2775
+ for (const deployment of deployments.items) {
2776
+ const readyReplicas = deployment.status?.readyReplicas ? deployment.status?.readyReplicas : 0;
2777
+ if (deployment.status?.readyReplicas !== deployment.spec?.replicas) {
2740
2778
  logger_default.info(
2741
- `Waiting for deployment ${deployment2.metadata?.name} rollout to finish: ${readyReplicas} of ${deployment2.spec?.replicas} replicas are available`
2779
+ `Waiting for deployment ${deployment.metadata?.name} rollout to finish: ${readyReplicas} of ${deployment.spec?.replicas} replicas are available`
2742
2780
  );
2743
2781
  } else {
2744
2782
  logger_default.info(
2745
- `Deployment ${deployment2.metadata?.name} rolled out: ${readyReplicas} of ${deployment2.spec?.replicas} replicas are available`
2783
+ `Deployment ${deployment.metadata?.name} rolled out: ${readyReplicas} of ${deployment.spec?.replicas} replicas are available`
2746
2784
  );
2747
2785
  readyCount++;
2748
2786
  }
@@ -2752,17 +2790,17 @@ async function checkDeploymentStatus(namespace2) {
2752
2790
  }
2753
2791
  return status;
2754
2792
  }
2755
- async function namespaceDeploymentsReady(namespace2 = "pepr-system") {
2756
- logger_default.info(`Checking ${namespace2} deployments status...`);
2793
+ async function namespaceDeploymentsReady(namespace = "pepr-system") {
2794
+ logger_default.info(`Checking ${namespace} deployments status...`);
2757
2795
  let ready = false;
2758
2796
  while (!ready) {
2759
- ready = await checkDeploymentStatus(namespace2);
2797
+ ready = await checkDeploymentStatus(namespace);
2760
2798
  if (ready) {
2761
2799
  return ready;
2762
2800
  }
2763
- await new Promise((resolve5) => setTimeout(resolve5, 1e3));
2801
+ await new Promise((resolve6) => setTimeout(resolve6, 1e3));
2764
2802
  }
2765
- logger_default.info(`All ${namespace2} deployments are ready`);
2803
+ logger_default.info(`All ${namespace} deployments are ready`);
2766
2804
  }
2767
2805
 
2768
2806
  // src/cli/deploy.ts
@@ -2831,8 +2869,8 @@ function deploy_default(program2) {
2831
2869
  }
2832
2870
 
2833
2871
  // src/cli/dev.ts
2834
- var import_child_process3 = require("child_process");
2835
- var import_fs9 = require("fs");
2872
+ var import_child_process4 = require("child_process");
2873
+ var import_fs10 = require("fs");
2836
2874
  var import_prompts2 = __toESM(require("prompts"));
2837
2875
  var import_kubernetes_fluent_client5 = require("kubernetes-fluent-client");
2838
2876
  function dev_default(program2) {
@@ -2856,8 +2894,8 @@ function dev_default(program2) {
2856
2894
  path,
2857
2895
  opts.host
2858
2896
  );
2859
- await import_fs9.promises.writeFile("insecure-tls.crt", webhook.tls.pem.crt);
2860
- await import_fs9.promises.writeFile("insecure-tls.key", webhook.tls.pem.key);
2897
+ await import_fs10.promises.writeFile("insecure-tls.crt", webhook.tls.pem.crt);
2898
+ await import_fs10.promises.writeFile("insecure-tls.key", webhook.tls.pem.key);
2861
2899
  try {
2862
2900
  let program3;
2863
2901
  const name2 = `pepr-${cfg.pepr.uuid}`;
@@ -2872,7 +2910,7 @@ function dev_default(program2) {
2872
2910
  console.error(`Error validating capability names:`, e);
2873
2911
  process.exit(1);
2874
2912
  }
2875
- program3 = (0, import_child_process3.fork)(path, {
2913
+ program3 = (0, import_child_process4.fork)(path, {
2876
2914
  env: {
2877
2915
  ...process.env,
2878
2916
  LOG_LEVEL: "debug",
@@ -2921,59 +2959,15 @@ var import_kubernetes_fluent_client6 = require("kubernetes-fluent-client");
2921
2959
  var import_stream = __toESM(require("stream"));
2922
2960
  function monitor_default(program2) {
2923
2961
  program2.command("monitor [module-uuid]").description("Monitor a Pepr Module").action(async (uuid) => {
2924
- let labels;
2925
- let errorMessage;
2926
- if (!uuid) {
2927
- labels = ["pepr.dev/controller", "admission"];
2928
- errorMessage = `No pods found with admission labels`;
2929
- } else {
2930
- labels = ["app", `pepr-${uuid}`];
2931
- errorMessage = `No pods found for module ${uuid}`;
2932
- }
2962
+ const { labels, errorMessage } = getLabelsAndErrorMessage(uuid);
2933
2963
  const pods = await (0, import_kubernetes_fluent_client6.K8s)(import_kubernetes_fluent_client6.kind.Pod).InNamespace("pepr-system").WithLabel(labels[0], labels[1]).Get();
2934
- const podNames = pods.items.flatMap((pod) => pod.metadata.name);
2964
+ const podNames = pods.items.flatMap((pod) => pod.metadata.name || "");
2935
2965
  if (podNames.length < 1) {
2936
2966
  console.error(errorMessage);
2937
2967
  process.exit(1);
2938
2968
  }
2939
- const kc = new import_client_node4.KubeConfig();
2940
- kc.loadFromDefault();
2941
- const log = new import_client_node4.Log(kc);
2942
- const logStream = new import_stream.default.PassThrough();
2943
- logStream.on("data", async (chunk) => {
2944
- const respMsg = `"msg":"Check response"`;
2945
- const lines = await chunk.toString().split("\n");
2946
- for (const line of lines) {
2947
- if (!line.includes(respMsg)) continue;
2948
- try {
2949
- const payload = JSON.parse(line.trim());
2950
- const isMutate = payload.res.patchType || payload.res.warnings;
2951
- const name2 = `${payload.namespace}${payload.name}`;
2952
- const uid = payload.res.uid;
2953
- if (isMutate) {
2954
- const plainPatch = payload.res?.patch !== void 0 && payload.res?.patch !== null ? atob(payload.res.patch) : "";
2955
- const patch = plainPatch !== "" && JSON.stringify(JSON.parse(plainPatch), null, 2);
2956
- const patchType = payload.res.patchType || payload.res.warnings || "";
2957
- const allowOrDeny = payload.res.allowed ? "\u{1F500}" : "\u{1F6AB}";
2958
- console.log(`
2959
- ${allowOrDeny} MUTATE ${name2} (${uid})`);
2960
- patchType.length > 0 && console.log(`
2961
- \x1B[1;34m${patch}\x1B[0m`);
2962
- } else {
2963
- const failures = Array.isArray(payload.res) ? payload.res : [payload.res];
2964
- const filteredFailures = failures.filter((r) => !r.allowed).map((r) => r.status.message);
2965
- console.log(
2966
- `
2967
- ${filteredFailures.length > 0 ? "\u274C" : "\u2705"} VALIDATE ${name2} (${uid})`
2968
- );
2969
- console.log(
2970
- filteredFailures.length > 0 ? `\x1B[1;31m${filteredFailures}\x1B[0m` : ""
2971
- );
2972
- }
2973
- } catch {
2974
- }
2975
- }
2976
- });
2969
+ const log = getK8sLogFromKubeConfig();
2970
+ const logStream = createLogStream();
2977
2971
  for (const podName of podNames) {
2978
2972
  await log.log("pepr-system", podName, "server", logStream, {
2979
2973
  follow: true,
@@ -2983,14 +2977,78 @@ ${filteredFailures.length > 0 ? "\u274C" : "\u2705"} VALIDATE ${name2} (${uid
2983
2977
  }
2984
2978
  });
2985
2979
  }
2980
+ function getLabelsAndErrorMessage(uuid) {
2981
+ let labels;
2982
+ let errorMessage;
2983
+ if (!uuid) {
2984
+ labels = ["pepr.dev/controller", "admission"];
2985
+ errorMessage = `No pods found with admission labels`;
2986
+ } else {
2987
+ labels = ["app", `pepr-${uuid}`];
2988
+ errorMessage = `No pods found for module ${uuid}`;
2989
+ }
2990
+ return { labels, errorMessage };
2991
+ }
2992
+ function getK8sLogFromKubeConfig() {
2993
+ const kc = new import_client_node4.KubeConfig();
2994
+ kc.loadFromDefault();
2995
+ return new import_client_node4.Log(kc);
2996
+ }
2997
+ function createLogStream() {
2998
+ const logStream = new import_stream.default.PassThrough();
2999
+ logStream.on("data", async (chunk) => {
3000
+ const lines = chunk.toString().split("\n");
3001
+ const respMsg = `"msg":"Check response"`;
3002
+ for (const line of lines) {
3003
+ if (!line.includes(respMsg)) continue;
3004
+ processLogLine(line);
3005
+ }
3006
+ });
3007
+ return logStream;
3008
+ }
3009
+ function processLogLine(line) {
3010
+ try {
3011
+ const payload = JSON.parse(line.trim());
3012
+ const isMutate = payload.res.patchType || payload.res.warnings;
3013
+ const name2 = `${payload.namespace}${payload.name}`;
3014
+ const uid = payload.res.uid;
3015
+ if (isMutate) {
3016
+ processMutateLog(payload, name2, uid);
3017
+ } else {
3018
+ processValidateLog(payload, name2, uid);
3019
+ }
3020
+ } catch {
3021
+ }
3022
+ }
3023
+ function processMutateLog(payload, name2, uid) {
3024
+ const plainPatch = payload.res.patch !== void 0 && payload.res.patch !== null ? atob(payload.res.patch) : "";
3025
+ const patch = plainPatch !== "" && JSON.stringify(JSON.parse(plainPatch), null, 2);
3026
+ const patchType = payload.res.patchType || payload.res.warnings || "";
3027
+ const allowOrDeny = payload.res.allowed ? "\u{1F500}" : "\u{1F6AB}";
3028
+ console.log(`
3029
+ ${allowOrDeny} MUTATE ${name2} (${uid})`);
3030
+ if (patchType.length > 0) {
3031
+ console.log(`
3032
+ \x1B[1;34m${patch}\x1B[0m`);
3033
+ }
3034
+ }
3035
+ function processValidateLog(payload, name2, uid) {
3036
+ const failures = Array.isArray(payload.res) ? payload.res : [payload.res];
3037
+ const filteredFailures = failures.filter((r) => !r.allowed).map((r) => r.status?.message || "");
3038
+ console.log(`
3039
+ ${filteredFailures.length > 0 ? "\u274C" : "\u2705"} VALIDATE ${name2} (${uid})`);
3040
+ if (filteredFailures.length > 0) {
3041
+ console.log(`\x1B[1;31m${filteredFailures}\x1B[0m`);
3042
+ }
3043
+ }
2986
3044
 
2987
3045
  // src/cli/init/index.ts
2988
- var import_child_process4 = require("child_process");
2989
- var import_path3 = require("path");
3046
+ var import_child_process5 = require("child_process");
3047
+ var import_path4 = require("path");
2990
3048
  var import_prompts4 = __toESM(require("prompts"));
2991
3049
 
2992
3050
  // src/cli/init/walkthrough.ts
2993
- var import_fs10 = require("fs");
3051
+ var import_fs11 = require("fs");
2994
3052
  var import_prompts3 = __toESM(require("prompts"));
2995
3053
 
2996
3054
  // src/lib/errors.ts
@@ -3018,7 +3076,7 @@ async function setName(name2) {
3018
3076
  validate: async (val) => {
3019
3077
  try {
3020
3078
  const name3 = sanitizeName(val);
3021
- await import_fs10.promises.access(name3, import_fs10.promises.constants.F_OK);
3079
+ await import_fs11.promises.access(name3, import_fs11.promises.constants.F_OK);
3022
3080
  return "A directory with this name already exists";
3023
3081
  } catch (e) {
3024
3082
  return val.length > 2 || "The name must be at least 3 characters long";
@@ -3132,19 +3190,19 @@ function init_default(program2) {
3132
3190
  console.log("Creating new Pepr module...");
3133
3191
  try {
3134
3192
  await createDir(dirName);
3135
- await createDir((0, import_path3.resolve)(dirName, ".vscode"));
3136
- await createDir((0, import_path3.resolve)(dirName, "capabilities"));
3137
- await write((0, import_path3.resolve)(dirName, gitignore.path), gitignore.data);
3138
- await write((0, import_path3.resolve)(dirName, eslint.path), eslint.data);
3139
- await write((0, import_path3.resolve)(dirName, prettier.path), prettier.data);
3140
- await write((0, import_path3.resolve)(dirName, packageJSON2.path), packageJSON2.data);
3141
- await write((0, import_path3.resolve)(dirName, readme.path), readme.data);
3142
- await write((0, import_path3.resolve)(dirName, tsConfig.path), tsConfig.data);
3143
- await write((0, import_path3.resolve)(dirName, peprTS3.path), peprTS3.data);
3144
- await write((0, import_path3.resolve)(dirName, ".vscode", snippet.path), snippet.data);
3145
- await write((0, import_path3.resolve)(dirName, ".vscode", codeSettings.path), codeSettings.data);
3146
- await write((0, import_path3.resolve)(dirName, "capabilities", samplesYaml.path), samplesYaml.data);
3147
- await write((0, import_path3.resolve)(dirName, "capabilities", helloPepr.path), helloPepr.data);
3193
+ await createDir((0, import_path4.resolve)(dirName, ".vscode"));
3194
+ await createDir((0, import_path4.resolve)(dirName, "capabilities"));
3195
+ await write((0, import_path4.resolve)(dirName, gitignore.path), gitignore.data);
3196
+ await write((0, import_path4.resolve)(dirName, eslint.path), eslint.data);
3197
+ await write((0, import_path4.resolve)(dirName, prettier.path), prettier.data);
3198
+ await write((0, import_path4.resolve)(dirName, packageJSON2.path), packageJSON2.data);
3199
+ await write((0, import_path4.resolve)(dirName, readme.path), readme.data);
3200
+ await write((0, import_path4.resolve)(dirName, tsConfig.path), tsConfig.data);
3201
+ await write((0, import_path4.resolve)(dirName, peprTS3.path), peprTS3.data);
3202
+ await write((0, import_path4.resolve)(dirName, ".vscode", snippet.path), snippet.data);
3203
+ await write((0, import_path4.resolve)(dirName, ".vscode", codeSettings.path), codeSettings.data);
3204
+ await write((0, import_path4.resolve)(dirName, "capabilities", samplesYaml.path), samplesYaml.data);
3205
+ await write((0, import_path4.resolve)(dirName, "capabilities", helloPepr.path), helloPepr.data);
3148
3206
  if (!opts.skipPostInit) {
3149
3207
  doPostInitActions(dirName);
3150
3208
  }
@@ -3161,14 +3219,14 @@ function init_default(program2) {
3161
3219
  }
3162
3220
  var doPostInitActions = (dirName) => {
3163
3221
  process.chdir(dirName);
3164
- (0, import_child_process4.execSync)("npm install", {
3222
+ (0, import_child_process5.execSync)("npm install", {
3165
3223
  stdio: "inherit"
3166
3224
  });
3167
- (0, import_child_process4.execSync)("git init --initial-branch=main", {
3225
+ (0, import_child_process5.execSync)("git init --initial-branch=main", {
3168
3226
  stdio: "inherit"
3169
3227
  });
3170
3228
  try {
3171
- (0, import_child_process4.execSync)("code .", {
3229
+ (0, import_child_process5.execSync)("code .", {
3172
3230
  stdio: "inherit"
3173
3231
  });
3174
3232
  } catch (e) {
@@ -3212,9 +3270,9 @@ var RootCmd = class extends import_commander2.Command {
3212
3270
  };
3213
3271
 
3214
3272
  // src/cli/update.ts
3215
- var import_child_process5 = require("child_process");
3216
- var import_fs11 = __toESM(require("fs"));
3217
- var import_path4 = require("path");
3273
+ var import_child_process6 = require("child_process");
3274
+ var import_fs12 = __toESM(require("fs"));
3275
+ var import_path5 = require("path");
3218
3276
  var import_prompts5 = __toESM(require("prompts"));
3219
3277
  function update_default(program2) {
3220
3278
  program2.command("update").description("Update this Pepr module. Not recommended for prod as it may change files.").option("--skip-template-update", "Skip updating the template files").action(async (opts) => {
@@ -3230,11 +3288,11 @@ function update_default(program2) {
3230
3288
  }
3231
3289
  console.log("Updating the Pepr module...");
3232
3290
  try {
3233
- (0, import_child_process5.execSync)("npm install pepr@latest", {
3291
+ (0, import_child_process6.execSync)("npm install pepr@latest", {
3234
3292
  stdio: "inherit"
3235
3293
  });
3236
3294
  if (!opts.skipTemplateUpdate) {
3237
- (0, import_child_process5.execSync)("npx pepr update-templates", {
3295
+ (0, import_child_process6.execSync)("npx pepr update-templates", {
3238
3296
  stdio: "inherit"
3239
3297
  });
3240
3298
  }
@@ -3248,17 +3306,17 @@ function update_default(program2) {
3248
3306
  console.log("Updating Pepr config and template tiles...");
3249
3307
  try {
3250
3308
  if (!opts.skipTemplateUpdate) {
3251
- await write((0, import_path4.resolve)(prettier.path), prettier.data);
3252
- await write((0, import_path4.resolve)(tsConfig.path), tsConfig.data);
3253
- await write((0, import_path4.resolve)(".vscode", snippet.path), snippet.data);
3254
- await write((0, import_path4.resolve)(".vscode", codeSettings.path), codeSettings.data);
3255
- const samplePath = (0, import_path4.resolve)("capabilities", samplesYaml.path);
3256
- if (import_fs11.default.existsSync(samplePath)) {
3257
- import_fs11.default.unlinkSync(samplePath);
3309
+ await write((0, import_path5.resolve)(prettier.path), prettier.data);
3310
+ await write((0, import_path5.resolve)(tsConfig.path), tsConfig.data);
3311
+ await write((0, import_path5.resolve)(".vscode", snippet.path), snippet.data);
3312
+ await write((0, import_path5.resolve)(".vscode", codeSettings.path), codeSettings.data);
3313
+ const samplePath = (0, import_path5.resolve)("capabilities", samplesYaml.path);
3314
+ if (import_fs12.default.existsSync(samplePath)) {
3315
+ import_fs12.default.unlinkSync(samplePath);
3258
3316
  await write(samplePath, samplesYaml.data);
3259
3317
  }
3260
- const tsPath = (0, import_path4.resolve)("capabilities", helloPepr.path);
3261
- if (import_fs11.default.existsSync(tsPath)) {
3318
+ const tsPath = (0, import_path5.resolve)("capabilities", helloPepr.path);
3319
+ if (import_fs12.default.existsSync(tsPath)) {
3262
3320
  await write(tsPath, helloPepr.data);
3263
3321
  }
3264
3322
  }
@@ -3270,7 +3328,7 @@ function update_default(program2) {
3270
3328
  }
3271
3329
 
3272
3330
  // src/cli/kfc.ts
3273
- var import_child_process6 = require("child_process");
3331
+ var import_child_process7 = require("child_process");
3274
3332
  var import_prompts6 = __toESM(require("prompts"));
3275
3333
  function kfc_default(program2) {
3276
3334
  program2.command("kfc [args...]").description("Execute Kubernetes Fluent Client commands").action(async (args) => {
@@ -3287,7 +3345,7 @@ function kfc_default(program2) {
3287
3345
  args.push("--help");
3288
3346
  }
3289
3347
  const argsString = args.join(" ");
3290
- (0, import_child_process6.execSync)(`kubernetes-fluent-client ${argsString}`, {
3348
+ (0, import_child_process7.execSync)(`kubernetes-fluent-client ${argsString}`, {
3291
3349
  stdio: "inherit"
3292
3350
  });
3293
3351
  } catch (e) {