@cloudoperators/juno-k8s-client 1.0.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.
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,141 @@
1
+ # JavaScript client for Kubernetes API
2
+
3
+ This client is designed for use in the browser (not tested in Node.js). It utilizes the fetch API and is compatible with all modern browsers. For older browsers, the fetch polyfill (github/fetch) should be used.
4
+
5
+ The k8sclient facilitates communication with the Kubernetes API. It minimizes data interpretation and adds only essential logic. In addition to standard HTTP methods like GET or POST, it implements the WATCH method, which establishes a stream to the server and reacts to events.
6
+
7
+ All functions return Promise objects and can therefore be processed with a chain of then calls. Potential errors can be caught using the catch method.
8
+
9
+ The client requires a Kubernetes API endpoint and a token. Once both parameters are provided, the following functions are available:
10
+
11
+ - head
12
+ - get
13
+ - post
14
+ - put
15
+ - patch
16
+ - delete
17
+ - watch
18
+
19
+ # Installation
20
+
21
+ With npm:
22
+
23
+ ```
24
+ npm install @cloudoperators/juno-k8s-client
25
+ ```
26
+
27
+ With yarn:
28
+
29
+ ```
30
+ yarn add @cloudoperators/juno-k8s-client
31
+ ```
32
+
33
+ # Example Code (ES6)
34
+
35
+ ## List all pods
36
+
37
+ In this code snippet, we use the get method to fetch all pods from the Kubernetes API endpoint. The retrieved data is then logged to the console.
38
+
39
+ ```js
40
+ import { createClient } from "@cloudoperators/juno-k8s-client"
41
+
42
+ const apiEndpoint = "https://k8s-api.com"
43
+ let token = "BEARER-TOKEN"
44
+
45
+ const apiClient = createClient({ apiEndpoint, token })
46
+
47
+ apiClient.get("/api/v1/pods").then((data) => console.log(data))
48
+ ```
49
+
50
+ ## Create a new namespace
51
+
52
+ You can use this example to create a new namespace in the Kubernetes cluster.
53
+
54
+ ```js
55
+ import { createClient } from "@cloudoperators/juno-k8s-client"
56
+
57
+ const apiEndpoint = "https://k8s-api.com"
58
+ let token = "BEARER-TOKEN"
59
+
60
+ const apiClient = createClient({ apiEndpoint, token })
61
+
62
+ apiClient.post("/api/v1/namespaces", {
63
+ apiVersion: "v1",
64
+ kind: "Namespace",
65
+ metadata: {
66
+ name: "my_namespace",
67
+ annotations: { displayName: "My Namespace" },
68
+ labels: { app: "my-app" },
69
+ },
70
+ })
71
+ ```
72
+
73
+ ## Delete a namespace
74
+
75
+ The following example demonstrates how to delete a namespace in the Kubernetes cluster.
76
+
77
+ ```js
78
+ import { createClient } from "@cloudoperators/juno-k8s-client"
79
+
80
+ const apiEndpoint = "https://k8s-api.com"
81
+ let token = "BEARER-TOKEN"
82
+
83
+ const apiClient = createClient({ apiEndpoint, token })
84
+
85
+ apiClient.delete("/api/v1/namespaces/my_namespace")
86
+ ```
87
+
88
+ ## Refresh Token
89
+
90
+ Use this example to refresh the authentication token.
91
+
92
+ ```js
93
+ import { createClient } from "@cloudoperators/juno-k8s-client"
94
+
95
+ const apiEndpoint = "https://k8s-api.com"
96
+ let token = "BEARER-TOKEN"
97
+
98
+ const apiClient = createClient({ apiEndpoint, token })
99
+
100
+ apiClient.refreshToken("NEW-TOKEN")
101
+ ```
102
+
103
+ ### Watch
104
+
105
+ The watch call establishes a persistent connection to the Kubernetes API server and listens for changes to the specified resource. In this example, we're watching for changes to pods ("/api/v1/pods").
106
+
107
+ The watch call should be **explicitly started** using `podsWatch.start()` to begin listening for changes, and it can be **cancelled** using `podsWatch.cancel()` when it's no longer needed.
108
+
109
+ ```javascript
110
+ import { createClient } from "@cloudoperators/juno-k8s-client"
111
+
112
+ const apiEndpoint = "https://k8s-api.com"
113
+ let token = "BEARER-TOKEN"
114
+
115
+ const apiClient = createClient({ apiEndpoint, token })
116
+ const dispatch = (action) => console.log(action)
117
+
118
+ // Initialize the watch call
119
+ const podsWatch = apiClient
120
+ .watch("/api/v1/pods")
121
+ .on(apiClient.WATCH_ERROR, () => console.log("ERROR"))
122
+ .on(apiClient.WATCH_ADDED, (items) => dispatch({ type: "RECEIVE_ITEMS", items }))
123
+ .on(apiClient.WATCH_MODIFIED, (items) => dispatch({ type: "UPDATE_ITEMS", items }))
124
+ .on(apiClient.WATCH_DELETED, (items) => dispatch({ type: "DELETE_ITEMS", items }))
125
+
126
+ // Start the watch call to begin listening for changes
127
+ podsWatch.start()
128
+
129
+ // Optionally, set a timeout to cancel the watch call after a certain period
130
+ setTimeout(podsWatch.cancel, 5 * 60 * 1000) // 5 minutes
131
+ ```
132
+
133
+ # Development
134
+
135
+ All dependencies of this project are expressed in its package.json file. Before you start developing, ensure that you have NPM installed, then run:
136
+
137
+ ```bash
138
+ npm install
139
+ npm run test
140
+ npm run build
141
+ ```
@@ -0,0 +1,240 @@
1
+ function D(r) {
2
+ return typeof r == "string" || r instanceof String;
3
+ }
4
+ function V(r) {
5
+ return typeof r == "number" && r.constructor === Number;
6
+ }
7
+ function F(r) {
8
+ return r !== null && typeof r == "object" && r.constructor === Object;
9
+ }
10
+ const B = (r) => {
11
+ if (!r) return;
12
+ const e = [];
13
+ for (const t in r)
14
+ if (Object.prototype.hasOwnProperty.call(r, t)) {
15
+ const n = r[t];
16
+ e.push(encodeURIComponent(t) + "=" + encodeURIComponent(n));
17
+ }
18
+ return e.join("&");
19
+ };
20
+ function d(...r) {
21
+ if (r.length < 2)
22
+ throw new Error("Bad parameters: buildUrl needs at least two non-empty parameters.");
23
+ const e = F(r[r.length - 1]) ? r.pop() : null;
24
+ r.forEach((i) => {
25
+ if (!i || !(D(i) || V(i)))
26
+ throw new Error(
27
+ "Bad parameters: buildUrl accepts only strings and numbers, with a hash map as the last parameter"
28
+ );
29
+ if (D(i) && i.indexOf("?") >= 0)
30
+ throw new Error(
31
+ 'Bad parameters: buildUrl does not accept strings with "?" character. Please use a hashmap as the last parameter instead!'
32
+ );
33
+ });
34
+ let t = r.join("/");
35
+ const [n, s] = t.split("://");
36
+ if (!n || !s)
37
+ throw new Error(`Bad URL: ${t}`);
38
+ return t = `${n}://${s.replace(/\/\/+/g, "/")}`, e && (t += `?${B(e)}`), t;
39
+ }
40
+ const O = "k8sClient:", j = (r) => function(...e) {
41
+ try {
42
+ const t = [`${O}`, ...e];
43
+ console[r](...t);
44
+ } catch (t) {
45
+ console.error(O, "Logging error:", t);
46
+ }
47
+ }, A = j("error"), h = j("debug"), L = (r) => {
48
+ if (r.status >= 200 && r.status < 300)
49
+ return r;
50
+ {
51
+ const e = new Error(r.statusText || `${r.status}`);
52
+ throw e.response = r, e;
53
+ }
54
+ };
55
+ function l(r, e, t = {}) {
56
+ t.params && (e = d(e, t.params));
57
+ const n = ["signal", "headers", "body", "mode", "cache", "credentials"].reduce(
58
+ (s, i) => (t[i] && (s[i] = t[i]), s),
59
+ { credentials: "same-origin", method: r }
60
+ );
61
+ return n.body && typeof n.body != "string" && (n.body = JSON.stringify(n.body)), h("fetch >", e, n), fetch(e, n).then(L);
62
+ }
63
+ const b = "ADDED", R = "MODIFIED", g = "DELETED", y = "ERROR", X = "BOOKMARK";
64
+ class $ {
65
+ constructor(e, t = {}, n) {
66
+ this.listeners = {
67
+ [b]: [],
68
+ [R]: [],
69
+ [g]: [],
70
+ [y]: []
71
+ }, this.controller = new AbortController(), this.signal = this.controller.signal, this.resourceVersion = null, this.PREFIX = "watch >", this.decoder = new TextDecoder(), this.url = e, this.options = t, this.getCurrentToken = n, t.params && t.params.resourceVersion && (this.resourceVersion = t.params.resourceVersion, delete t.params.resourceVersion);
72
+ }
73
+ refreshToken(e) {
74
+ this.options.headers && (this.options.headers.Authorization = `Bearer ${e}`);
75
+ }
76
+ checkType(e) {
77
+ if (![b, R, g, y].includes(e))
78
+ throw new Error(`Bad type: ${e}`);
79
+ }
80
+ addListener(e, t) {
81
+ this.checkType(e), this.listeners[e].push(t);
82
+ }
83
+ informListeners(e, t) {
84
+ const n = this.listeners[e];
85
+ n && n.forEach((s) => {
86
+ try {
87
+ s(t);
88
+ } catch (i) {
89
+ A(i);
90
+ }
91
+ });
92
+ }
93
+ handleEvents(e) {
94
+ Array.isArray(e) || (e = [e]), setTimeout(() => {
95
+ const t = {};
96
+ e.forEach((n) => {
97
+ n.type === X ? this.resourceVersion = n.object.metadata.resourceVersion : (t[n.type] || (t[n.type] = []), t[n.type].push(n.object));
98
+ }), Object.keys(t).forEach((n) => this.informListeners(n, t[n]));
99
+ });
100
+ }
101
+ async getResourceVersion() {
102
+ if (this.resourceVersion) return this.resourceVersion;
103
+ h(this.PREFIX, "get resource version from API");
104
+ const { metadata: e, items: t } = await l("GET", this.url, this.options).then((n) => n.json());
105
+ return this.resourceVersion = e.resourceVersion, t && this.informListeners(b, t), this.resourceVersion;
106
+ }
107
+ start() {
108
+ return this.getCurrentToken && this.refreshToken(this.getCurrentToken()), this.getResourceVersion().then((e) => (h(this.PREFIX, "current resource version", e), l("GET", this.url, {
109
+ ...this.options,
110
+ params: {
111
+ ...this.options.params,
112
+ watch: 1,
113
+ allowWatchBookmarks: !0,
114
+ resourceVersion: e
115
+ },
116
+ signal: this.signal
117
+ }))).then(async (e) => {
118
+ var i;
119
+ const t = (i = e.body) == null ? void 0 : i.getReader();
120
+ let n = !1, s = "";
121
+ for (; !n; ) {
122
+ h(this.PREFIX, "read stream chunk");
123
+ const u = await (t == null ? void 0 : t.read());
124
+ n = (u == null ? void 0 : u.done) ?? !0, s += this.decoder.decode((u == null ? void 0 : u.value) || new Uint8Array());
125
+ const E = s.split(/\n|\r|\r\n/);
126
+ s = E.pop() || "";
127
+ const T = [];
128
+ E.forEach((w) => {
129
+ const m = JSON.parse(w);
130
+ if (m.type === y && m.object.code === 410) {
131
+ this.cancel(), setTimeout(() => {
132
+ h(this.PREFIX, "resource is gone 410", "recreate watch request!"), this.start();
133
+ });
134
+ return;
135
+ }
136
+ T.push(m);
137
+ }), h(this.PREFIX, "inform listeners", E), this.handleEvents(T);
138
+ }
139
+ }).catch((e) => {
140
+ if (e.name === "AbortError") return;
141
+ const t = e.code || e.response && e.response.status;
142
+ if (t === 410) {
143
+ h(this.PREFIX, "resource is gone 410"), this.resourceVersion = null, setTimeout(() => this.start(), 0);
144
+ return;
145
+ }
146
+ if ([404].includes(t)) {
147
+ this.handleEvents({ type: y, object: e }), this.cancel();
148
+ return;
149
+ }
150
+ A("WATCH ERROR", e, e.code, t, e.response), console.dir(e), setTimeout(() => {
151
+ h(this.PREFIX, "recover connection", "restart!"), this.start();
152
+ }, 3e4);
153
+ }), this.cancel;
154
+ }
155
+ on(e, t) {
156
+ return this.addListener(e, t), this;
157
+ }
158
+ cancel() {
159
+ h(this.PREFIX, "cancel connection"), this.controller.abort();
160
+ }
161
+ }
162
+ const p = async (r) => {
163
+ var t;
164
+ const e = (t = r.response) != null && t.data ? new Error(r.response.data.message || r.message) : r;
165
+ return Promise.reject(e);
166
+ };
167
+ function H(r) {
168
+ const { apiEndpoint: e } = r;
169
+ let t = r.token;
170
+ if (!e || !t)
171
+ throw new Error(`Bad options: ${JSON.stringify(r, null, 4)}. Please provide apiEndpoint and token`);
172
+ const n = () => ({
173
+ Authorization: `Bearer ${t}`,
174
+ "Content-Type": "application/json"
175
+ });
176
+ function s(o, c = {}) {
177
+ const a = {
178
+ ...n(),
179
+ ...c.headers,
180
+ ...o.headers
181
+ };
182
+ return {
183
+ ...c,
184
+ ...o,
185
+ headers: a
186
+ };
187
+ }
188
+ function i(o, c = {}) {
189
+ return l("HEAD", d(e, o), s(c)).catch(p);
190
+ }
191
+ function u(o, c = {}) {
192
+ return l("GET", d(e, o), s(c)).then((a) => a.json()).catch(p);
193
+ }
194
+ function E(o, c, a = {}) {
195
+ return l("POST", d(e, o), s(a, { body: c })).then((C) => C.json()).catch(p);
196
+ }
197
+ function T(o, c, a = {}) {
198
+ return l("PUT", d(e, o), s(a, { body: c })).then((f) => f.json()).catch(p);
199
+ }
200
+ function w(o, c, a = {}) {
201
+ return l(
202
+ "PATCH",
203
+ d(e, o),
204
+ s(a, {
205
+ headers: { "Content-Type": "application/merge-patch+json" },
206
+ body: c
207
+ })
208
+ ).then((f) => f.json()).catch(p);
209
+ }
210
+ function m(o, c, a = {}) {
211
+ return l("DELETE", d(e, o), s(a, { body: c })).then((f) => f.json()).catch(p);
212
+ }
213
+ function I(o, c = {}) {
214
+ return new $(d(e, o), s(c), () => t);
215
+ }
216
+ function P(o) {
217
+ t = o;
218
+ }
219
+ function k() {
220
+ return t;
221
+ }
222
+ return {
223
+ WATCH_ERROR: y,
224
+ WATCH_ADDED: b,
225
+ WATCH_DELETED: g,
226
+ WATCH_MODIFIED: R,
227
+ head: i,
228
+ get: u,
229
+ post: E,
230
+ put: T,
231
+ patch: w,
232
+ delete: m,
233
+ watch: I,
234
+ refreshToken: P,
235
+ currentToken: k
236
+ };
237
+ }
238
+ export {
239
+ H as createClient
240
+ };
@@ -0,0 +1,10 @@
1
+ interface ApiErrorType extends Error {
2
+ response?: {
3
+ data?: {
4
+ message?: string;
5
+ };
6
+ };
7
+ }
8
+ declare const apiErrorHandler: (apiError: ApiErrorType) => Promise<never>;
9
+ export default apiErrorHandler;
10
+ //# sourceMappingURL=apiErrorHandler.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"apiErrorHandler.d.ts","sourceRoot":"","sources":["../../src/apiErrorHandler.ts"],"names":[],"mappings":"AAAA,UAAU,YAAa,SAAQ,KAAK;IAClC,QAAQ,CAAC,EAAE;QACT,IAAI,CAAC,EAAE;YAAE,OAAO,CAAC,EAAE,MAAM,CAAA;SAAE,CAAA;KAC5B,CAAA;CACF;AACD,QAAA,MAAM,eAAe,aAAoB,YAAY,KAAG,OAAO,CAAC,KAAK,CAIpE,CAAA;AAED,eAAe,eAAe,CAAA"}
@@ -0,0 +1,32 @@
1
+ import { Watch } from './watch';
2
+ interface ClientOptions {
3
+ apiEndpoint: string;
4
+ token: string;
5
+ [key: string]: any;
6
+ }
7
+ interface RequestOptions {
8
+ params?: Record<string, any>;
9
+ headers?: Record<string, string>;
10
+ body?: any;
11
+ signal?: AbortSignal;
12
+ mode?: RequestMode;
13
+ cache?: RequestCache;
14
+ credentials?: RequestCredentials;
15
+ }
16
+ declare function createClient(options: ClientOptions): {
17
+ WATCH_ERROR: string;
18
+ WATCH_ADDED: string;
19
+ WATCH_DELETED: string;
20
+ WATCH_MODIFIED: string;
21
+ head: (path: string, options?: RequestOptions) => Promise<Response>;
22
+ get: (path: string, options?: RequestOptions) => Promise<any>;
23
+ post: (path: string, data: {}, options?: RequestOptions) => Promise<any>;
24
+ put: (path: string, data: {}, options?: RequestOptions) => Promise<any>;
25
+ patch: (path: string, data: {}, options?: RequestOptions) => Promise<any>;
26
+ delete: (path: string, data?: {} | null, options?: RequestOptions) => Promise<any>;
27
+ watch: (path: string, options?: RequestOptions) => Watch;
28
+ refreshToken: (newToken: string) => void;
29
+ currentToken: () => string;
30
+ };
31
+ export { createClient };
32
+ //# sourceMappingURL=client.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"client.d.ts","sourceRoot":"","sources":["../../src/client.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,KAAK,EAAmC,MAAM,SAAS,CAAA;AAGhE,UAAU,aAAa;IACrB,WAAW,EAAE,MAAM,CAAA;IACnB,KAAK,EAAE,MAAM,CAAA;IACb,CAAC,GAAG,EAAE,MAAM,GAAG,GAAG,CAAA;CACnB;AAED,UAAU,cAAc;IACtB,MAAM,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,CAAA;IAC5B,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAA;IAChC,IAAI,CAAC,EAAE,GAAG,CAAA;IACV,MAAM,CAAC,EAAE,WAAW,CAAA;IACpB,IAAI,CAAC,EAAE,WAAW,CAAA;IAClB,KAAK,CAAC,EAAE,YAAY,CAAA;IACpB,WAAW,CAAC,EAAE,kBAAkB,CAAA;CACjC;AAED,iBAAS,YAAY,CAAC,OAAO,EAAE,aAAa;;;;;iBA2BtB,MAAM,YAAW,cAAc,KAAQ,OAAO,CAAC,QAAQ,CAAC;gBAIzD,MAAM,YAAW,cAAc,KAAQ,OAAO,CAAC,GAAG,CAAC;iBAMlD,MAAM,QAAQ,EAAE,YAAW,cAAc,KAAQ,OAAO,CAAC,GAAG,CAAC;gBAO9D,MAAM,QAAQ,EAAE,YAAW,cAAc,KAAQ,OAAO,CAAC,GAAG,CAAC;kBAM3D,MAAM,QAAQ,EAAE,YAAW,cAAc,KAAQ,OAAO,CAAC,GAAG,CAAC;mBAa/D,MAAM,SAAS,EAAE,GAAG,IAAI,YAAW,cAAc,KAAQ,OAAO,CAAC,GAAG,CAAC;kBAMnE,MAAM,YAAW,cAAc,KAAQ,KAAK;6BAIjC,MAAM,KAAG,IAAI;wBAIpB,MAAM;EAmBhC;AAED,OAAO,EAAE,YAAY,EAAE,CAAA"}
@@ -0,0 +1,2 @@
1
+ export { createClient } from './client';
2
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,YAAY,EAAE,MAAM,UAAU,CAAA"}
@@ -0,0 +1,5 @@
1
+ export declare const log: (...args: unknown[]) => void;
2
+ export declare const error: (...args: unknown[]) => void;
3
+ export declare const debug: (...args: unknown[]) => void;
4
+ export declare const info: (...args: unknown[]) => void;
5
+ //# sourceMappingURL=logger.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"logger.d.ts","sourceRoot":"","sources":["../../src/logger.ts"],"names":[],"mappings":"AAmBA,eAAO,MAAM,GAAG,YAVY,OAAO,EAAE,SAUA,CAAA;AACrC,eAAO,MAAM,KAAK,YAXU,OAAO,EAAE,SAWI,CAAA;AACzC,eAAO,MAAM,KAAK,YAZU,OAAO,EAAE,SAYI,CAAA;AACzC,eAAO,MAAM,IAAI,YAbW,OAAO,EAAE,SAaE,CAAA"}
@@ -0,0 +1,20 @@
1
+ interface RequestOptions {
2
+ params?: Record<string, any>;
3
+ signal?: AbortSignal;
4
+ headers?: HeadersInit;
5
+ body?: any;
6
+ mode?: RequestMode;
7
+ cache?: RequestCache;
8
+ credentials?: RequestCredentials;
9
+ }
10
+ /**
11
+ * Creates a request.
12
+ *
13
+ * @param {string} method Http method.
14
+ * @param {string} url The URL to send the request to.
15
+ * @param {RequestOptions} options params, headers, and other options supported by fetch.
16
+ * @return {Promise<Response>} The response promise.
17
+ */
18
+ declare function request(method: string, url: string, options?: RequestOptions): Promise<Response>;
19
+ export default request;
20
+ //# sourceMappingURL=request.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"request.d.ts","sourceRoot":"","sources":["../../src/request.ts"],"names":[],"mappings":"AAIA,UAAU,cAAc;IACtB,MAAM,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,CAAA;IAC5B,MAAM,CAAC,EAAE,WAAW,CAAA;IACpB,OAAO,CAAC,EAAE,WAAW,CAAA;IACrB,IAAI,CAAC,EAAE,GAAG,CAAA;IACV,IAAI,CAAC,EAAE,WAAW,CAAA;IAClB,KAAK,CAAC,EAAE,YAAY,CAAA;IACpB,WAAW,CAAC,EAAE,kBAAkB,CAAA;CACjC;AAaD;;;;;;;GAOG;AACH,iBAAS,OAAO,CAAC,MAAM,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,EAAE,OAAO,GAAE,cAAmB,GAAG,OAAO,CAAC,QAAQ,CAAC,CAwB7F;AAED,eAAe,OAAO,CAAA"}
@@ -0,0 +1,9 @@
1
+ /**
2
+ * Builds a URL from all path parts passed to the function.
3
+ * @param {...(string | number)} path - A part of the URL.
4
+ * @param {Record<string, any>} params - Params, headers, and other options supported by fetch.
5
+ * @return {string}
6
+ */
7
+ declare function buildUrl(...args: (string | number | Record<string, any>)[]): string;
8
+ export { buildUrl };
9
+ //# sourceMappingURL=urlHelpers.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"urlHelpers.d.ts","sourceRoot":"","sources":["../../src/urlHelpers.ts"],"names":[],"mappings":"AAoBA;;;;;GAKG;AACH,iBAAS,QAAQ,CAAC,GAAG,IAAI,EAAE,CAAC,MAAM,GAAG,MAAM,GAAG,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC,EAAE,GAAG,MAAM,CAmC5E;AAED,OAAO,EAAE,QAAQ,EAAE,CAAA"}
@@ -0,0 +1,44 @@
1
+ /**
2
+ * Returns true if a value is a string
3
+ * @param {any} value value to be tested
4
+ * @return {boolean} true or false
5
+ */
6
+ declare function isString(value: any): value is string;
7
+ /**
8
+ * Returns true if a value is a number
9
+ * @param {any} value value to be tested
10
+ * @return {boolean} true or false
11
+ */
12
+ declare function isNumber(value: any): value is number;
13
+ /**
14
+ * Returns true if a value is an object
15
+ * @param {any} value value to be tested
16
+ * @return {boolean} true or false
17
+ */
18
+ declare function isObject<T>(value: T): boolean;
19
+ /**
20
+ * Returns true if a value is an array
21
+ * @param {any} value value to be tested
22
+ * @return {boolean} true or false
23
+ */
24
+ declare function isArray(value: any): value is any[];
25
+ /**
26
+ * Returns true if a value is a function
27
+ * @param {any} value value to be tested
28
+ * @return {boolean} true or false
29
+ */
30
+ declare function isFunction(value: any): value is Function;
31
+ /**
32
+ * Returns true if a value is null
33
+ * @param {any} value value to be tested
34
+ * @return {boolean} true or false
35
+ */
36
+ declare function isNull(value: any): value is null;
37
+ /**
38
+ * Returns true if a value is undefined
39
+ * @param {any} value value to be tested
40
+ * @return {boolean} true or false
41
+ */
42
+ declare function isUndefined(value: any): value is undefined;
43
+ export { isString, isNumber, isObject, isArray, isFunction, isNull, isUndefined };
44
+ //# sourceMappingURL=utils.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"utils.d.ts","sourceRoot":"","sources":["../../src/utils.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,iBAAS,QAAQ,CAAC,KAAK,EAAE,GAAG,GAAG,KAAK,IAAI,MAAM,CAE7C;AAED;;;;GAIG;AACH,iBAAS,QAAQ,CAAC,KAAK,EAAE,GAAG,GAAG,KAAK,IAAI,MAAM,CAE7C;AAED;;;;GAIG;AACH,iBAAS,QAAQ,CAAC,CAAC,EAAE,KAAK,EAAE,CAAC,GAAG,OAAO,CAEtC;AAED;;;;GAIG;AACH,iBAAS,OAAO,CAAC,KAAK,EAAE,GAAG,GAAG,KAAK,IAAI,GAAG,EAAE,CAE3C;AAED;;;;GAIG;AACH,iBAAS,UAAU,CAAC,KAAK,EAAE,GAAG,GAAG,KAAK,IAAI,QAAQ,CAEjD;AAED;;;;GAIG;AACH,iBAAS,MAAM,CAAC,KAAK,EAAE,GAAG,GAAG,KAAK,IAAI,IAAI,CAEzC;AAED;;;;GAIG;AACH,iBAAS,WAAW,CAAC,KAAK,EAAE,GAAG,GAAG,KAAK,IAAI,SAAS,CAEnD;AAED,OAAO,EAAE,QAAQ,EAAE,QAAQ,EAAE,QAAQ,EAAE,OAAO,EAAE,UAAU,EAAE,MAAM,EAAE,WAAW,EAAE,CAAA"}
@@ -0,0 +1,37 @@
1
+ declare const ADDED = "ADDED";
2
+ declare const MODIFIED = "MODIFIED";
3
+ declare const DELETED = "DELETED";
4
+ declare const ERROR = "ERROR";
5
+ type Listener = (_items: any) => void;
6
+ interface WatchOptions {
7
+ params?: Record<string, any>;
8
+ headers?: Record<string, string>;
9
+ signal?: AbortSignal;
10
+ body?: any;
11
+ mode?: RequestMode;
12
+ cache?: RequestCache;
13
+ credentials?: RequestCredentials;
14
+ }
15
+ declare class Watch {
16
+ private listeners;
17
+ private controller;
18
+ private signal;
19
+ private resourceVersion;
20
+ private PREFIX;
21
+ private decoder;
22
+ private url;
23
+ private options;
24
+ private getCurrentToken?;
25
+ constructor(url: string, options?: WatchOptions, getCurrentToken?: () => string);
26
+ refreshToken(newToken: string): void;
27
+ private checkType;
28
+ private addListener;
29
+ private informListeners;
30
+ private handleEvents;
31
+ private getResourceVersion;
32
+ start(): () => void;
33
+ on(type: string, listener: Listener): this;
34
+ cancel(): void;
35
+ }
36
+ export { ADDED, MODIFIED, DELETED, ERROR, Watch };
37
+ //# sourceMappingURL=watch.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"watch.d.ts","sourceRoot":"","sources":["../../src/watch.ts"],"names":[],"mappings":"AAGA,QAAA,MAAM,KAAK,UAAU,CAAA;AACrB,QAAA,MAAM,QAAQ,aAAa,CAAA;AAC3B,QAAA,MAAM,OAAO,YAAY,CAAA;AACzB,QAAA,MAAM,KAAK,UAAU,CAAA;AAGrB,KAAK,QAAQ,GAAG,CAAC,MAAM,EAAE,GAAG,KAAK,IAAI,CAAA;AAErC,UAAU,YAAY;IACpB,MAAM,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,CAAA;IAC5B,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAA;IAChC,MAAM,CAAC,EAAE,WAAW,CAAA;IACpB,IAAI,CAAC,EAAE,GAAG,CAAA;IACV,IAAI,CAAC,EAAE,WAAW,CAAA;IAClB,KAAK,CAAC,EAAE,YAAY,CAAA;IACpB,WAAW,CAAC,EAAE,kBAAkB,CAAA;CACjC;AAED,cAAM,KAAK;IACT,OAAO,CAAC,SAAS,CAKhB;IACD,OAAO,CAAC,UAAU,CAAyC;IAC3D,OAAO,CAAC,MAAM,CAAsC;IACpD,OAAO,CAAC,eAAe,CAAsB;IAC7C,OAAO,CAAC,MAAM,CAAY;IAC1B,OAAO,CAAC,OAAO,CAAoB;IACnC,OAAO,CAAC,GAAG,CAAQ;IACnB,OAAO,CAAC,OAAO,CAAc;IAC7B,OAAO,CAAC,eAAe,CAAC,CAAc;gBAE1B,GAAG,EAAE,MAAM,EAAE,OAAO,GAAE,YAAiB,EAAE,eAAe,CAAC,EAAE,MAAM,MAAM;IAYnF,YAAY,CAAC,QAAQ,EAAE,MAAM;IAM7B,OAAO,CAAC,SAAS;IAMjB,OAAO,CAAC,WAAW;IAKnB,OAAO,CAAC,eAAe;IAcvB,OAAO,CAAC,YAAY;YAqBN,kBAAkB;IAYhC,KAAK;IAgFL,EAAE,CAAC,IAAI,EAAE,MAAM,EAAE,QAAQ,EAAE,QAAQ;IAKnC,MAAM;CAIP;AAED,OAAO,EAAE,KAAK,EAAE,QAAQ,EAAE,OAAO,EAAE,KAAK,EAAE,KAAK,EAAE,CAAA"}
package/package.json ADDED
@@ -0,0 +1,35 @@
1
+ {
2
+ "name": "@cloudoperators/juno-k8s-client",
3
+ "version": "1.0.0",
4
+ "author": "UI-Team",
5
+ "description": "JavaScript client for Kubernetes API",
6
+ "main": "build/k8s-client.es.js",
7
+ "module": "build/k8s-client.es.js",
8
+ "types": "build/types/index.d.ts",
9
+ "files": [
10
+ "build/**",
11
+ "LICENCE"
12
+ ],
13
+ "type": "module",
14
+ "scripts": {
15
+ "test": "vitest run",
16
+ "lint": "eslint",
17
+ "typecheck": "tsc --noEmit",
18
+ "dev": "vite",
19
+ "build": "vite build",
20
+ "serve": "vite preview",
21
+ "clean": "rm -rf build && rm -rf node_modules && rm -rf .turbo"
22
+ },
23
+ "keywords": [
24
+ "kubernetes",
25
+ "js",
26
+ "typescript",
27
+ "client"
28
+ ],
29
+ "devDependencies": {
30
+ "@cloudoperators/juno-eslint-config": "*",
31
+ "@cloudoperators/juno-typescript-config": "*",
32
+ "vite": "^5.4.0",
33
+ "vite-plugin-dts": "^4.0.3"
34
+ }
35
+ }