pepr 0.3.2 → 0.4.0

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 (103) hide show
  1. package/dist/cli.d.ts +3 -0
  2. package/dist/cli.d.ts.map +1 -0
  3. package/dist/cli.js +1420 -0
  4. package/dist/controller.js +157 -0
  5. package/dist/{src/lib → lib}/capability.d.ts +1 -1
  6. package/dist/lib/capability.d.ts.map +1 -0
  7. package/dist/lib/controller.d.ts.map +1 -0
  8. package/dist/{src/lib → lib}/fetch.d.ts +1 -2
  9. package/dist/lib/fetch.d.ts.map +1 -0
  10. package/dist/{src/lib → lib}/filter.d.ts +1 -1
  11. package/dist/lib/filter.d.ts.map +1 -0
  12. package/dist/lib/k8s/index.d.ts.map +1 -0
  13. package/dist/lib/k8s/kinds.d.ts.map +1 -0
  14. package/dist/lib/k8s/tls.d.ts.map +1 -0
  15. package/dist/lib/k8s/types.d.ts.map +1 -0
  16. package/dist/{src/lib → lib}/k8s/upstream.d.ts +2 -2
  17. package/dist/lib/k8s/upstream.d.ts.map +1 -0
  18. package/dist/{src/lib → lib}/k8s/webhook.d.ts +1 -1
  19. package/dist/lib/k8s/webhook.d.ts.map +1 -0
  20. package/dist/lib/logger.d.ts.map +1 -0
  21. package/dist/lib/module.d.ts.map +1 -0
  22. package/dist/lib/processor.d.ts.map +1 -0
  23. package/dist/{src/lib → lib}/request.d.ts +1 -1
  24. package/dist/lib/request.d.ts.map +1 -0
  25. package/dist/{src/lib → lib}/types.d.ts +5 -1
  26. package/dist/lib/types.d.ts.map +1 -0
  27. package/dist/{src/lib/index.d.ts → lib.d.ts} +8 -8
  28. package/dist/lib.d.ts.map +1 -0
  29. package/dist/lib.js +1150 -0
  30. package/dist/lib.js.map +7 -0
  31. package/package.json +8 -12
  32. package/src/cli.ts +37 -0
  33. package/src/lib/capability.ts +2 -1
  34. package/src/lib/controller.ts +15 -1
  35. package/src/lib/fetch.ts +3 -2
  36. package/src/lib/filter.ts +1 -1
  37. package/src/lib/k8s/upstream.ts +2 -2
  38. package/src/lib/k8s/webhook.ts +8 -3
  39. package/src/lib/module.ts +3 -2
  40. package/src/lib/processor.ts +2 -2
  41. package/src/lib/request.ts +4 -4
  42. package/src/lib/types.ts +6 -1
  43. package/src/{lib/index.ts → lib.ts} +7 -7
  44. package/dist/package.json +0 -66
  45. package/dist/src/cli/banner.js +0 -70
  46. package/dist/src/cli/build.js +0 -120
  47. package/dist/src/cli/capability.js +0 -14
  48. package/dist/src/cli/deploy.js +0 -54
  49. package/dist/src/cli/dev.js +0 -114
  50. package/dist/src/cli/index.js +0 -35
  51. package/dist/src/cli/init/index.js +0 -81
  52. package/dist/src/cli/init/templates/.prettierrc.json +0 -13
  53. package/dist/src/cli/init/templates/capabilities/hello-pepr.samples.json +0 -115
  54. package/dist/src/cli/init/templates/data.json +0 -1
  55. package/dist/src/cli/init/templates/pepr.code-snippets.json +0 -21
  56. package/dist/src/cli/init/templates/tsconfig.module.json +0 -12
  57. package/dist/src/cli/init/templates.js +0 -96
  58. package/dist/src/cli/init/utils.js +0 -56
  59. package/dist/src/cli/init/walkthrough.js +0 -84
  60. package/dist/src/cli/root.js +0 -21
  61. package/dist/src/cli/run.js +0 -58
  62. package/dist/src/cli/test.js +0 -50
  63. package/dist/src/cli/update.js +0 -58
  64. package/dist/src/lib/capability.d.ts.map +0 -1
  65. package/dist/src/lib/capability.js +0 -125
  66. package/dist/src/lib/controller.d.ts.map +0 -1
  67. package/dist/src/lib/controller.js +0 -108
  68. package/dist/src/lib/fetch.d.ts.map +0 -1
  69. package/dist/src/lib/fetch.js +0 -92
  70. package/dist/src/lib/filter.d.ts.map +0 -1
  71. package/dist/src/lib/filter.js +0 -77
  72. package/dist/src/lib/index.d.ts.map +0 -1
  73. package/dist/src/lib/index.js +0 -26
  74. package/dist/src/lib/k8s/index.d.ts.map +0 -1
  75. package/dist/src/lib/k8s/index.js +0 -39
  76. package/dist/src/lib/k8s/kinds.d.ts.map +0 -1
  77. package/dist/src/lib/k8s/kinds.js +0 -447
  78. package/dist/src/lib/k8s/tls.d.ts.map +0 -1
  79. package/dist/src/lib/k8s/tls.js +0 -74
  80. package/dist/src/lib/k8s/types.d.ts.map +0 -1
  81. package/dist/src/lib/k8s/types.js +0 -20
  82. package/dist/src/lib/k8s/upstream.d.ts.map +0 -1
  83. package/dist/src/lib/k8s/upstream.js +0 -50
  84. package/dist/src/lib/k8s/webhook.d.ts.map +0 -1
  85. package/dist/src/lib/k8s/webhook.js +0 -502
  86. package/dist/src/lib/logger.d.ts.map +0 -1
  87. package/dist/src/lib/logger.js +0 -125
  88. package/dist/src/lib/module.d.ts.map +0 -1
  89. package/dist/src/lib/module.js +0 -43
  90. package/dist/src/lib/processor.d.ts.map +0 -1
  91. package/dist/src/lib/processor.js +0 -85
  92. package/dist/src/lib/request.d.ts.map +0 -1
  93. package/dist/src/lib/request.js +0 -124
  94. package/dist/src/lib/types.d.ts.map +0 -1
  95. package/dist/src/lib/types.js +0 -34
  96. /package/dist/{src/lib → lib}/controller.d.ts +0 -0
  97. /package/dist/{src/lib → lib}/k8s/index.d.ts +0 -0
  98. /package/dist/{src/lib → lib}/k8s/kinds.d.ts +0 -0
  99. /package/dist/{src/lib → lib}/k8s/tls.d.ts +0 -0
  100. /package/dist/{src/lib → lib}/k8s/types.d.ts +0 -0
  101. /package/dist/{src/lib → lib}/logger.d.ts +0 -0
  102. /package/dist/{src/lib → lib}/module.d.ts +0 -0
  103. /package/dist/{src/lib → lib}/processor.d.ts +0 -0
@@ -1,35 +0,0 @@
1
- #!/usr/bin/env node
2
- "use strict";
3
- // SPDX-License-Identifier: Apache-2.0
4
- // SPDX-FileCopyrightText: 2023-Present The Pepr Authors
5
- var __importDefault = (this && this.__importDefault) || function (mod) {
6
- return (mod && mod.__esModule) ? mod : { "default": mod };
7
- };
8
- Object.defineProperty(exports, "__esModule", { value: true });
9
- const package_json_1 = require("../../package.json");
10
- const banner_1 = require("./banner");
11
- const build_1 = __importDefault(require("./build"));
12
- const deploy_1 = __importDefault(require("./deploy"));
13
- const dev_1 = __importDefault(require("./dev"));
14
- const init_1 = __importDefault(require("./init"));
15
- const root_1 = require("./root");
16
- const update_1 = __importDefault(require("./update"));
17
- const program = new root_1.RootCmd();
18
- program
19
- .version(package_json_1.version)
20
- .description(`Pepr Kubernetes Thingy (v${package_json_1.version})`)
21
- .action(() => {
22
- if (program.args.length < 1) {
23
- console.log(banner_1.banner);
24
- program.help();
25
- }
26
- });
27
- (0, init_1.default)(program);
28
- (0, build_1.default)(program);
29
- (0, deploy_1.default)(program);
30
- (0, dev_1.default)(program);
31
- (0, update_1.default)(program);
32
- // @todo: finish/re-evaluate these commands
33
- // test(program);
34
- // capability(program);
35
- program.parse();
@@ -1,81 +0,0 @@
1
- "use strict";
2
- // SPDX-License-Identifier: Apache-2.0
3
- // SPDX-FileCopyrightText: 2023-Present The Pepr Authors
4
- var __importDefault = (this && this.__importDefault) || function (mod) {
5
- return (mod && mod.__esModule) ? mod : { "default": mod };
6
- };
7
- Object.defineProperty(exports, "__esModule", { value: true });
8
- const child_process_1 = require("child_process");
9
- const path_1 = require("path");
10
- const prompts_1 = __importDefault(require("prompts"));
11
- const logger_1 = __importDefault(require("../../../src/lib/logger"));
12
- const templates_1 = require("./templates");
13
- const utils_1 = require("./utils");
14
- const walkthrough_1 = require("./walkthrough");
15
- function default_1(program) {
16
- program
17
- .command("init")
18
- .description("Initialize a new Pepr Module")
19
- // skip auto npm install and git init
20
- .option("--skip-post-init", "Skip npm install, git init and VSCode launch")
21
- .action(async (opts) => {
22
- let pkgOverride = "";
23
- // Overrides for testing. @todo: don't be so gross with Node CLI testing
24
- if (process.env.TEST_MODE === "true") {
25
- prompts_1.default.inject(["pepr-test-module", "A test module for Pepr", "ignore", "y"]);
26
- pkgOverride = "file:../pepr-0.0.0-development.tgz";
27
- }
28
- const response = await (0, walkthrough_1.walkthrough)();
29
- const dirName = (0, utils_1.sanitizeName)(response.name);
30
- const packageJSON = (0, templates_1.genPkgJSON)(response, pkgOverride);
31
- const peprTS = (0, templates_1.genPeprTS)();
32
- const confirmed = await (0, walkthrough_1.confirm)(dirName, packageJSON, peprTS.path);
33
- if (confirmed) {
34
- console.log("Creating new Pepr module...");
35
- try {
36
- await (0, utils_1.createDir)(dirName);
37
- await (0, utils_1.createDir)((0, path_1.resolve)(dirName, ".vscode"));
38
- await (0, utils_1.createDir)((0, path_1.resolve)(dirName, "capabilities"));
39
- await (0, utils_1.write)((0, path_1.resolve)(dirName, templates_1.gitIgnore.path), templates_1.gitIgnore.data);
40
- await (0, utils_1.write)((0, path_1.resolve)(dirName, templates_1.prettierRC.path), templates_1.prettierRC.data);
41
- await (0, utils_1.write)((0, path_1.resolve)(dirName, packageJSON.path), packageJSON.data);
42
- await (0, utils_1.write)((0, path_1.resolve)(dirName, templates_1.readme.path), templates_1.readme.data);
43
- await (0, utils_1.write)((0, path_1.resolve)(dirName, templates_1.tsConfig.path), templates_1.tsConfig.data);
44
- await (0, utils_1.write)((0, path_1.resolve)(dirName, peprTS.path), peprTS.data);
45
- await (0, utils_1.write)((0, path_1.resolve)(dirName, ".vscode", templates_1.snippet.path), templates_1.snippet.data);
46
- await (0, utils_1.write)((0, path_1.resolve)(dirName, "capabilities", templates_1.samplesYaml.path), templates_1.samplesYaml.data);
47
- await (0, utils_1.write)((0, path_1.resolve)(dirName, "capabilities", templates_1.helloPeprTS.path), templates_1.helloPeprTS.data);
48
- if (!opts.skipPostInit) {
49
- // run npm install from the new directory
50
- process.chdir(dirName);
51
- (0, child_process_1.execSync)("npm install", {
52
- stdio: "inherit",
53
- });
54
- // setup git
55
- (0, child_process_1.execSync)("git init", {
56
- stdio: "inherit",
57
- });
58
- // try to open vscode
59
- try {
60
- (0, child_process_1.execSync)("code .", {
61
- stdio: "inherit",
62
- });
63
- }
64
- catch (e) {
65
- // vscode not found, do nothing
66
- }
67
- }
68
- console.log(`New Pepr module created at ${dirName}`);
69
- console.log(`Open VSCode or your editor of choice in ${dirName} to get started!`);
70
- }
71
- catch (e) {
72
- logger_1.default.debug(e);
73
- if (e instanceof Error) {
74
- logger_1.default.error(e.message);
75
- }
76
- process.exit(1);
77
- }
78
- }
79
- });
80
- }
81
- exports.default = default_1;
@@ -1,13 +0,0 @@
1
- {
2
- "arrowParens": "avoid",
3
- "bracketSameLine": false,
4
- "bracketSpacing": true,
5
- "embeddedLanguageFormatting": "auto",
6
- "insertPragma": false,
7
- "printWidth": 80,
8
- "quoteProps": "as-needed",
9
- "requirePragma": false,
10
- "semi": true,
11
- "tabWidth": 2,
12
- "useTabs": false
13
- }
@@ -1,115 +0,0 @@
1
- [
2
- {
3
- "apiVersion": "v1",
4
- "kind": "Namespace",
5
- "metadata": {
6
- "name": "pepr-demo",
7
- "labels": {
8
- "keep-me": "please",
9
- "remove-me": "please"
10
- }
11
- }
12
- },
13
- {
14
- "apiVersion": "v1",
15
- "kind": "ConfigMap",
16
- "metadata": {
17
- "name": "example-1",
18
- "namespace": "pepr-demo"
19
- },
20
- "data": {
21
- "key": "ex-1-val"
22
- }
23
- },
24
- {
25
- "apiVersion": "v1",
26
- "kind": "ConfigMap",
27
- "metadata": {
28
- "name": "example-2",
29
- "namespace": "pepr-demo"
30
- },
31
- "data": {
32
- "key": "ex-2-val"
33
- }
34
- },
35
- {
36
- "apiVersion": "v1",
37
- "kind": "ConfigMap",
38
- "metadata": {
39
- "name": "example-3",
40
- "namespace": "pepr-demo",
41
- "labels": {
42
- "change": "by-label"
43
- }
44
- },
45
- "data": {
46
- "key": "ex-3-val"
47
- }
48
- },
49
- {
50
- "apiVersion": "v1",
51
- "kind": "ConfigMap",
52
- "metadata": {
53
- "name": "example-4",
54
- "namespace": "pepr-demo"
55
- },
56
- "data": {
57
- "key": "ex-4-val"
58
- }
59
- },
60
- {
61
- "apiVersion": "v1",
62
- "kind": "ConfigMap",
63
- "metadata": {
64
- "name": "example-5",
65
- "namespace": "pepr-demo",
66
- "labels": {
67
- "chuck-norris": "test"
68
- }
69
- },
70
- "data": {
71
- "key": "ex-5-val"
72
- }
73
- },
74
- {
75
- "apiVersion": "apiextensions.k8s.io/v1",
76
- "kind": "CustomResourceDefinition",
77
- "metadata": {
78
- "name": "unicorns.pepr.dev"
79
- },
80
- "spec": {
81
- "group": "pepr.dev",
82
- "versions": [
83
- {
84
- "name": "v1",
85
- "served": true,
86
- "storage": true,
87
- "schema": {
88
- "openAPIV3Schema": {
89
- "type": "object",
90
- "properties": {
91
- "spec": {
92
- "type": "object",
93
- "properties": {
94
- "message": {
95
- "type": "string"
96
- },
97
- "counter": {
98
- "type": "number"
99
- }
100
- }
101
- }
102
- }
103
- }
104
- }
105
- }
106
- ],
107
- "scope": "Namespaced",
108
- "names": {
109
- "plural": "unicorns",
110
- "singular": "unicorn",
111
- "kind": "Unicorn"
112
- }
113
- }
114
- }
115
- ]
@@ -1 +0,0 @@
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 { Log, PeprModule } from \"pepr\";\nimport { HelloPepr } from \"./capabilities/hello-pepr\";\n// cfg loads your pepr configuration from package.json\nimport cfg from \"./package.json\";\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(\n cfg,\n [\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 {\n // Any actions you want to perform before the request is processed, including modifying the request.\n // Comment out or delete the line below to remove the default beforeHook.\n beforeHook: req => Log.debug(`beforeHook: ${req.uid}`),\n\n // Any actions you want to perform after the request is processed, including modifying the response.\n // Comment out or delete the line below to remove the default afterHook.\n afterHook: res => Log.debug(`afterHook: ${res.uid}`),\n }\n);\n", "helloPeprTS": "import {\n Capability,\n PeprRequest,\n RegisterKind,\n a,\n fetch,\n fetchStatus,\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 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 (Namespace) *\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 (CM Example 1) *\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 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 .Then(request =>\n request\n .SetLabel(\"pepr\", \"was-here\")\n .SetAnnotation(\"pepr.dev\", \"annotations-work-too\")\n );\n\n/**\n * ---------------------------------------------------------------------------------------------------\n * CAPABILITY ACTION (CM Example 2) *\n * ---------------------------------------------------------------------------------------------------\n *\n * This Capability 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 (CM Example 3) *\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 processed.\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 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/**\n * ---------------------------------------------------------------------------------------------------\n * CAPABILITY ACTION (CM Example 4) *\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-4\")\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 intellisense in the function body.\nfunction addThird(cm) {\n cm.SetLabel(\"pepr.dev/third\", \"true\");\n}\n\n/**\n * ---------------------------------------------------------------------------------------------------\n * CAPABILITY ACTION (CM Example 5) *\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 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 .Then(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 * CAPABILITY 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 Capability 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 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 (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 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" }
@@ -1,21 +0,0 @@
1
- {
2
- "Create a new Pepr capability": {
3
- "prefix": "create pepr capability",
4
- "body": [
5
- "import { Capability, a } from 'pepr';",
6
- "",
7
- "export const ${TM_FILENAME_BASE/(.*)/${1:/pascalcase}/} = new Capability({",
8
- "\tname: '${TM_FILENAME_BASE}',",
9
- "\tdescription: '${1:A brief description of this capability.}',",
10
- "\tnamespaces: [${2:}],",
11
- "});",
12
- "",
13
- "// Use the 'When' function to create a new Capability Action",
14
- "const { When } = ${TM_FILENAME_BASE/(.*)/${1:/pascalcase}/};",
15
- "",
16
- "// When(a.<Kind>).Is<Event>().Then(change => change.<changes>",
17
- "When(${3:})"
18
- ],
19
- "description": "Creates a new Pepr capability with a specified description, and optional namespaces, and adds a When statement for the specified value."
20
- }
21
- }
@@ -1,12 +0,0 @@
1
- {
2
- "compilerOptions": {
3
- "esModuleInterop": true,
4
- "lib": ["ES2020"],
5
- "moduleResolution": "node",
6
- "resolveJsonModule": true,
7
- "rootDir": ".",
8
- "strict": false,
9
- "target": "ES2020"
10
- },
11
- "include": ["**/*.ts"]
12
- }
@@ -1,96 +0,0 @@
1
- "use strict";
2
- // SPDX-License-Identifier: Apache-2.0
3
- // SPDX-FileCopyrightText: 2023-Present The Pepr Authors
4
- var __importDefault = (this && this.__importDefault) || function (mod) {
5
- return (mod && mod.__esModule) ? mod : { "default": mod };
6
- };
7
- Object.defineProperty(exports, "__esModule", { value: true });
8
- exports.prettierRC = exports.tsConfig = exports.snippet = exports.samplesYaml = exports.gitIgnore = exports.helloPeprTS = exports.readme = exports.genPeprTS = exports.genPkgJSON = void 0;
9
- const client_node_1 = require("@kubernetes/client-node");
10
- const util_1 = require("util");
11
- const uuid_1 = require("uuid");
12
- const package_json_1 = require("../../../package.json");
13
- const _prettierrc_json_1 = __importDefault(require("./templates/.prettierrc.json"));
14
- const hello_pepr_samples_json_1 = __importDefault(require("./templates/capabilities/hello-pepr.samples.json"));
15
- const data_json_1 = __importDefault(require("./templates/data.json"));
16
- const pepr_code_snippets_json_1 = __importDefault(require("./templates/pepr.code-snippets.json"));
17
- const tsconfig_module_json_1 = __importDefault(require("./templates/tsconfig.module.json"));
18
- const utils_1 = require("./utils");
19
- function genPkgJSON(opts, pgkVerOverride) {
20
- // Generate a random UUID for the module based on the module name
21
- const uuid = (0, uuid_1.v5)(opts.name, (0, uuid_1.v4)());
22
- // Generate a name for the module based on the module name
23
- const name = (0, utils_1.sanitizeName)(opts.name);
24
- // Make typescript a dev dependency
25
- const { typescript } = package_json_1.peerDependencies;
26
- const { prettier } = package_json_1.devDependencies;
27
- const data = {
28
- name,
29
- version: "0.0.1",
30
- description: opts.description,
31
- keywords: ["pepr", "k8s", "policy-engine", "pepr-module", "security"],
32
- pepr: {
33
- name: opts.name.trim(),
34
- uuid: pgkVerOverride ? "static-test" : uuid,
35
- onError: opts.errorBehavior,
36
- alwaysIgnore: {
37
- namespaces: [],
38
- labels: [],
39
- },
40
- },
41
- scripts: {
42
- "k3d-setup": package_json_1.scripts["test:e2e:k3d"],
43
- build: "pepr build",
44
- deploy: "pepr deploy",
45
- start: "pepr dev",
46
- },
47
- dependencies: {
48
- pepr: pgkVerOverride || `${package_json_1.version}`,
49
- },
50
- devDependencies: {
51
- prettier,
52
- typescript,
53
- },
54
- };
55
- return {
56
- data,
57
- path: "package.json",
58
- print: (0, util_1.inspect)(data, false, 5, true),
59
- };
60
- }
61
- exports.genPkgJSON = genPkgJSON;
62
- function genPeprTS() {
63
- return {
64
- path: "pepr.ts",
65
- data: data_json_1.default.peprTS,
66
- };
67
- }
68
- exports.genPeprTS = genPeprTS;
69
- exports.readme = {
70
- path: "README.md",
71
- data: data_json_1.default.readme,
72
- };
73
- exports.helloPeprTS = {
74
- path: "hello-pepr.ts",
75
- data: data_json_1.default.helloPeprTS,
76
- };
77
- exports.gitIgnore = {
78
- path: ".gitignore",
79
- data: data_json_1.default.gitignore,
80
- };
81
- exports.samplesYaml = {
82
- path: "hello-pepr.samples.yaml",
83
- data: hello_pepr_samples_json_1.default.map(r => (0, client_node_1.dumpYaml)(r, { noRefs: true })).join("---\n"),
84
- };
85
- exports.snippet = {
86
- path: "pepr.code-snippets",
87
- data: pepr_code_snippets_json_1.default,
88
- };
89
- exports.tsConfig = {
90
- path: "tsconfig.json",
91
- data: tsconfig_module_json_1.default,
92
- };
93
- exports.prettierRC = {
94
- path: ".prettierrc",
95
- data: _prettierrc_json_1.default,
96
- };
@@ -1,56 +0,0 @@
1
- "use strict";
2
- // SPDX-License-Identifier: Apache-2.0
3
- // SPDX-FileCopyrightText: 2023-Present The Pepr Authors
4
- Object.defineProperty(exports, "__esModule", { value: true });
5
- exports.write = exports.createDir = exports.sanitizeName = void 0;
6
- const fs_1 = require("fs");
7
- /**
8
- * Sanitize a user input name to be used as a pepr module directory name
9
- *
10
- * @param name the user input name
11
- * @returns the sanitized name
12
- */
13
- function sanitizeName(name) {
14
- // Replace any characters outside of [^a-z0-9-] with "-"
15
- let sanitized = name.toLowerCase().replace(/[^a-z0-9-]+/gi, "-");
16
- // Remove any leading or trailing hyphens
17
- sanitized = sanitized.replace(/^-+|-+$/g, "");
18
- // Replace multiple hyphens with a single hyphen
19
- sanitized = sanitized.replace(/--+/g, "-");
20
- return sanitized;
21
- }
22
- exports.sanitizeName = sanitizeName;
23
- /**
24
- * Creates a directory and throws an error if it already exists
25
- *
26
- * @param dir - The directory to create
27
- */
28
- async function createDir(dir) {
29
- try {
30
- await fs_1.promises.mkdir(dir);
31
- }
32
- catch (err) {
33
- // The directory already exists
34
- if (err && err.code === "EEXIST") {
35
- throw new Error(`Directory ${dir} already exists`);
36
- }
37
- else {
38
- throw err;
39
- }
40
- }
41
- }
42
- exports.createDir = createDir;
43
- /**
44
- * Write data to a file on disk
45
- * @param path - The path to the file
46
- * @param data - The data to write
47
- * @returns A promise that resolves when the file has been written
48
- */
49
- function write(path, data) {
50
- // If the data is not a string, stringify it
51
- if (typeof data !== "string") {
52
- data = JSON.stringify(data, null, 2);
53
- }
54
- return fs_1.promises.writeFile(path, data);
55
- }
56
- exports.write = write;
@@ -1,84 +0,0 @@
1
- "use strict";
2
- // SPDX-License-Identifier: Apache-2.0
3
- // SPDX-FileCopyrightText: 2023-Present The Pepr Authors
4
- var __importDefault = (this && this.__importDefault) || function (mod) {
5
- return (mod && mod.__esModule) ? mod : { "default": mod };
6
- };
7
- Object.defineProperty(exports, "__esModule", { value: true });
8
- exports.confirm = exports.walkthrough = void 0;
9
- const fs_1 = require("fs");
10
- const prompts_1 = __importDefault(require("prompts"));
11
- const types_1 = require("../../../src/lib/types");
12
- const templates_1 = require("./templates");
13
- const utils_1 = require("./utils");
14
- function walkthrough() {
15
- const askName = {
16
- type: "text",
17
- name: "name",
18
- message: "Enter a name for the new Pepr module. This will create a new directory based on the name.\n",
19
- validate: async (val) => {
20
- try {
21
- const name = (0, utils_1.sanitizeName)(val);
22
- await fs_1.promises.access(name, fs_1.promises.constants.F_OK);
23
- return "A directory with this name already exists";
24
- }
25
- catch (e) {
26
- return val.length > 2 || "The name must be at least 3 characters long";
27
- }
28
- },
29
- };
30
- const askDescription = {
31
- type: "text",
32
- name: "description",
33
- message: "(Recommended) Enter a description for the new Pepr module.\n",
34
- };
35
- const askErrorBehavior = {
36
- type: "select",
37
- name: "errorBehavior",
38
- validate: (val) => types_1.ErrorBehavior[val],
39
- message: "How do you want Pepr to handle errors encountered during K8s operations?",
40
- choices: [
41
- {
42
- title: "Ignore",
43
- value: types_1.ErrorBehavior.ignore,
44
- description: "Pepr will continue processing and generate an entry in the Pepr Controller log.",
45
- selected: true,
46
- },
47
- {
48
- title: "Log an audit event",
49
- value: types_1.ErrorBehavior.audit,
50
- description: "Pepr will continue processing and generate an entry in the Pepr Controller log as well as an audit event in the cluster.",
51
- },
52
- {
53
- title: "Reject the operation",
54
- value: types_1.ErrorBehavior.reject,
55
- description: "Pepr will reject the operation and return an error to the client.",
56
- },
57
- ],
58
- };
59
- return (0, prompts_1.default)([askName, askDescription, askErrorBehavior]);
60
- }
61
- exports.walkthrough = walkthrough;
62
- async function confirm(dirName, packageJSON, peprTSPath) {
63
- console.log(`
64
- To be generated:
65
-
66
- \x1b[1m${dirName}\x1b[0m
67
- ├── \x1b[1m${templates_1.gitIgnore.path}\x1b[0m
68
- ├── \x1b[1m${templates_1.prettierRC.path}\x1b[0m
69
- ├── \x1b[1mcapabilties\x1b[0m
70
- | └── \x1b[1mhello-pepr.ts\x1b[0m
71
- ├── \x1b[1m${packageJSON.path}\x1b[0m
72
- ${packageJSON.print.replace(/^/gm, " │ ")}
73
- ├── \x1b[1m${peprTSPath}\x1b[0m
74
- ├── \x1b[1m${templates_1.readme.path}\x1b[0m
75
- └── \x1b[1m${templates_1.tsConfig.path}\x1b[0m
76
- `);
77
- const confirm = await (0, prompts_1.default)({
78
- type: "confirm",
79
- name: "confirm",
80
- message: "Create the new Pepr module?",
81
- });
82
- return confirm.confirm;
83
- }
84
- exports.confirm = confirm;
@@ -1,21 +0,0 @@
1
- "use strict";
2
- // SPDX-License-Identifier: Apache-2.0
3
- // SPDX-FileCopyrightText: 2023-Present The Pepr Authors
4
- var __importDefault = (this && this.__importDefault) || function (mod) {
5
- return (mod && mod.__esModule) ? mod : { "default": mod };
6
- };
7
- Object.defineProperty(exports, "__esModule", { value: true });
8
- exports.RootCmd = void 0;
9
- const commander_1 = require("commander");
10
- const logger_1 = __importDefault(require("../../src/lib/logger"));
11
- class RootCmd extends commander_1.Command {
12
- createCommand(name) {
13
- const cmd = new commander_1.Command(name);
14
- cmd.option("-l, --log-level [level]", "Log level: debug, info, warn, error", "info");
15
- cmd.hook("preAction", run => {
16
- logger_1.default.SetLogLevel(run.opts().logLevel);
17
- });
18
- return cmd;
19
- }
20
- }
21
- exports.RootCmd = RootCmd;
@@ -1,58 +0,0 @@
1
- #!/usr/bin/env node
2
- "use strict";
3
- // SPDX-License-Identifier: Apache-2.0
4
- // SPDX-FileCopyrightText: 2023-Present The Pepr Authors
5
- var __importDefault = (this && this.__importDefault) || function (mod) {
6
- return (mod && mod.__esModule) ? mod : { "default": mod };
7
- };
8
- Object.defineProperty(exports, "__esModule", { value: true });
9
- const child_process_1 = require("child_process");
10
- const crypto_1 = __importDefault(require("crypto"));
11
- const fs_1 = __importDefault(require("fs"));
12
- const zlib_1 = require("zlib");
13
- const package_json_1 = require("../../package.json");
14
- const logger_1 = __importDefault(require("../lib/logger"));
15
- function validateHash(expectedHash) {
16
- // Require the hash to be 64 characters long
17
- if (!expectedHash || expectedHash.length !== 64) {
18
- logger_1.default.error("Invalid hash");
19
- process.exit(1);
20
- }
21
- }
22
- function runModule(expectedHash) {
23
- const gzPath = `/app/load/module-${expectedHash}.js.gz`;
24
- const jsPath = `/app/module-${expectedHash}.js`;
25
- // Set the log level
26
- logger_1.default.SetLogLevel("debug");
27
- // Check if the path is a valid file
28
- if (!fs_1.default.existsSync(gzPath)) {
29
- logger_1.default.error(`File not found: ${gzPath}`);
30
- process.exit(1);
31
- }
32
- try {
33
- logger_1.default.info(`Loading module ${gzPath}`);
34
- // Extract the code from the file
35
- const codeGZ = fs_1.default.readFileSync(gzPath);
36
- const code = (0, zlib_1.gunzipSync)(codeGZ);
37
- // Get the hash of the extracted code
38
- const actualHash = crypto_1.default.createHash("sha256").update(code).digest("hex");
39
- // If the hash doesn't match, exit
40
- if (expectedHash !== actualHash) {
41
- logger_1.default.error(`File hash does not match, expected ${expectedHash} but got ${actualHash}`);
42
- process.exit(1);
43
- }
44
- logger_1.default.info(`File hash matches, running module`);
45
- // Write the code to a file
46
- fs_1.default.writeFileSync(jsPath, code);
47
- // Run the module
48
- (0, child_process_1.fork)(jsPath);
49
- }
50
- catch (e) {
51
- logger_1.default.error(`Failed to decompress module: ${e}`);
52
- process.exit(1);
53
- }
54
- }
55
- logger_1.default.info(`Pepr Controller (v${package_json_1.version})`);
56
- const hash = process.argv[2];
57
- validateHash(hash);
58
- runModule(hash);