pepr 0.28.4 → 0.28.6

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/SECURITY.md ADDED
@@ -0,0 +1,18 @@
1
+ # Security Policy
2
+
3
+ ## Reporting a Vulnerability
4
+
5
+ If you discover a security vulnerability in Pepr, please report it to us by sending an email to [pepr@defenseunicorns.com](mailto:pepr@defenseunicorns.com?subject=Vulnerability) or directly through the [GitHub UI](https://github.com/defenseunicorns/pepr/security/advisories/new).
6
+
7
+ Please include the following details in your report:
8
+
9
+ - A clear description of the vulnerability
10
+ - Steps to reproduce the vulnerability
11
+ - Any additional information that may be helpful in understanding and fixing the issue
12
+
13
+ We appreciate your help in making Pepr more secure and will acknowledge your contribution in the remediation PR.
14
+
15
+
16
+ ## Contact
17
+
18
+ If you have any questions or concerns regarding the security of Pepr, please contact us at pepr@defenseunicorns.com.
package/dist/cli.js CHANGED
@@ -276,9 +276,9 @@ function watcherService(name2) {
276
276
  var import_zlib = require("zlib");
277
277
 
278
278
  // src/lib/helpers.ts
279
- var import_kubernetes_fluent_client = require("kubernetes-fluent-client");
280
279
  var import_fs2 = require("fs");
281
- var createRBACMap = (capabilities) => {
280
+ var import_kubernetes_fluent_client = require("kubernetes-fluent-client");
281
+ function createRBACMap(capabilities) {
282
282
  return capabilities.reduce((acc, capability) => {
283
283
  capability.bindings.forEach((binding) => {
284
284
  const key = `${binding.kind.group}/${binding.kind.version}/${binding.kind.kind}`;
@@ -299,7 +299,7 @@ var createRBACMap = (capabilities) => {
299
299
  });
300
300
  return acc;
301
301
  }, {});
302
- };
302
+ }
303
303
  async function createDirectoryIfNotExists(path) {
304
304
  try {
305
305
  await import_fs2.promises.access(path);
@@ -754,7 +754,7 @@ function genEnv(config, watchMode = false) {
754
754
  const def = {
755
755
  PEPR_WATCH_MODE: watchMode ? "true" : "false",
756
756
  PEPR_PRETTY_LOG: "false",
757
- LOG_LEVEL: config.logLevel || "debug"
757
+ LOG_LEVEL: config.logLevel || "info"
758
758
  };
759
759
  const cfg = config.env || {};
760
760
  const env = Object.entries({ ...def, ...cfg }).map(([name2, value]) => ({ name: name2, value }));
@@ -1134,7 +1134,7 @@ async function overridesFile({ hash, name: name2, image, config, apiToken }, pat
1134
1134
  env: [
1135
1135
  { name: "PEPR_WATCH_MODE", value: "false" },
1136
1136
  { name: "PEPR_PRETTY_LOG", value: "false" },
1137
- { name: "LOG_LEVEL", value: "debug" }
1137
+ { name: "LOG_LEVEL", value: "info" }
1138
1138
  ],
1139
1139
  image,
1140
1140
  annotations: {
@@ -1179,7 +1179,7 @@ async function overridesFile({ hash, name: name2, image, config, apiToken }, pat
1179
1179
  env: [
1180
1180
  { name: "PEPR_WATCH_MODE", value: "true" },
1181
1181
  { name: "PEPR_PRETTY_LOG", value: "false" },
1182
- { name: "LOG_LEVEL", value: "debug" }
1182
+ { name: "LOG_LEVEL", value: "info" }
1183
1183
  ],
1184
1184
  image,
1185
1185
  annotations: {
@@ -1815,7 +1815,7 @@ var gitIgnore = "# Ignore node_modules and Pepr build artifacts\nnode_modules\nd
1815
1815
  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';
1816
1816
  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';
1817
1817
  var helloPeprTS = 'import {\n Capability,\n K8s,\n Log,\n PeprMutateRequest,\n RegisterKind,\n a,\n fetch,\n fetchStatus,\n kind,\n} from "pepr";\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://api.chucknorris.io/jokes/random?category=dev");\n * const joke = await fetch("https://api.chucknorris.io/jokes/random?category=dev") as TheChuckNorrisJoke;\n * ```\n *\n * Alternatively, you can drop the type completely:\n *\n * ```ts\n * fetch("https://api.chucknorris.io/jokes/random?category=dev")\n * ```\n */\ninterface TheChuckNorrisJoke {\n icon_url: string;\n id: string;\n url: string;\n value: string;\n}\n\nWhen(a.ConfigMap)\n .IsCreated()\n .WithLabel("chuck-norris")\n .Mutate(async change => {\n // Try/catch is not needed as a response object will always be returned\n const response = await fetch<TheChuckNorrisJoke>(\n "https://api.chucknorris.io/jokes/random?category=dev",\n );\n\n // Instead, check the `response.ok` field\n if (response.ok) {\n // Add the Chuck Norris joke to the configmap\n change.Raw.data["chuck-says"] = response.data.value;\n return;\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';
1818
- 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" }, version: "0.28.4", main: "dist/lib.js", types: "dist/lib.d.ts", scripts: { "gen-data-json": "node hack/build-template-data.js", prebuild: "rm -fr dist/* && npm run gen-data-json", build: "tsc && node build.mjs", test: "npm run test:unit && npm run test:journey", "test:unit": "npm run gen-data-json && jest src --coverage --detectOpenHandles --coverageDirectory=./coverage", "test:journey": "npm run test:journey:k3d && npm run test:journey: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 test:journey: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:build": "npm run build && npm pack", "test:journey:image": "docker buildx build --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" }, dependencies: { "@types/ramda": "0.29.11", express: "4.18.3", "fast-json-patch": "3.1.1", "kubernetes-fluent-client": "2.2.3", pino: "8.19.0", "pino-pretty": "10.3.1", "prom-client": "15.1.0", ramda: "0.29.1" }, devDependencies: { "@commitlint/cli": "19.2.0", "@commitlint/config-conventional": "19.1.0", "@jest/globals": "29.7.0", "@types/eslint": "8.56.5", "@types/express": "4.17.21", "@types/node": "18.x.x", "@types/node-forge": "1.3.11", "@types/prompts": "2.4.9", "@types/uuid": "9.0.8", jest: "29.7.0", nock: "13.5.4", "ts-jest": "29.1.2" }, peerDependencies: { "@typescript-eslint/eslint-plugin": "6.15.0", "@typescript-eslint/parser": "6.15.0", commander: "11.1.0", esbuild: "0.19.10", eslint: "8.56.0", "node-forge": "1.3.1", prettier: "3.1.1", prompts: "2.4.2", typescript: "5.3.3", uuid: "9.0.1" } };
1818
+ 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" }, version: "0.28.6", main: "dist/lib.js", types: "dist/lib.d.ts", scripts: { "gen-data-json": "node hack/build-template-data.js", prebuild: "rm -fr dist/* && npm run gen-data-json", build: "tsc && node build.mjs", test: "npm run test:unit && npm run test:journey", "test:unit": "npm run gen-data-json && jest src --coverage --detectOpenHandles --coverageDirectory=./coverage", "test:journey": "npm run test:journey:k3d && npm run test:journey: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 test:journey: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:build": "npm run build && npm pack", "test:journey:image": "docker buildx build --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" }, dependencies: { "@types/ramda": "0.29.11", express: "4.19.1", "fast-json-patch": "3.1.1", "kubernetes-fluent-client": "2.3.0", pino: "8.19.0", "pino-pretty": "11.0.0", "prom-client": "15.1.0", ramda: "0.29.1" }, devDependencies: { "@commitlint/cli": "19.2.1", "@commitlint/config-conventional": "19.1.0", "@jest/globals": "29.7.0", "@types/eslint": "8.56.6", "@types/express": "4.17.21", "@types/node": "18.x.x", "@types/node-forge": "1.3.11", "@types/prompts": "2.4.9", "@types/uuid": "9.0.8", jest: "29.7.0", nock: "13.5.4", "ts-jest": "29.1.2" }, peerDependencies: { "@typescript-eslint/eslint-plugin": "6.15.0", "@typescript-eslint/parser": "6.15.0", commander: "11.1.0", esbuild: "0.19.10", eslint: "8.56.0", "node-forge": "1.3.1", prettier: "3.1.1", prompts: "2.4.2", typescript: "5.3.3", uuid: "9.0.1" } };
1819
1819
 
1820
1820
  // src/templates/pepr.code-snippets.json
1821
1821
  var pepr_code_snippets_default = {
@@ -2629,7 +2629,7 @@ var import_fs11 = __toESM(require("fs"));
2629
2629
  var import_path4 = require("path");
2630
2630
  var import_prompts5 = __toESM(require("prompts"));
2631
2631
  function update_default(program2) {
2632
- program2.command("update").description("Update this Pepr module").option("--skip-template-update", "Skip updating the template files").action(async (opts) => {
2632
+ 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) => {
2633
2633
  if (!opts.skipTemplateUpdate) {
2634
2634
  const { confirm: confirm2 } = await (0, import_prompts5.default)({
2635
2635
  type: "confirm",
@@ -49,7 +49,7 @@ if (process.env.LOG_LEVEL) {
49
49
  var logger_default = Log;
50
50
 
51
51
  // src/templates/data.json
52
- 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" }, version: "0.28.4", main: "dist/lib.js", types: "dist/lib.d.ts", scripts: { "gen-data-json": "node hack/build-template-data.js", prebuild: "rm -fr dist/* && npm run gen-data-json", build: "tsc && node build.mjs", test: "npm run test:unit && npm run test:journey", "test:unit": "npm run gen-data-json && jest src --coverage --detectOpenHandles --coverageDirectory=./coverage", "test:journey": "npm run test:journey:k3d && npm run test:journey: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 test:journey: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:build": "npm run build && npm pack", "test:journey:image": "docker buildx build --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" }, dependencies: { "@types/ramda": "0.29.11", express: "4.18.3", "fast-json-patch": "3.1.1", "kubernetes-fluent-client": "2.2.3", pino: "8.19.0", "pino-pretty": "10.3.1", "prom-client": "15.1.0", ramda: "0.29.1" }, devDependencies: { "@commitlint/cli": "19.2.0", "@commitlint/config-conventional": "19.1.0", "@jest/globals": "29.7.0", "@types/eslint": "8.56.5", "@types/express": "4.17.21", "@types/node": "18.x.x", "@types/node-forge": "1.3.11", "@types/prompts": "2.4.9", "@types/uuid": "9.0.8", jest: "29.7.0", nock: "13.5.4", "ts-jest": "29.1.2" }, peerDependencies: { "@typescript-eslint/eslint-plugin": "6.15.0", "@typescript-eslint/parser": "6.15.0", commander: "11.1.0", esbuild: "0.19.10", eslint: "8.56.0", "node-forge": "1.3.1", prettier: "3.1.1", prompts: "2.4.2", typescript: "5.3.3", uuid: "9.0.1" } };
52
+ 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" }, version: "0.28.6", main: "dist/lib.js", types: "dist/lib.d.ts", scripts: { "gen-data-json": "node hack/build-template-data.js", prebuild: "rm -fr dist/* && npm run gen-data-json", build: "tsc && node build.mjs", test: "npm run test:unit && npm run test:journey", "test:unit": "npm run gen-data-json && jest src --coverage --detectOpenHandles --coverageDirectory=./coverage", "test:journey": "npm run test:journey:k3d && npm run test:journey: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 test:journey: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:build": "npm run build && npm pack", "test:journey:image": "docker buildx build --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" }, dependencies: { "@types/ramda": "0.29.11", express: "4.19.1", "fast-json-patch": "3.1.1", "kubernetes-fluent-client": "2.3.0", pino: "8.19.0", "pino-pretty": "11.0.0", "prom-client": "15.1.0", ramda: "0.29.1" }, devDependencies: { "@commitlint/cli": "19.2.1", "@commitlint/config-conventional": "19.1.0", "@jest/globals": "29.7.0", "@types/eslint": "8.56.6", "@types/express": "4.17.21", "@types/node": "18.x.x", "@types/node-forge": "1.3.11", "@types/prompts": "2.4.9", "@types/uuid": "9.0.8", jest: "29.7.0", nock: "13.5.4", "ts-jest": "29.1.2" }, peerDependencies: { "@typescript-eslint/eslint-plugin": "6.15.0", "@typescript-eslint/parser": "6.15.0", commander: "11.1.0", esbuild: "0.19.10", eslint: "8.56.0", "node-forge": "1.3.1", prettier: "3.1.1", prompts: "2.4.2", typescript: "5.3.3", uuid: "9.0.1" } };
53
53
 
54
54
  // src/lib/k8s.ts
55
55
  var import_kubernetes_fluent_client = require("kubernetes-fluent-client");
@@ -1,6 +1,5 @@
1
1
  import { KubernetesObject } from "kubernetes-fluent-client";
2
- import { CapabilityExport } from "./types";
3
- import { Binding } from "./types";
2
+ import { Binding, CapabilityExport } from "./types";
4
3
  type RBACMap = {
5
4
  [key: string]: {
6
5
  verbs: string[];
@@ -11,9 +10,9 @@ export declare function checkOverlap(bindingFilters: Record<string, string>, obj
11
10
  /**
12
11
  * Decide to run callback after the event comes back from API Server
13
12
  **/
14
- export declare const filterMatcher: (binding: Partial<Binding>, obj: Partial<KubernetesObject>, capabilityNamespaces: string[]) => string;
15
- export declare const addVerbIfNotExists: (verbs: string[], verb: string) => void;
16
- export declare const createRBACMap: (capabilities: CapabilityExport[]) => RBACMap;
13
+ export declare function filterNoMatchReason(binding: Partial<Binding>, obj: Partial<KubernetesObject>, capabilityNamespaces: string[]): string;
14
+ export declare function addVerbIfNotExists(verbs: string[], verb: string): void;
15
+ export declare function createRBACMap(capabilities: CapabilityExport[]): RBACMap;
17
16
  export declare function createDirectoryIfNotExists(path: string): Promise<void>;
18
17
  export declare function hasEveryOverlap<T>(array1: T[], array2: T[]): boolean;
19
18
  export declare function hasAnyOverlap<T>(array1: T[], array2: T[]): boolean;
@@ -1 +1 @@
1
- {"version":3,"file":"helpers.d.ts","sourceRoot":"","sources":["../../src/lib/helpers.ts"],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AM,UAK1E"}
@@ -1,11 +1,12 @@
1
1
  import { KubernetesObject } from "@kubernetes/client-node";
2
+ import { WatchPhase } from "kubernetes-fluent-client/dist/fluent/types";
2
3
  /**
3
4
  * Queue is a FIFO queue for reconciling
4
5
  */
5
6
  export declare class Queue<K extends KubernetesObject> {
6
7
  #private;
7
8
  constructor();
8
- setReconcile(reconcile: (...args: unknown[]) => Promise<void>): void;
9
+ setReconcile(reconcile: (obj: KubernetesObject, type: WatchPhase) => Promise<void>): void;
9
10
  /**
10
11
  * Enqueue adds an item to the queue and returns a promise that resolves when the item is
11
12
  * reconciled.
@@ -13,6 +14,6 @@ export declare class Queue<K extends KubernetesObject> {
13
14
  * @param item The object to reconcile
14
15
  * @returns A promise that resolves when the object is reconciled
15
16
  */
16
- enqueue(item: K): Promise<void>;
17
+ enqueue(item: K, type: WatchPhase): Promise<void>;
17
18
  }
18
19
  //# sourceMappingURL=queue.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"queue.d.ts","sourceRoot":"","sources":["../../src/lib/queue.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,gBAAgB,EAAE,MAAM,yBAAyB,CAAC;AAS3D;;GAEG;AACH,qBAAa,KAAK,CAAC,CAAC,SAAS,gBAAgB;;;IAS3C,YAAY,CAAC,SAAS,EAAE,CAAC,GAAG,IAAI,EAAE,OAAO,EAAE,KAAK,OAAO,CAAC,IAAI,CAAC;IAG7D;;;;;;OAMG;IACH,OAAO,CAAC,IAAI,EAAE,CAAC;CA2ChB"}
1
+ {"version":3,"file":"queue.d.ts","sourceRoot":"","sources":["../../src/lib/queue.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,gBAAgB,EAAE,MAAM,yBAAyB,CAAC;AAC3D,OAAO,EAAE,UAAU,EAAE,MAAM,4CAA4C,CAAC;AAUxE;;GAEG;AACH,qBAAa,KAAK,CAAC,CAAC,SAAS,gBAAgB;;;IAS3C,YAAY,CAAC,SAAS,EAAE,CAAC,GAAG,EAAE,gBAAgB,EAAE,IAAI,EAAE,UAAU,KAAK,OAAO,CAAC,IAAI,CAAC;IAIlF;;;;;;OAMG;IACH,OAAO,CAAC,IAAI,EAAE,CAAC,EAAE,IAAI,EAAE,UAAU;CAoDlC"}
@@ -1,3 +1,8 @@
1
1
  import { Capability } from "./capability";
2
+ /**
3
+ * Entrypoint for setting up watches for all capabilities
4
+ *
5
+ * @param capabilities The capabilities to load watches for
6
+ */
2
7
  export declare function setupWatch(capabilities: Capability[]): void;
3
8
  //# sourceMappingURL=watch-processor.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"watch-processor.d.ts","sourceRoot":"","sources":["../../src/lib/watch-processor.ts"],"names":[],"mappings":"AAOA,OAAO,EAAE,UAAU,EAAE,MAAM,cAAc,CAAC;AAS1C,wBAAgB,UAAU,CAAC,YAAY,EAAE,UAAU,EAAE,QAMpD"}
1
+ {"version":3,"file":"watch-processor.d.ts","sourceRoot":"","sources":["../../src/lib/watch-processor.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,UAAU,EAAE,MAAM,cAAc,CAAC;AAqB1C;;;;GAIG;AACH,wBAAgB,UAAU,CAAC,YAAY,EAAE,UAAU,EAAE,QAMpD"}
package/dist/lib.js CHANGED
@@ -647,9 +647,9 @@ var PeprControllerStore = class {
647
647
  }
648
648
  } else {
649
649
  for (const { name: name2, registerStore } of capabilities) {
650
- const { store: store2 } = registerStore();
651
- store2.registerSender(this.#send(name2));
652
- this.#stores[name2] = store2;
650
+ const { store } = registerStore();
651
+ store.registerSender(this.#send(name2));
652
+ this.#stores[name2] = store;
653
653
  }
654
654
  }
655
655
  setTimeout(
@@ -661,10 +661,10 @@ var PeprControllerStore = class {
661
661
  const watcher = (0, import_kubernetes_fluent_client2.K8s)(PeprStore, { name: this.#name, namespace }).Watch(this.#receive);
662
662
  watcher.start().catch((e) => logger_default.error(e, "Error starting Pepr store watch"));
663
663
  };
664
- #receive = (store2) => {
665
- logger_default.debug(store2, "Pepr Store update");
664
+ #receive = (store) => {
665
+ logger_default.debug(store, "Pepr Store update");
666
666
  const debounced = () => {
667
- const data = store2.data || {};
667
+ const data = store.data || {};
668
668
  for (const name of Object.keys(this.#stores)) {
669
669
  const offset = `${name}-`.length;
670
670
  const filtered = {};
@@ -904,7 +904,7 @@ var Controller = class _Controller {
904
904
  const responseList = Array.isArray(response) ? response : [response];
905
905
  responseList.map((res2) => {
906
906
  this.#afterHook && this.#afterHook(res2);
907
- logger_default.debug({ ...reqMetadata, res: res2 }, "Check response");
907
+ logger_default.info({ ...reqMetadata, res: res2 }, "Check response");
908
908
  });
909
909
  let kubeAdmissionResponse;
910
910
  if (admissionKind === "Mutate") {
@@ -981,61 +981,9 @@ var Controller = class _Controller {
981
981
  };
982
982
 
983
983
  // src/lib/watch-processor.ts
984
- var import_crypto = require("crypto");
985
984
  var import_kubernetes_fluent_client4 = require("kubernetes-fluent-client");
986
985
  var import_types2 = require("kubernetes-fluent-client/dist/fluent/types");
987
986
 
988
- // src/lib/queue.ts
989
- var Queue = class {
990
- #queue = [];
991
- #pendingPromise = false;
992
- #reconcile;
993
- constructor() {
994
- this.#reconcile = async () => await new Promise((resolve) => resolve());
995
- }
996
- setReconcile(reconcile) {
997
- this.#reconcile = reconcile;
998
- }
999
- /**
1000
- * Enqueue adds an item to the queue and returns a promise that resolves when the item is
1001
- * reconciled.
1002
- *
1003
- * @param item The object to reconcile
1004
- * @returns A promise that resolves when the object is reconciled
1005
- */
1006
- enqueue(item) {
1007
- logger_default.debug(`Enqueueing ${item.metadata.namespace}/${item.metadata.name}`);
1008
- return new Promise((resolve, reject) => {
1009
- this.#queue.push({ item, resolve, reject });
1010
- return this.#dequeue();
1011
- });
1012
- }
1013
- /**
1014
- * Dequeue reconciles the next item in the queue
1015
- *
1016
- * @returns A promise that resolves when the webapp is reconciled
1017
- */
1018
- async #dequeue() {
1019
- if (this.#pendingPromise)
1020
- return false;
1021
- const element = this.#queue.shift();
1022
- if (!element)
1023
- return false;
1024
- try {
1025
- this.#pendingPromise = true;
1026
- if (this.#reconcile) {
1027
- await this.#reconcile(element.item);
1028
- }
1029
- element.resolve();
1030
- } catch (e) {
1031
- element.reject(e);
1032
- } finally {
1033
- this.#pendingPromise = false;
1034
- await this.#dequeue();
1035
- }
1036
- }
1037
- };
1038
-
1039
987
  // src/lib/helpers.ts
1040
988
  var import_kubernetes_fluent_client3 = require("kubernetes-fluent-client");
1041
989
  function checkOverlap(bindingFilters, objectFilters) {
@@ -1056,7 +1004,7 @@ function checkOverlap(bindingFilters, objectFilters) {
1056
1004
  }
1057
1005
  return matchCount === Object.keys(bindingFilters).length;
1058
1006
  }
1059
- var filterMatcher = (binding, obj, capabilityNamespaces) => {
1007
+ function filterNoMatchReason(binding, obj, capabilityNamespaces) {
1060
1008
  if (binding.kind && binding.kind.kind === "Namespace" && binding.filters && binding.filters.namespaces.length !== 0) {
1061
1009
  return `Ignoring Watch Callback: Cannot use a namespace filter in a namespace object.`;
1062
1010
  }
@@ -1088,76 +1036,114 @@ var filterMatcher = (binding, obj, capabilityNamespaces) => {
1088
1036
  )}, Object namespace: ${obj.metadata.namespace}.`;
1089
1037
  }
1090
1038
  return "";
1039
+ }
1040
+
1041
+ // src/lib/queue.ts
1042
+ var Queue = class {
1043
+ #queue = [];
1044
+ #pendingPromise = false;
1045
+ #reconcile;
1046
+ constructor() {
1047
+ this.#reconcile = async () => await new Promise((resolve) => resolve());
1048
+ }
1049
+ setReconcile(reconcile) {
1050
+ this.#reconcile = reconcile;
1051
+ }
1052
+ /**
1053
+ * Enqueue adds an item to the queue and returns a promise that resolves when the item is
1054
+ * reconciled.
1055
+ *
1056
+ * @param item The object to reconcile
1057
+ * @returns A promise that resolves when the object is reconciled
1058
+ */
1059
+ enqueue(item, type) {
1060
+ logger_default.debug(`Enqueueing ${item.metadata.namespace}/${item.metadata.name}`);
1061
+ return new Promise((resolve, reject) => {
1062
+ this.#queue.push({ item, type, resolve, reject });
1063
+ return this.#dequeue();
1064
+ });
1065
+ }
1066
+ /**
1067
+ * Dequeue reconciles the next item in the queue
1068
+ *
1069
+ * @returns A promise that resolves when the webapp is reconciled
1070
+ */
1071
+ async #dequeue() {
1072
+ if (this.#pendingPromise) {
1073
+ logger_default.debug("Pending promise, not dequeuing");
1074
+ return false;
1075
+ }
1076
+ const element = this.#queue.shift();
1077
+ if (!element) {
1078
+ logger_default.debug("No element, not dequeuing");
1079
+ return false;
1080
+ }
1081
+ try {
1082
+ this.#pendingPromise = true;
1083
+ if (this.#reconcile) {
1084
+ logger_default.debug(`Reconciling ${element.item.metadata.name}`);
1085
+ await this.#reconcile(element.item, element.type);
1086
+ }
1087
+ element.resolve();
1088
+ } catch (e) {
1089
+ logger_default.debug(`Error reconciling ${element.item.metadata.name}`, { error: e });
1090
+ element.reject(e);
1091
+ } finally {
1092
+ logger_default.debug("Resetting pending promise and dequeuing");
1093
+ this.#pendingPromise = false;
1094
+ await this.#dequeue();
1095
+ }
1096
+ }
1091
1097
  };
1092
1098
 
1093
1099
  // src/lib/watch-processor.ts
1094
- var store = {};
1100
+ var watchCfg = {
1101
+ retryMax: 5,
1102
+ retryDelaySec: 5
1103
+ };
1104
+ var eventToPhaseMap = {
1105
+ ["CREATE" /* Create */]: [import_types2.WatchPhase.Added],
1106
+ ["UPDATE" /* Update */]: [import_types2.WatchPhase.Modified],
1107
+ ["CREATEORUPDATE" /* CreateOrUpdate */]: [import_types2.WatchPhase.Added, import_types2.WatchPhase.Modified],
1108
+ ["DELETE" /* Delete */]: [import_types2.WatchPhase.Deleted],
1109
+ ["*" /* Any */]: [import_types2.WatchPhase.Added, import_types2.WatchPhase.Modified, import_types2.WatchPhase.Deleted]
1110
+ };
1095
1111
  function setupWatch(capabilities) {
1096
1112
  capabilities.map(
1097
1113
  (capability) => capability.bindings.filter((binding) => binding.isWatch).forEach((bindingElement) => runBinding(bindingElement, capability.namespaces))
1098
1114
  );
1099
1115
  }
1100
1116
  async function runBinding(binding, capabilityNamespaces) {
1101
- const eventToPhaseMap = {
1102
- ["CREATE" /* Create */]: [import_types2.WatchPhase.Added],
1103
- ["UPDATE" /* Update */]: [import_types2.WatchPhase.Modified],
1104
- ["CREATEORUPDATE" /* CreateOrUpdate */]: [import_types2.WatchPhase.Added, import_types2.WatchPhase.Modified],
1105
- ["DELETE" /* Delete */]: [import_types2.WatchPhase.Deleted],
1106
- ["*" /* Any */]: [import_types2.WatchPhase.Added, import_types2.WatchPhase.Modified, import_types2.WatchPhase.Deleted]
1107
- };
1108
1117
  const phaseMatch = eventToPhaseMap[binding.event] || eventToPhaseMap["*" /* Any */];
1109
- const watchCfg = {
1110
- retryMax: 5,
1111
- retryDelaySec: 5
1112
- };
1113
- let watcher;
1114
- if (binding.isQueue) {
1115
- const queue = new Queue();
1116
- watcher = (0, import_kubernetes_fluent_client4.K8s)(binding.model, binding.filters).Watch(async (obj, type) => {
1117
- logger_default.debug(obj, `Watch event ${type} received`);
1118
- if (phaseMatch.includes(type)) {
1119
- try {
1120
- const filterMatch = filterMatcher(binding, obj, capabilityNamespaces);
1121
- if (filterMatch === "") {
1122
- queue.setReconcile(async () => await binding.watchCallback?.(obj, type));
1123
- await queue.enqueue(obj);
1124
- } else {
1125
- logger_default.debug(filterMatch);
1126
- }
1127
- } catch (e) {
1128
- logger_default.error(e, "Error executing watch callback");
1129
- }
1130
- }
1131
- }, watchCfg);
1132
- } else {
1133
- watcher = (0, import_kubernetes_fluent_client4.K8s)(binding.model, binding.filters).Watch(async (obj, type) => {
1134
- logger_default.debug(obj, `Watch event ${type} received`);
1135
- if (phaseMatch.includes(type)) {
1136
- try {
1137
- const filterMatch = filterMatcher(binding, obj, capabilityNamespaces);
1138
- if (filterMatch === "") {
1139
- await binding.watchCallback?.(obj, type);
1140
- } else {
1141
- logger_default.debug(filterMatch);
1142
- }
1143
- } catch (e) {
1144
- logger_default.error(e, "Error executing watch callback");
1118
+ const watchCallback = async (obj, type) => {
1119
+ if (phaseMatch.includes(type)) {
1120
+ try {
1121
+ const filterMatch = filterNoMatchReason(binding, obj, capabilityNamespaces);
1122
+ if (filterMatch === "") {
1123
+ await binding.watchCallback?.(obj, type);
1124
+ } else {
1125
+ logger_default.debug(filterMatch);
1145
1126
  }
1127
+ } catch (e) {
1128
+ logger_default.error(e, "Error executing watch callback");
1146
1129
  }
1147
- }, watchCfg);
1148
- }
1149
- const cacheSuffix = (0, import_crypto.createHash)("sha224").update(binding.watchCallback.toString()).digest("hex").substring(0, 5);
1150
- const cacheID = [watcher.getCacheID(), cacheSuffix].join("-");
1130
+ }
1131
+ };
1132
+ const queue = new Queue();
1133
+ queue.setReconcile(watchCallback);
1134
+ const watcher = (0, import_kubernetes_fluent_client4.K8s)(binding.model, binding.filters).Watch(async (obj, type) => {
1135
+ logger_default.debug(obj, `Watch event ${type} received`);
1136
+ if (binding.isQueue) {
1137
+ await queue.enqueue(obj, type);
1138
+ } else {
1139
+ await watchCallback(obj, type);
1140
+ }
1141
+ }, watchCfg);
1151
1142
  watcher.events.on(import_kubernetes_fluent_client4.WatchEvent.GIVE_UP, (err) => {
1152
1143
  logger_default.error(err, "Watch failed after 5 attempts, giving up");
1153
1144
  process.exit(1);
1154
1145
  });
1155
1146
  try {
1156
- const resourceVersion = store[cacheID];
1157
- if (resourceVersion) {
1158
- logger_default.debug(`Starting watch ${binding.model.name} from version ${resourceVersion}`);
1159
- watcher.resourceVersion = resourceVersion;
1160
- }
1161
1147
  await watcher.start();
1162
1148
  } catch (err) {
1163
1149
  logger_default.error(err, "Error starting watch");
@@ -1355,8 +1341,8 @@ var OnSchedule = class {
1355
1341
  this.startTime = schedule?.startTime;
1356
1342
  this.completions = schedule?.completions;
1357
1343
  }
1358
- setStore(store2) {
1359
- this.store = store2;
1344
+ setStore(store) {
1345
+ this.store = store;
1360
1346
  this.startInterval();
1361
1347
  }
1362
1348
  startInterval() {