pepr 0.1.44 → 0.1.45

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -2,7 +2,7 @@ import k8s from "@kubernetes/client-node";
2
2
  import utils from "ramda";
3
3
  import { Capability } from "./src/lib/capability";
4
4
  import { fetch, fetchRaw } from "./src/lib/fetch";
5
- import { a } from "./src/lib/k8s";
5
+ import { RegisterKind, a } from "./src/lib/k8s";
6
6
  import Log from "./src/lib/logger";
7
7
  import { PeprModule } from "./src/lib/module";
8
8
  import { PeprRequest } from "./src/lib/request";
@@ -10,4 +10,4 @@ import type * as KubernetesClientNode from "@kubernetes/client-node";
10
10
  import type * as RamdaUtils from "ramda";
11
11
  export { a,
12
12
  /** PeprModule is used to setup a complete Pepr Module: `new PeprModule(cfg, {...capabilities})` */
13
- PeprModule, PeprRequest, Capability, Log, utils, fetch, fetchRaw, k8s, RamdaUtils, KubernetesClientNode, };
13
+ PeprModule, PeprRequest, RegisterKind, Capability, Log, utils, fetch, fetchRaw, k8s, RamdaUtils, KubernetesClientNode, };
package/dist/index.js CHANGED
@@ -3,7 +3,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
3
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.k8s = exports.fetchRaw = exports.fetch = exports.utils = exports.Log = exports.Capability = exports.PeprRequest = exports.PeprModule = exports.a = void 0;
6
+ exports.k8s = exports.fetchRaw = exports.fetch = exports.utils = exports.Log = exports.Capability = exports.RegisterKind = exports.PeprRequest = exports.PeprModule = exports.a = void 0;
7
7
  const client_node_1 = __importDefault(require("@kubernetes/client-node"));
8
8
  exports.k8s = client_node_1.default;
9
9
  const ramda_1 = __importDefault(require("ramda"));
@@ -14,6 +14,7 @@ const fetch_1 = require("./src/lib/fetch");
14
14
  Object.defineProperty(exports, "fetch", { enumerable: true, get: function () { return fetch_1.fetch; } });
15
15
  Object.defineProperty(exports, "fetchRaw", { enumerable: true, get: function () { return fetch_1.fetchRaw; } });
16
16
  const k8s_1 = require("./src/lib/k8s");
17
+ Object.defineProperty(exports, "RegisterKind", { enumerable: true, get: function () { return k8s_1.RegisterKind; } });
17
18
  Object.defineProperty(exports, "a", { enumerable: true, get: function () { return k8s_1.a; } });
18
19
  const logger_1 = __importDefault(require("./src/lib/logger"));
19
20
  exports.Log = logger_1.default;
package/dist/package.json CHANGED
@@ -9,7 +9,7 @@
9
9
  "engines": {
10
10
  "node": ">=18.0.0"
11
11
  },
12
- "version": "0.1.44",
12
+ "version": "0.1.45",
13
13
  "main": "dist/index.js",
14
14
  "types": "dist/index.d.ts",
15
15
  "pepr": {
@@ -1 +1 @@
1
- { "gitignore": "# Ignore node_modules and Pepr build artifacts\nnode_modules\ndist\ninsecure*\n", "readme": "# Pepr Module\n\nThis is a Pepr Module. [Pepr](https://github.com/defenseunicorns/pepr) is a Kubernetes transformation system\nwritten in Typescript.\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├── package.json\n├── pepr.ts\n└── capabilities\n ├── example-one.ts\n ├── example-three.ts\n └── example-two.ts\n```\n", "peprTS": "import { PeprModule } from \"pepr\";\nimport { HelloPepr } from \"./capabilities/hello-pepr\";\nimport cfg from \"./package.json\";\n\n/**\n * This is the main entrypoint for the Pepr module. It is the file that is run when the module is started.\n * This is where you register your configurations and capabilities with the module.\n */\nnew PeprModule(cfg, [\n // \"HelloPepr\" is a demo capability that is included with Pepr. You can remove it if you want.\n HelloPepr,\n\n // Your additional capabilities go here\n]);\n", "helloPeprTS": "import { Capability, PeprRequest, a, fetch } 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 can run `pepr dev` or `npm start` 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\"],\n});\n\n// Use the 'When' function to create a new Capability Action\nconst { When } = HelloPepr;\n\n/**\n * ---------------------------------------------------------------------------------------------------\n * CAPABILITY ACTION *\n * ---------------------------------------------------------------------------------------------------\n *\n * This Capability 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 .Then(ns => ns.RemoveLabel(\"remove-me\"));\n\n/**\n * ---------------------------------------------------------------------------------------------------\n * CAPABILITY ACTION *\n * ---------------------------------------------------------------------------------------------------\n *\n * This is a single Capability Action. They can be in the same file or put imported from other files.\n * In this exmaple, when a ConfigMap is created with the name `example-1`, then add a label and annotation.\n *\n * Equivelant 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 .Then(request =>\n request\n .SetLabel(\"pepr\", \"was-here\")\n .SetAnnotation(\"pepr.dev\", \"annotations-work-too\")\n );\n\n/**\n * ---------------------------------------------------------------------------------------------------\n * CAPABILITY ACTION *\n * ---------------------------------------------------------------------------------------------------\n *\n * This Capabiility Action does the exact same changes for example-2, except this time it uses\n * the `.ThenSet()` feature. You can stack multiple `.Then()` calls, but only a single `.ThenSet()`\n */\nWhen(a.ConfigMap)\n .IsCreated()\n .WithName(\"example-2\")\n .ThenSet({\n metadata: {\n labels: {\n pepr: \"was-here\",\n },\n annotations: {\n \"pepr.dev\": \"annotations-work-too\",\n },\n },\n });\n\n/**\n * ---------------------------------------------------------------------------------------------------\n * CAPABILITY ACTION *\n * ---------------------------------------------------------------------------------------------------\n *\n * This Capability 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 procssed.\n */\nWhen(a.ConfigMap)\n .IsCreatedOrUpdated()\n .WithLabel(\"change\", \"by-label\")\n .Then(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 reuest\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/**\n * ---------------------------------------------------------------------------------------------------\n * CAPABILITY ACTION *\n * ---------------------------------------------------------------------------------------------------\n *\n * This Capability Action show how you can use the `Then()` function to make multiple changes to the\n * same object from different functions. This is useful if you want to keep your Capability Actions\n * small and focused on a single task, or if you want to reuse the same function in multiple\n * Capability Actions.\n *\n * Note that the order of the `.Then()` calls matters. The first call will be executed first,\n * then the second, and so on. Also note the functions are not called until the Capability Action\n * is triggered.\n */\nWhen(a.ConfigMap)\n .IsCreated()\n .WithName(\"example-5\")\n .Then(cm => cm.SetLabel(\"pepr.dev/first\", \"true\"))\n .Then(addSecond)\n .Then(addThird);\n\n//This function uses the complete type definition, but is not required.\nfunction addSecond(cm: PeprRequest<a.ConfigMap>) {\n cm.SetLabel(\"pepr.dev/second\", \"true\");\n}\n\n// This function has no type definition, so you won't have intelisense in the function body.\nfunction addThird(cm) {\n cm.SetLabel(\"pepr.dev/third\", \"true\");\n}\n\n/**\n * ---------------------------------------------------------------------------------------------------\n * CAPABILITY ACTION *\n * ---------------------------------------------------------------------------------------------------\n *\n * This Capability 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 Capability 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 equivelant:\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 .Then(async change => {\n const joke = await fetch<TheChuckNorrisJoke>(\n \"https://api.chucknorris.io/jokes/random?category=dev\"\n );\n\n // Add the Chuck Norris joke to the configmap\n change.Raw.data[\"chuck-says\"] = joke.value;\n });\n" }
1
+ { "gitignore": "# Ignore node_modules and Pepr build artifacts\nnode_modules\ndist\ninsecure*\n", "readme": "# Pepr Module\n\nThis is a Pepr Module. [Pepr](https://github.com/defenseunicorns/pepr) is a Kubernetes transformation system\nwritten in Typescript.\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├── package.json\n├── pepr.ts\n└── capabilities\n ├── example-one.ts\n ├── example-three.ts\n └── example-two.ts\n```\n", "peprTS": "import { PeprModule } from \"pepr\";\nimport { HelloPepr } from \"./capabilities/hello-pepr\";\nimport cfg from \"./package.json\";\n\n/**\n * This is the main entrypoint for the Pepr module. It is the file that is run when the module is started.\n * This is where you register your configurations and capabilities with the module.\n */\nnew PeprModule(cfg, [\n // \"HelloPepr\" is a demo capability that is included with Pepr. You can remove it if you want.\n HelloPepr,\n\n // Your additional capabilities go here\n]);\n", "helloPeprTS": "import { Capability, PeprRequest, RegisterKind, a, fetch } 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 can run `pepr dev` or `npm start` 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\"],\n});\n\n// Use the 'When' function to create a new Capability Action\nconst { When } = HelloPepr;\n\n/**\n * ---------------------------------------------------------------------------------------------------\n * CAPABILITY ACTION *\n * ---------------------------------------------------------------------------------------------------\n *\n * This Capability 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 .Then(ns => ns.RemoveLabel(\"remove-me\"));\n\n/**\n * ---------------------------------------------------------------------------------------------------\n * CAPABILITY ACTION *\n * ---------------------------------------------------------------------------------------------------\n *\n * This is a single Capability Action. They can be in the same file or put imported from other files.\n * In this exmaple, when a ConfigMap is created with the name `example-1`, then add a label and annotation.\n *\n * Equivelant 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 .Then(request =>\n request\n .SetLabel(\"pepr\", \"was-here\")\n .SetAnnotation(\"pepr.dev\", \"annotations-work-too\")\n );\n\n/**\n * ---------------------------------------------------------------------------------------------------\n * CAPABILITY ACTION *\n * ---------------------------------------------------------------------------------------------------\n *\n * This Capabiility Action does the exact same changes for example-2, except this time it uses\n * the `.ThenSet()` feature. You can stack multiple `.Then()` calls, but only a single `.ThenSet()`\n */\nWhen(a.ConfigMap)\n .IsCreated()\n .WithName(\"example-2\")\n .ThenSet({\n metadata: {\n labels: {\n pepr: \"was-here\",\n },\n annotations: {\n \"pepr.dev\": \"annotations-work-too\",\n },\n },\n });\n\n/**\n * ---------------------------------------------------------------------------------------------------\n * CAPABILITY ACTION *\n * ---------------------------------------------------------------------------------------------------\n *\n * This Capability 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 procssed.\n */\nWhen(a.ConfigMap)\n .IsCreatedOrUpdated()\n .WithLabel(\"change\", \"by-label\")\n .Then(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 reuest\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/**\n * ---------------------------------------------------------------------------------------------------\n * CAPABILITY ACTION *\n * ---------------------------------------------------------------------------------------------------\n *\n * This Capability Action show how you can use the `Then()` function to make multiple changes to the\n * same object from different functions. This is useful if you want to keep your Capability Actions\n * small and focused on a single task, or if you want to reuse the same function in multiple\n * Capability Actions.\n *\n * Note that the order of the `.Then()` calls matters. The first call will be executed first,\n * then the second, and so on. Also note the functions are not called until the Capability Action\n * is triggered.\n */\nWhen(a.ConfigMap)\n .IsCreated()\n .WithName(\"example-5\")\n .Then(cm => cm.SetLabel(\"pepr.dev/first\", \"true\"))\n .Then(addSecond)\n .Then(addThird);\n\n//This function uses the complete type definition, but is not required.\nfunction addSecond(cm: PeprRequest<a.ConfigMap>) {\n cm.SetLabel(\"pepr.dev/second\", \"true\");\n}\n\n// This function has no type definition, so you won't have intelisense in the function body.\nfunction addThird(cm) {\n cm.SetLabel(\"pepr.dev/third\", \"true\");\n}\n\n/**\n * ---------------------------------------------------------------------------------------------------\n * CAPABILITY ACTION *\n * ---------------------------------------------------------------------------------------------------\n *\n * This Capability 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 Capability 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 equivelant:\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 .Then(async change => {\n const joke = await fetch<TheChuckNorrisJoke>(\n \"https://api.chucknorris.io/jokes/random?category=dev\"\n );\n\n // Add the Chuck Norris joke to the configmap\n change.Raw.data[\"chuck-says\"] = joke.value;\n });\n\n/**\n * ---------------------------------------------------------------------------------------------------\n * CAPABILITY ACTION *\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 Capability Action should be triggered or not. Since we are using a `GenericKind`,\n * Pepr will not be able to provide any intelisense 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 ot 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 .ThenSet({\n spec: {\n message: \"Hello Pepr without type data!\",\n counter: Math.random(),\n },\n });\n\n/**\n * ---------------------------------------------------------------------------------------------------\n * CAPABILITY ACTION *\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 intelisense\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 Capability 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 Capability Actions, but we are putting it here for demonstration purposes.\n *\n * You will need ot 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 .ThenSet({\n spec: {\n message: \"Hello Pepr now with type data!\",\n counter: Math.random(),\n },\n });\n" }
@@ -67,5 +67,46 @@
67
67
  "name": "example-5",
68
68
  "namespace": "pepr-demo"
69
69
  }
70
+ },
71
+ {
72
+ "apiVersion": "apiextensions.k8s.io/v1",
73
+ "kind": "CustomResourceDefinition",
74
+ "metadata": {
75
+ "name": "unicorns.pepr.dev"
76
+ },
77
+ "spec": {
78
+ "group": "pepr.dev",
79
+ "versions": [
80
+ {
81
+ "name": "v1",
82
+ "served": true,
83
+ "storage": true,
84
+ "schema": {
85
+ "openAPIV3Schema": {
86
+ "type": "object",
87
+ "properties": {
88
+ "spec": {
89
+ "type": "object",
90
+ "properties": {
91
+ "message": {
92
+ "type": "string"
93
+ },
94
+ "counter": {
95
+ "type": "number"
96
+ }
97
+ }
98
+ }
99
+ }
100
+ }
101
+ }
102
+ }
103
+ ],
104
+ "scope": "Namespaced",
105
+ "names": {
106
+ "plural": "unicorns",
107
+ "singular": "unicorn",
108
+ "kind": "Unicorn"
109
+ }
110
+ }
70
111
  }
71
112
  ]
@@ -1,3 +1,4 @@
1
+ import { GroupVersionKind } from "./k8s";
1
2
  import { Binding, CapabilityCfg, GenericClass, HookPhase, WhenSelector } from "./types";
2
3
  /**
3
4
  * A capability is a unit of functionality that can be registered with the Pepr runtime.
@@ -19,8 +20,9 @@ export declare class Capability implements CapabilityCfg {
19
20
  * processed by Pepr. The action will be executed if the resource matches the specified kind and any
20
21
  * filters that are applied.
21
22
  *
22
- * @param model if using a custom KubernetesObject not available in `a.*`, specify the GroupVersionKind
23
+ * @param model the KubernetesObject model to match
24
+ * @param kind if using a custom KubernetesObject not available in `a.*`, specify the GroupVersionKind
23
25
  * @returns
24
26
  */
25
- When: <T extends GenericClass>(model: T) => WhenSelector<T>;
27
+ When: <T extends GenericClass>(model: T, kind?: GroupVersionKind) => WhenSelector<T>;
26
28
  }
@@ -37,13 +37,19 @@ class Capability {
37
37
  * processed by Pepr. The action will be executed if the resource matches the specified kind and any
38
38
  * filters that are applied.
39
39
  *
40
- * @param model if using a custom KubernetesObject not available in `a.*`, specify the GroupVersionKind
40
+ * @param model the KubernetesObject model to match
41
+ * @param kind if using a custom KubernetesObject not available in `a.*`, specify the GroupVersionKind
41
42
  * @returns
42
43
  */
43
- this.When = (model) => {
44
+ this.When = (model, kind) => {
45
+ const matchedKind = (0, k8s_1.modelToGroupVersionKind)(model.name);
46
+ // If the kind is not specified and the model is not a KubernetesObject, throw an error
47
+ if (!matchedKind && !kind) {
48
+ throw new Error(`Kind not specified for ${model.name}`);
49
+ }
44
50
  const binding = {
45
- // If the kind is not specified, use the default KubernetesObject
46
- kind: (0, k8s_1.modelToGroupVersionKind)(model.name),
51
+ // If the kind is not specified, use the matched kind from the model
52
+ kind: kind || matchedKind,
47
53
  filters: {
48
54
  name: "",
49
55
  namespaces: [],
@@ -1,5 +1,5 @@
1
1
  import * as kind from "./upstream";
2
2
  /** a is a colleciton of K8s types to be used within a CapabilityAction: `When(a.Configmap)` */
3
3
  export { kind as a };
4
- export { modelToGroupVersionKind, gvkMap } from "./kinds";
4
+ export { modelToGroupVersionKind, gvkMap, RegisterKind } from "./kinds";
5
5
  export * from "./types";
@@ -28,11 +28,12 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
28
28
  for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
29
29
  };
30
30
  Object.defineProperty(exports, "__esModule", { value: true });
31
- exports.gvkMap = exports.modelToGroupVersionKind = exports.a = void 0;
31
+ exports.RegisterKind = exports.gvkMap = exports.modelToGroupVersionKind = exports.a = void 0;
32
32
  // Export kinds as a single object
33
33
  const kind = __importStar(require("./upstream"));
34
34
  exports.a = kind;
35
35
  var kinds_1 = require("./kinds");
36
36
  Object.defineProperty(exports, "modelToGroupVersionKind", { enumerable: true, get: function () { return kinds_1.modelToGroupVersionKind; } });
37
37
  Object.defineProperty(exports, "gvkMap", { enumerable: true, get: function () { return kinds_1.gvkMap; } });
38
+ Object.defineProperty(exports, "RegisterKind", { enumerable: true, get: function () { return kinds_1.RegisterKind; } });
38
39
  __exportStar(require("./types"), exports);
@@ -1,3 +1,11 @@
1
+ import { GenericClass } from "../types";
1
2
  import { GroupVersionKind } from "./types";
2
3
  export declare const gvkMap: Record<string, GroupVersionKind>;
3
4
  export declare function modelToGroupVersionKind(key: string): GroupVersionKind;
5
+ /**
6
+ * Registers a new model and GroupVersionKind with Pepr for use with `When(a.<Kind>)`
7
+ *
8
+ * @param model Used to match the GroupVersionKind and define the type-data for the request
9
+ * @param groupVersionKind Contains the match paramaters to determine the request should be handled
10
+ */
11
+ export declare const RegisterKind: (model: GenericClass, groupVersionKind: GroupVersionKind) => void;
@@ -2,7 +2,7 @@
2
2
  // SPDX-License-Identifier: Apache-2.0
3
3
  // SPDX-FileCopyrightText: 2023-Present The Pepr Authors
4
4
  Object.defineProperty(exports, "__esModule", { value: true });
5
- exports.modelToGroupVersionKind = exports.gvkMap = void 0;
5
+ exports.RegisterKind = exports.modelToGroupVersionKind = exports.gvkMap = void 0;
6
6
  exports.gvkMap = {
7
7
  /**
8
8
  * Represents a K8s ConfigMap resource.
@@ -429,3 +429,19 @@ function modelToGroupVersionKind(key) {
429
429
  return exports.gvkMap[key];
430
430
  }
431
431
  exports.modelToGroupVersionKind = modelToGroupVersionKind;
432
+ /**
433
+ * Registers a new model and GroupVersionKind with Pepr for use with `When(a.<Kind>)`
434
+ *
435
+ * @param model Used to match the GroupVersionKind and define the type-data for the request
436
+ * @param groupVersionKind Contains the match paramaters to determine the request should be handled
437
+ */
438
+ const RegisterKind = (model, groupVersionKind) => {
439
+ const name = model.name;
440
+ // Do not allow overwriting existing GVKs
441
+ if (exports.gvkMap[name]) {
442
+ throw new Error(`GVK ${name} already registered`);
443
+ }
444
+ // Set the GVK
445
+ exports.gvkMap[name] = groupVersionKind;
446
+ };
447
+ exports.RegisterKind = RegisterKind;
@@ -16,6 +16,17 @@ export interface KubernetesListObject<T extends KubernetesObject> {
16
16
  metadata?: V1ListMeta;
17
17
  items: T[];
18
18
  }
19
+ /**
20
+ * GenericKind is a generic Kubernetes object that can be used to represent any Kubernetes object
21
+ * that is not explicitly supported by Pepr. This can be used on its own or as a base class for
22
+ * other types. See the examples in `HelloPepr.ts` for more information.
23
+ */
24
+ export declare class GenericKind {
25
+ apiVersion?: string;
26
+ kind?: string;
27
+ metadata?: V1ObjectMeta;
28
+ [key: string]: any;
29
+ }
19
30
  /**
20
31
  * GroupVersionKind unambiguously identifies a kind. It doesn't anonymously include GroupVersion
21
32
  * to avoid automatic coercion. It doesn't use a GroupVersion to avoid custom marshalling
@@ -2,7 +2,7 @@
2
2
  // SPDX-License-Identifier: Apache-2.0
3
3
  // SPDX-FileCopyrightText: 2023-Present The Pepr Authors
4
4
  Object.defineProperty(exports, "__esModule", { value: true });
5
- exports.Operation = void 0;
5
+ exports.GenericKind = exports.Operation = void 0;
6
6
  var Operation;
7
7
  (function (Operation) {
8
8
  Operation["CREATE"] = "CREATE";
@@ -10,3 +10,11 @@ var Operation;
10
10
  Operation["DELETE"] = "DELETE";
11
11
  Operation["CONNECT"] = "CONNECT";
12
12
  })(Operation = exports.Operation || (exports.Operation = {}));
13
+ /**
14
+ * GenericKind is a generic Kubernetes object that can be used to represent any Kubernetes object
15
+ * that is not explicitly supported by Pepr. This can be used on its own or as a base class for
16
+ * other types. See the examples in `HelloPepr.ts` for more information.
17
+ */
18
+ class GenericKind {
19
+ }
20
+ exports.GenericKind = GenericKind;
@@ -1,2 +1,3 @@
1
1
  /** a is a colleciton of K8s types to be used within a CapabilityAction: `When(a.Configmap)` */
2
2
  export { V1APIService as APIService, V1CertificateSigningRequest as CertificateSigningRequest, V1ConfigMap as ConfigMap, V1ControllerRevision as ControllerRevision, V1CronJob as CronJob, V1CSIDriver as CSIDriver, V1CSIStorageCapacity as CSIStorageCapacity, V1CustomResourceDefinition as CustomResourceDefinition, V1DaemonSet as DaemonSet, V1Deployment as Deployment, V1EndpointSlice as EndpointSlice, V1HorizontalPodAutoscaler as HorizontalPodAutoscaler, V1Ingress as Ingress, V1IngressClass as IngressClass, V1Job as Job, V1LimitRange as LimitRange, V1LocalSubjectAccessReview as LocalSubjectAccessReview, V1MutatingWebhookConfiguration as MutatingWebhookConfiguration, V1Namespace as Namespace, V1NetworkPolicy as NetworkPolicy, V1Node as Node, V1PersistentVolume as PersistentVolume, V1PersistentVolumeClaim as PersistentVolumeClaim, V1Pod as Pod, V1PodDisruptionBudget as PodDisruptionBudget, V1PodTemplate as PodTemplate, V1ReplicaSet as ReplicaSet, V1ReplicationController as ReplicationController, V1ResourceQuota as ResourceQuota, V1RuntimeClass as RuntimeClass, V1Secret as Secret, V1SelfSubjectAccessReview as SelfSubjectAccessReview, V1SelfSubjectRulesReview as SelfSubjectRulesReview, V1Service as Service, V1ServiceAccount as ServiceAccount, V1StatefulSet as StatefulSet, V1StorageClass as StorageClass, V1SubjectAccessReview as SubjectAccessReview, V1TokenReview as TokenReview, V1ValidatingWebhookConfiguration as ValidatingWebhookConfiguration, V1VolumeAttachment as VolumeAttachment, } from "@kubernetes/client-node/dist";
3
+ export { GenericKind } from "./types";
@@ -2,7 +2,7 @@
2
2
  // SPDX-License-Identifier: Apache-2.0
3
3
  // SPDX-FileCopyrightText: 2023-Present The Pepr Authors
4
4
  Object.defineProperty(exports, "__esModule", { value: true });
5
- exports.VolumeAttachment = exports.ValidatingWebhookConfiguration = exports.TokenReview = exports.SubjectAccessReview = exports.StorageClass = exports.StatefulSet = exports.ServiceAccount = exports.Service = exports.SelfSubjectRulesReview = exports.SelfSubjectAccessReview = exports.Secret = exports.RuntimeClass = exports.ResourceQuota = exports.ReplicationController = exports.ReplicaSet = exports.PodTemplate = exports.PodDisruptionBudget = exports.Pod = exports.PersistentVolumeClaim = exports.PersistentVolume = exports.Node = exports.NetworkPolicy = exports.Namespace = exports.MutatingWebhookConfiguration = exports.LocalSubjectAccessReview = exports.LimitRange = exports.Job = exports.IngressClass = exports.Ingress = exports.HorizontalPodAutoscaler = exports.EndpointSlice = exports.Deployment = exports.DaemonSet = exports.CustomResourceDefinition = exports.CSIStorageCapacity = exports.CSIDriver = exports.CronJob = exports.ControllerRevision = exports.ConfigMap = exports.CertificateSigningRequest = exports.APIService = void 0;
5
+ exports.GenericKind = exports.VolumeAttachment = exports.ValidatingWebhookConfiguration = exports.TokenReview = exports.SubjectAccessReview = exports.StorageClass = exports.StatefulSet = exports.ServiceAccount = exports.Service = exports.SelfSubjectRulesReview = exports.SelfSubjectAccessReview = exports.Secret = exports.RuntimeClass = exports.ResourceQuota = exports.ReplicationController = exports.ReplicaSet = exports.PodTemplate = exports.PodDisruptionBudget = exports.Pod = exports.PersistentVolumeClaim = exports.PersistentVolume = exports.Node = exports.NetworkPolicy = exports.Namespace = exports.MutatingWebhookConfiguration = exports.LocalSubjectAccessReview = exports.LimitRange = exports.Job = exports.IngressClass = exports.Ingress = exports.HorizontalPodAutoscaler = exports.EndpointSlice = exports.Deployment = exports.DaemonSet = exports.CustomResourceDefinition = exports.CSIStorageCapacity = exports.CSIDriver = exports.CronJob = exports.ControllerRevision = exports.ConfigMap = exports.CertificateSigningRequest = exports.APIService = void 0;
6
6
  /** a is a colleciton of K8s types to be used within a CapabilityAction: `When(a.Configmap)` */
7
7
  var dist_1 = require("@kubernetes/client-node/dist");
8
8
  Object.defineProperty(exports, "APIService", { enumerable: true, get: function () { return dist_1.V1APIService; } });
@@ -46,3 +46,5 @@ Object.defineProperty(exports, "SubjectAccessReview", { enumerable: true, get: f
46
46
  Object.defineProperty(exports, "TokenReview", { enumerable: true, get: function () { return dist_1.V1TokenReview; } });
47
47
  Object.defineProperty(exports, "ValidatingWebhookConfiguration", { enumerable: true, get: function () { return dist_1.V1ValidatingWebhookConfiguration; } });
48
48
  Object.defineProperty(exports, "VolumeAttachment", { enumerable: true, get: function () { return dist_1.V1VolumeAttachment; } });
49
+ var types_1 = require("./types");
50
+ Object.defineProperty(exports, "GenericKind", { enumerable: true, get: function () { return types_1.GenericKind; } });
package/package.json CHANGED
@@ -9,7 +9,7 @@
9
9
  "engines": {
10
10
  "node": ">=18.0.0"
11
11
  },
12
- "version": "0.1.44",
12
+ "version": "0.1.45",
13
13
  "main": "dist/index.js",
14
14
  "types": "dist/index.d.ts",
15
15
  "pepr": {