@cloudoperators/juno-k8s-client 1.0.7 → 1.1.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/README.md CHANGED
@@ -1,10 +1,10 @@
1
1
  # JavaScript client for Kubernetes API
2
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.
3
+ This `Kubernetes client` is designed for use in both browser and Node.js environments. It utilizes the fetch API and is compatible with all modern browsers. For older browsers, the fetch polyfill (github/fetch) should be used.
4
4
 
5
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
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.
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 and will be of type `K8sApiError`.
8
8
 
9
9
  The client requires a Kubernetes API endpoint and a token. Once both parameters are provided, the following functions are available:
10
10
 
@@ -36,8 +36,84 @@ With yarn:
36
36
  yarn add @cloudoperators/juno-k8s-client
37
37
  ```
38
38
 
39
+ # Configuration Options
40
+
41
+ When creating a client, you can pass the following options:
42
+
43
+ | Option | Type | Required | Description |
44
+ | ------------- | ------- | -------- | --------------------------------------------------- |
45
+ | `apiEndpoint` | string | Yes | The Kubernetes API server endpoint |
46
+ | `token` | string | Yes | Bearer token for authentication |
47
+ | `ignoreSsl` | boolean | No | Ignore SSL certificate verification (Node.js only) |
48
+ | `debug` | boolean | No | Enable debug logging for API requests and responses |
49
+
50
+ ## SSL Certificate Handling
51
+
52
+ The `ignoreSsl` option allows you to bypass SSL certificate verification when connecting to Kubernetes APIs with self-signed or invalid certificates.
53
+
54
+ **⚠️ Security Warning**: Only use `ignoreSsl: true` in development environments or with trusted internal APIs. Never disable SSL verification in production.
55
+
56
+ **Browser Limitation**: The `ignoreSsl` option is only supported in Node.js environments. In browser environments, this option is ignored for security reasons, as browsers handle SSL certificate validation automatically.
57
+
58
+ ```js
59
+ import { createClient } from "@cloudoperators/juno-k8s-client"
60
+
61
+ // For internal/development APIs with self-signed certificates (Node.js only)
62
+ const apiClient = createClient({
63
+ apiEndpoint: "https://internal-k8s-api.company.com",
64
+ token: "BEARER-TOKEN",
65
+ ignoreSsl: true, // Only works in Node.js
66
+ })
67
+ ```
68
+
69
+ # Error Handling
70
+
71
+ All API errors thrown by this client implement the `K8sApiError` interface:
72
+
73
+ ```typescript
74
+ interface K8sApiError extends Error {
75
+ apiVersion?: string
76
+ kind?: string
77
+ message: string
78
+ metadata?: Record<string, any>
79
+ reason?: string
80
+ status?: string
81
+ code?: number
82
+ response?: {
83
+ data?: { message?: string }
84
+ status?: number
85
+ }
86
+ }
87
+ ```
88
+
89
+ This provides detailed information about Kubernetes API errors, including status codes, reasons, and additional metadata.
90
+
39
91
  # Example Code (ES6)
40
92
 
93
+ ## Basic client creation
94
+
95
+ ```js
96
+ import { createClient } from "@cloudoperators/juno-k8s-client"
97
+
98
+ const apiEndpoint = "https://k8s-api.com"
99
+ let token = "BEARER-TOKEN"
100
+ const apiClient = createClient({ apiEndpoint, token })
101
+ ```
102
+
103
+ ## Client with SSL ignore (Node.js only)
104
+
105
+ ```js
106
+ import { createClient } from "@cloudoperators/juno-k8s-client"
107
+
108
+ const apiEndpoint = "https://internal-k8s-api.company.com"
109
+ let token = "BEARER-TOKEN"
110
+ const apiClient = createClient({
111
+ apiEndpoint,
112
+ token,
113
+ ignoreSsl: true, // For internal APIs with self-signed certificates
114
+ })
115
+ ```
116
+
41
117
  ## List all pods
42
118
 
43
119
  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.
@@ -47,10 +123,46 @@ import { createClient } from "@cloudoperators/juno-k8s-client"
47
123
 
48
124
  const apiEndpoint = "https://k8s-api.com"
49
125
  let token = "BEARER-TOKEN"
126
+ const apiClient = createClient({ apiEndpoint, token })
127
+
128
+ apiClient
129
+ .get("/api/v1/pods")
130
+ .then((data) => console.log(data))
131
+ .catch((error) => {
132
+ console.error("Failed to fetch pods:", error.message)
133
+ console.error("Status:", error.status)
134
+ console.error("Reason:", error.reason)
135
+ console.error("HTTP Code:", error.code)
136
+ })
137
+ ```
50
138
 
139
+ ## List pods with query parameters
140
+
141
+ ```js
142
+ import { createClient } from "@cloudoperators/juno-k8s-client"
143
+
144
+ const apiEndpoint = "https://k8s-api.com"
145
+ let token = "BEARER-TOKEN"
51
146
  const apiClient = createClient({ apiEndpoint, token })
52
147
 
53
- apiClient.get("/api/v1/pods").then((data) => console.log(data))
148
+ // Get pods with label selector
149
+ apiClient
150
+ .get("/api/v1/namespaces/default/pods", {
151
+ params: {
152
+ labelSelector: "app=nginx",
153
+ fieldSelector: "status.phase=Running",
154
+ },
155
+ })
156
+ .then((data) => console.log(data))
157
+ .catch((error) => {
158
+ if (error.code === 403) {
159
+ console.error("Access forbidden:", error.reason)
160
+ } else if (error.code === 404) {
161
+ console.error("Namespace not found:", error.message)
162
+ } else {
163
+ console.error("API Error:", error.message)
164
+ }
165
+ })
54
166
  ```
55
167
 
56
168
  ## Create a new namespace
@@ -62,18 +174,28 @@ import { createClient } from "@cloudoperators/juno-k8s-client"
62
174
 
63
175
  const apiEndpoint = "https://k8s-api.com"
64
176
  let token = "BEARER-TOKEN"
65
-
66
177
  const apiClient = createClient({ apiEndpoint, token })
67
178
 
68
- apiClient.post("/api/v1/namespaces", {
69
- apiVersion: "v1",
70
- kind: "Namespace",
71
- metadata: {
72
- name: "my_namespace",
73
- annotations: { displayName: "My Namespace" },
74
- labels: { app: "my-app" },
75
- },
76
- })
179
+ apiClient
180
+ .post("/api/v1/namespaces", {
181
+ apiVersion: "v1",
182
+ kind: "Namespace",
183
+ metadata: {
184
+ name: "my_namespace",
185
+ annotations: { displayName: "My Namespace" },
186
+ labels: { app: "my-app" },
187
+ },
188
+ })
189
+ .then((result) => console.log("Namespace created:", result))
190
+ .catch((error) => {
191
+ if (error.reason === "AlreadyExists") {
192
+ console.error("Namespace already exists:", error.message)
193
+ } else if (error.code === 422) {
194
+ console.error("Invalid namespace configuration:", error.message)
195
+ } else {
196
+ console.error("Failed to create namespace:", error.message)
197
+ }
198
+ })
77
199
  ```
78
200
 
79
201
  ## Delete a namespace
@@ -85,10 +207,50 @@ import { createClient } from "@cloudoperators/juno-k8s-client"
85
207
 
86
208
  const apiEndpoint = "https://k8s-api.com"
87
209
  let token = "BEARER-TOKEN"
88
-
89
210
  const apiClient = createClient({ apiEndpoint, token })
90
211
 
91
- apiClient.delete("/api/v1/namespaces/my_namespace")
212
+ apiClient
213
+ .delete("/api/v1/namespaces/my_namespace")
214
+ .then((result) => console.log("Namespace deleted:", result))
215
+ .catch((error) => {
216
+ if (error.code === 404) {
217
+ console.error("Namespace not found:", error.message)
218
+ } else if (error.reason === "Forbidden") {
219
+ console.error("Insufficient permissions to delete namespace:", error.message)
220
+ } else {
221
+ console.error("Failed to delete namespace:", error.message)
222
+ console.error("Error details:", error.metadata)
223
+ }
224
+ })
225
+ ```
226
+
227
+ ## Per-request SSL override (Node.js only)
228
+
229
+ You can also override SSL behavior on a per-request basis:
230
+
231
+ ```js
232
+ import { createClient } from "@cloudoperators/juno-k8s-client"
233
+
234
+ const apiEndpoint = "https://k8s-api.com"
235
+ let token = "BEARER-TOKEN"
236
+
237
+ // Client with SSL verification enabled by default
238
+ const apiClient = createClient({ apiEndpoint, token, ignoreSsl: false })
239
+
240
+ // Most requests use SSL verification
241
+ apiClient.get("/api/v1/pods")
242
+
243
+ // But you can override for specific requests (Node.js only)
244
+ apiClient
245
+ .get("/api/v1/secrets", {
246
+ ignoreSsl: true, // This request ignores SSL
247
+ })
248
+ .catch((error) => {
249
+ console.error("Failed to fetch secrets:", error.message)
250
+ if (error.response?.status) {
251
+ console.error("HTTP Status:", error.response.status)
252
+ }
253
+ })
92
254
  ```
93
255
 
94
256
  ## Refresh Token
@@ -100,13 +262,17 @@ import { createClient } from "@cloudoperators/juno-k8s-client"
100
262
 
101
263
  const apiEndpoint = "https://k8s-api.com"
102
264
  let token = "BEARER-TOKEN"
103
-
104
265
  const apiClient = createClient({ apiEndpoint, token })
105
266
 
106
- apiClient.refreshToken("NEW-TOKEN")
267
+ try {
268
+ apiClient.refreshToken("NEW-TOKEN")
269
+ console.log("Token refreshed successfully")
270
+ } catch (error) {
271
+ console.error("Failed to refresh token:", error.message)
272
+ }
107
273
  ```
108
274
 
109
- ### Watch
275
+ ## Watch
110
276
 
111
277
  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").
112
278
 
@@ -117,14 +283,27 @@ import { createClient } from "@cloudoperators/juno-k8s-client"
117
283
 
118
284
  const apiEndpoint = "https://k8s-api.com"
119
285
  let token = "BEARER-TOKEN"
120
-
121
286
  const apiClient = createClient({ apiEndpoint, token })
287
+
122
288
  const dispatch = (action) => console.log(action)
123
289
 
124
290
  // Initialize the watch call
125
291
  const podsWatch = apiClient
126
292
  .watch("/api/v1/pods")
127
- .on(apiClient.WATCH_ERROR, () => console.log("ERROR"))
293
+ .on(apiClient.WATCH_ERROR, (error) => {
294
+ console.error("Watch error occurred:", error.message)
295
+ console.error("Error reason:", error.reason)
296
+ console.error("Error code:", error.code)
297
+
298
+ // Handle specific error cases
299
+ if (error.code === 401) {
300
+ console.error("Authentication failed - token may be expired")
301
+ } else if (error.code === 403) {
302
+ console.error("Access forbidden - insufficient permissions")
303
+ } else if (error.reason === "Expired") {
304
+ console.error("Watch session expired - consider restarting")
305
+ }
306
+ })
128
307
  .on(apiClient.WATCH_ADDED, (items) => dispatch({ type: "RECEIVE_ITEMS", items }))
129
308
  .on(apiClient.WATCH_MODIFIED, (items) => dispatch({ type: "UPDATE_ITEMS", items }))
130
309
  .on(apiClient.WATCH_DELETED, (items) => dispatch({ type: "DELETE_ITEMS", items }))
@@ -136,6 +315,125 @@ podsWatch.start()
136
315
  setTimeout(podsWatch.cancel, 5 * 60 * 1000) // 5 minutes
137
316
  ```
138
317
 
318
+ ## Watch with SSL ignore (Node.js only)
319
+
320
+ ```javascript
321
+ import { createClient } from "@cloudoperators/juno-k8s-client"
322
+
323
+ const apiEndpoint = "https://internal-k8s-api.company.com"
324
+ let token = "BEARER-TOKEN"
325
+ const apiClient = createClient({
326
+ apiEndpoint,
327
+ token,
328
+ ignoreSsl: true, // For internal APIs
329
+ })
330
+
331
+ const podsWatch = apiClient
332
+ .watch("/api/v1/pods", {
333
+ params: { watch: "true" },
334
+ ignoreSsl: true, // Can also be set per-request
335
+ })
336
+ .on(apiClient.WATCH_ERROR, (error) => {
337
+ console.error("Watch connection failed:", error.message)
338
+ if (error.response?.data?.message) {
339
+ console.error("Server message:", error.response.data.message)
340
+ }
341
+ })
342
+ .on(apiClient.WATCH_ADDED, (items) => console.log("Added:", items))
343
+
344
+ podsWatch.start()
345
+ ```
346
+
347
+ # Common Use Cases
348
+
349
+ ## Internal Kubernetes Clusters
350
+
351
+ For internal clusters with self-signed certificates (Node.js environments):
352
+
353
+ ```js
354
+ const apiClient = createClient({
355
+ apiEndpoint: "https://rancher.internal.company.com/k8s/clusters/c-12345",
356
+ token: process.env.K8S_TOKEN,
357
+ ignoreSsl: true, // Safe for internal networks
358
+ })
359
+
360
+ // Example with error handling for internal clusters
361
+ apiClient
362
+ .get("/api/v1/nodes")
363
+ .then((nodes) => console.log("Cluster nodes:", nodes))
364
+ .catch((error) => {
365
+ console.error("Failed to connect to internal cluster:", error.message)
366
+ if (error.code === 0 || error.message.includes("ECONNREFUSED")) {
367
+ console.error("Network connectivity issue - check VPN or firewall")
368
+ }
369
+ })
370
+ ```
371
+
372
+ ## Development Environment
373
+
374
+ ```js
375
+ const apiClient = createClient({
376
+ apiEndpoint: "https://localhost:6443",
377
+ token: "dev-token",
378
+ ignoreSsl: process.env.NODE_ENV === "development", // Only in development
379
+ })
380
+
381
+ // Development-specific error handling
382
+ apiClient.get("/api/v1/namespaces").catch((error) => {
383
+ if (process.env.NODE_ENV === "development") {
384
+ console.warn("Development API error:", error.message)
385
+ console.warn("This might be expected in dev environment")
386
+ } else {
387
+ console.error("Production API error:", error)
388
+ }
389
+ })
390
+ ```
391
+
392
+ ## Production Environment
393
+
394
+ ```js
395
+ const apiClient = createClient({
396
+ apiEndpoint: "https://prod-k8s-api.company.com",
397
+ token: process.env.K8S_TOKEN,
398
+ // ignoreSsl should not be used in production
399
+ })
400
+
401
+ // Production error handling with monitoring
402
+ apiClient.get("/api/v1/pods").catch((error) => {
403
+ // Log detailed error information for monitoring
404
+ console.error("Production API Error:", {
405
+ message: error.message,
406
+ status: error.status,
407
+ reason: error.reason,
408
+ code: error.code,
409
+ apiVersion: error.apiVersion,
410
+ kind: error.kind,
411
+ timestamp: new Date().toISOString(),
412
+ })
413
+
414
+ // Send to monitoring service
415
+ // monitoringService.reportError(error)
416
+ })
417
+ ```
418
+
419
+ # Environment Support
420
+
421
+ ## Browser Environment
422
+
423
+ - ✅ Full HTTP methods support (GET, POST, PUT, PATCH, DELETE, HEAD)
424
+ - ✅ Watch functionality
425
+ - ✅ Token refresh
426
+ - ✅ Complete error handling with `K8sApiError`
427
+ - ❌ `ignoreSsl` option (ignored for security reasons)
428
+
429
+ ## Node.js Environment
430
+
431
+ - ✅ Full HTTP methods support
432
+ - ✅ Watch functionality
433
+ - ✅ Token refresh
434
+ - ✅ Complete error handling with `K8sApiError`
435
+ - ✅ `ignoreSsl` option with HTTPS agent support
436
+
139
437
  # Development
140
438
 
141
439
  All dependencies of this project are expressed in its package.json file. Before you start developing, ensure that you have NPM installed, then run:
@@ -145,3 +443,11 @@ pnpm install
145
443
  pnpm test
146
444
  pnpm build
147
445
  ```
446
+
447
+ ## Contributing
448
+
449
+ We welcome contributions from the community. Please follow our [contribution guidelines](https://github.com/cloudoperators/juno/blob/main/CONTRIBUTING.md) to contribute to this project.
450
+
451
+ ## License
452
+
453
+ Licensed under the [Apache License](LICENSE).
package/build/client.d.ts CHANGED
@@ -1,19 +1,13 @@
1
+ import { RequestOptions } from './request';
1
2
  import { Watch } from './watch';
2
3
  import { K8sApiError } from './apiErrorHandler';
3
4
  interface ClientOptions {
4
5
  apiEndpoint: string;
5
6
  token: string;
7
+ ignoreSsl?: boolean;
8
+ debug?: boolean;
6
9
  [key: string]: any;
7
10
  }
8
- interface RequestOptions {
9
- params?: Record<string, any>;
10
- headers?: Record<string, string>;
11
- body?: Object | null;
12
- signal?: AbortSignal;
13
- mode?: RequestMode;
14
- cache?: RequestCache;
15
- credentials?: RequestCredentials;
16
- }
17
11
  declare function createClient(options: ClientOptions): {
18
12
  WATCH_ERROR: string;
19
13
  WATCH_ADDED: string;
@@ -1 +1 @@
1
- {"version":3,"file":"client.d.ts","sourceRoot":"","sources":["../src/client.ts"],"names":[],"mappings":"AAOA,OAAO,EAAE,KAAK,EAAmC,MAAM,SAAS,CAAA;AAChE,OAAuB,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAA;AAE/D,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,MAAM,GAAG,IAAI,CAAA;IACpB,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,GAAG,WAAW,CAAC;gBAIvE,MAAM,YAAW,cAAc,KAAQ,OAAO,CAAC,OAAO,CAAC;iBAMtD,MAAM,QAAQ,EAAE,YAAW,cAAc,KAAQ,OAAO,CAAC,OAAO,CAAC;gBAOlE,MAAM,QAAQ,EAAE,YAAW,cAAc,KAAQ,OAAO,CAAC,OAAO,CAAC;kBAM/D,MAAM,QAAQ,EAAE,YAAW,cAAc,KAAQ,OAAO,CAAC,OAAO,CAAC;mBAanE,MAAM,SAAS,EAAE,GAAG,IAAI,YAAW,cAAc,KAAQ,OAAO,CAAC,OAAO,CAAC;kBAMvE,MAAM,YAAW,cAAc,KAAQ,KAAK;6BAIjC,MAAM,KAAG,IAAI;wBAIpB,MAAM;EAmBhC;AAED,OAAO,EAAE,YAAY,EAAE,KAAK,cAAc,EAAE,CAAA"}
1
+ {"version":3,"file":"client.d.ts","sourceRoot":"","sources":["../src/client.ts"],"names":[],"mappings":"AAKA,OAAgB,EAAE,cAAc,EAAE,MAAM,WAAW,CAAA;AAEnD,OAAO,EAAE,KAAK,EAAmC,MAAM,SAAS,CAAA;AAChE,OAAuB,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAA;AAE/D,UAAU,aAAa;IACrB,WAAW,EAAE,MAAM,CAAA;IACnB,KAAK,EAAE,MAAM,CAAA;IACb,SAAS,CAAC,EAAE,OAAO,CAAA;IACnB,KAAK,CAAC,EAAE,OAAO,CAAA;IACf,CAAC,GAAG,EAAE,MAAM,GAAG,GAAG,CAAA;CACnB;AAED,iBAAS,YAAY,CAAC,OAAO,EAAE,aAAa;;;;;iBAmCtB,MAAM,YAAW,cAAc,KAAQ,OAAO,CAAC,QAAQ,GAAG,WAAW,CAAC;gBAIvE,MAAM,YAAW,cAAc,KAAQ,OAAO,CAAC,OAAO,CAAC;iBAMtD,MAAM,QAAQ,EAAE,YAAW,cAAc,KAAQ,OAAO,CAAC,OAAO,CAAC;gBAOlE,MAAM,QAAQ,EAAE,YAAW,cAAc,KAAQ,OAAO,CAAC,OAAO,CAAC;kBAM/D,MAAM,QAAQ,EAAE,YAAW,cAAc,KAAQ,OAAO,CAAC,OAAO,CAAC;mBAanE,MAAM,SAAS,EAAE,GAAG,IAAI,YAAW,cAAc,KAAQ,OAAO,CAAC,OAAO,CAAC;kBAMvE,MAAM,YAAW,cAAc,KAAQ,KAAK;6BAIjC,MAAM,KAAG,IAAI;wBAIpB,MAAM;EAmBhC;AAED,OAAO,EAAE,YAAY,EAAE,KAAK,cAAc,EAAE,CAAA"}
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});function j(t){return typeof t=="string"||t instanceof String}function V(t){return typeof t=="number"&&t.constructor===Number}function L(t){return t!==null&&typeof t=="object"&&t.constructor===Object}const B=t=>{if(!t)return;const s=[];for(const r in t)if(Object.keys(t).includes(r)){const d=t[r];s.push(encodeURIComponent(r)+"="+encodeURIComponent(d))}return s.join("&")};function p(...t){if(t.length<2)throw new Error("Bad parameters: buildUrl needs at least two non-empty parameters.");const s=L(t[t.length-1])?t.pop():null;t.forEach(e=>{if(!e||!(j(e)||V(e)))throw new Error("Bad parameters: buildUrl accepts only strings and numbers, with a hash map as the last parameter");if(j(e)&&e.indexOf("?")>=0)throw new Error('Bad parameters: buildUrl does not accept strings with "?" character. Please use a hashmap as the last parameter instead!')});let r=t.join("/");const[d,i]=r.split("://");if(!d||!i)throw new Error(`Bad URL: ${r}`);return r=`${d}://${i.replace(/\/\/+/g,"/")}`,s&&(r+=`?${B(s)}`),r}const I="k8sClient:",P=t=>function(...s){try{const r=[`${I}`,...s];console[t](...r)}catch(r){console.error(I,"Logging error:",r)}},k=P("error"),f=P("debug"),X=t=>{if(t.status>=200&&t.status<300)return t;{const s=new Error(t.statusText||`${t.status}`);throw s.response=t,s}};function m(t,s,r={}){r.params&&(s=p(s,r.params));const i=["signal","headers","body","mode","cache","credentials"].reduce((e,n)=>r[n]?{...e,[n]:r[n]}:e,{credentials:"same-origin",method:t});return i.body&&typeof i.body!="string"&&(i.body=JSON.stringify(i.body)),f("fetch >",s,i),fetch(s,i).then(X)}const g="ADDED",O="MODIFIED",A="DELETED",R="ERROR",$="BOOKMARK";class C{constructor(s,r={},d){var i;this.listeners={[g]:[],[O]:[],[A]:[],[R]:[]},this.controller=new AbortController,this.signal=this.controller.signal,this.resourceVersion=null,this.PREFIX="watch >",this.decoder=new TextDecoder,this.refreshToken=e=>{this.options.headers&&(this.options.headers.Authorization=`Bearer ${e}`)},this.checkType=e=>{if(![g,O,A,R].includes(e))throw new Error(`Bad type: ${e}`)},this.addListener=(e,n)=>{this.checkType(e),this.listeners[e].push(n)},this.informListeners=(e,n)=>{const a=this.listeners[e];a&&a.forEach(c=>{try{c(n)}catch(l){k(l)}})},this.handleEvents=e=>{Array.isArray(e)||(e=[e]);const n=this;setTimeout(()=>{const a={};e.forEach(c=>{var l,y;c.type===$?n.resourceVersion=((y=(l=c==null?void 0:c.object)==null?void 0:l.metadata)==null?void 0:y.resourceVersion)??null:(a[c.type]||(a[c.type]=[]),a[c.type].push(c.object))}),Object.keys(a).forEach(c=>n.informListeners(c,a[c]))})},this.getResourceVersion=async()=>{if(this.resourceVersion)return this.resourceVersion;f(this.PREFIX,"get resource version from API");const{metadata:e,items:n}=await m("GET",this.url,this.options).then(a=>a.json());return this.resourceVersion=e.resourceVersion,n&&this.informListeners(g,n),this.resourceVersion},this.start=()=>{const e=this;return e.getCurrentToken&&e.refreshToken(e.getCurrentToken()),e.getResourceVersion().then(n=>(f(e.PREFIX,"current resource version",n),m("GET",e.url,{...e.options,params:{...e.options.params,watch:1,allowWatchBookmarks:!0,resourceVersion:n},signal:e.signal}))).then(async n=>{var y;const a=(y=n.body)==null?void 0:y.getReader();let c=!1,l="";for(;!c;){f(e.PREFIX,"read stream chunk");const E=await(a==null?void 0:a.read());c=(E==null?void 0:E.done)??!0,l+=e.decoder.decode((E==null?void 0:E.value)||new Uint8Array);const D=l.split(/\n|\r|\r\n/);l=D.pop()??"";const w=[];D.forEach(u=>{var h;const o=JSON.parse(u);if(o.type===R&&((h=o==null?void 0:o.object)==null?void 0:h.code)===410){e.cancel(),setTimeout(()=>{f(e.PREFIX,"resource is gone 410","recreate watch request!"),e.start()});return}w.push(o)}),f(e.PREFIX,"inform listeners",D),e.handleEvents(w)}}).catch(n=>{var c;if(n.name==="AbortError")return;const a=n.code??((c=n==null?void 0:n.response)==null?void 0:c.status);if(a===410){f(e.PREFIX,"resource is gone 410"),e.resourceVersion=null,setTimeout(()=>e.start(),0);return}if(a===404){e.handleEvents({type:R,object:n}),e.cancel();return}k("WATCH ERROR",n,n.code,a,n.response),console.dir(n),setTimeout(()=>{f(e.PREFIX,"recover connection","restart!"),e.start()},3e4)}),e.cancel},this.on=(e,n)=>(this.addListener(e,n),this),this.cancel=()=>{f(this.PREFIX,"cancel connection"),this.controller.abort()},this.url=s,this.options=r,this.getCurrentToken=d,(i=r==null?void 0:r.params)!=null&&i.resourceVersion&&(this.resourceVersion=r.params.resourceVersion,delete r.params.resourceVersion)}}const b=async t=>{var r;const s=(r=t.response)!=null&&r.data?new Error(t.response.data.message??t.message):t;return Promise.reject(s)};function H(t){const{apiEndpoint:s}=t;let r=t.token;if(!s||!r)throw new Error(`Bad options: ${JSON.stringify(t,null,4)}. Please provide apiEndpoint and token`);const d=()=>({Authorization:`Bearer ${r}`,"Content-Type":"application/json"});function i(u,o={}){const h={...d(),...o.headers,...u.headers};return{...o,...u,headers:h}}function e(u,o={}){return m("HEAD",p(s,u),i(o)).catch(b)}function n(u,o={}){return m("GET",p(s,u),i(o)).then(h=>h.json()).catch(b)}function a(u,o,h={}){return m("POST",p(s,u),i(h,{body:o})).then(F=>F.json()).catch(b)}function c(u,o,h={}){return m("PUT",p(s,u),i(h,{body:o})).then(T=>T.json()).catch(b)}function l(u,o,h={}){return m("PATCH",p(s,u),i(h,{headers:{"Content-Type":"application/merge-patch+json"},body:o})).then(T=>T.json()).catch(b)}function y(u,o,h={}){return m("DELETE",p(s,u),i(h,{body:o})).then(T=>T.json()).catch(b)}function E(u,o={}){return new C(p(s,u),i(o),()=>r)}function D(u){r=u}function w(){return r}return{WATCH_ERROR:R,WATCH_ADDED:g,WATCH_DELETED:A,WATCH_MODIFIED:O,head:e,get:n,post:a,put:c,patch:l,delete:y,watch:E,refreshToken:D,currentToken:w}}exports.ADDED=g;exports.DELETED=A;exports.ERROR=R;exports.MODIFIED=O;exports.Watch=C;exports.createClient=H;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const V={};function j(t){return typeof t=="string"||t instanceof String}function B(t){return typeof t=="number"&&t.constructor===Number}function $(t){return t!==null&&typeof t=="object"&&t.constructor===Object}const H=t=>{if(!t)return;const n=[];for(const s in t)if(Object.keys(t).includes(s)){const u=t[s];n.push(encodeURIComponent(s)+"="+encodeURIComponent(u))}return n.join("&")};function p(...t){if(t.length<2)throw new Error("Bad parameters: buildUrl needs at least two non-empty parameters.");const n=$(t[t.length-1])?t.pop():null;t.forEach(r=>{if(!r||!(j(r)||B(r)))throw new Error("Bad parameters: buildUrl accepts only strings and numbers, with a hash map as the last parameter");if(j(r)&&r.indexOf("?")>=0)throw new Error('Bad parameters: buildUrl does not accept strings with "?" character. Please use a hashmap as the last parameter instead!')});let s=t.join("/");const[u,e]=s.split("://");if(!u||!e)throw new Error(`Bad URL: ${s}`);return s=`${u}://${e.replace(/\/\/+/g,"/")}`,n&&(s+=`?${H(n)}`),s}const I="[k8sClient]:",P=t=>function(...n){try{const s=[`${I}`,...n];console[t](...s)}catch(s){console.error(I,"Logging error:",s)}},k=P("error"),d=P("debug"),U=t=>{if(t.status>=200&&t.status<300)return t;{const n=new Error(t.statusText||`${t.status}`);throw n.response=t,n}};function E(t,n,s={}){s.params&&(n=p(n,s.params));const{ignoreSsl:u,...e}=s;let r;u&&n.startsWith("https:")&&typeof window>"u"&&(r=new V.Agent({rejectUnauthorized:!1}),process.env.NODE_ENV!=="test"&&s.debug===!0&&d(`⚠️ SSL verification disabled for request to: ${n}`));const i=["signal","headers","body","mode","cache","credentials"].reduce((l,f)=>e[f]?{...l,[f]:e[f]}:l,{credentials:"same-origin",method:t});return r&&(i.agent=r),i.body&&typeof i.body!="string"&&(i.body=JSON.stringify(i.body)),s.debug===!0&&d("fetch >",n,{...i,agent:r?"HTTPS Agent (SSL ignored)":i.agent}),fetch(n,i).then(U)}const w="ADDED",R="MODIFIED",O="DELETED",y="ERROR",X="BOOKMARK";class C{constructor(n,s={},u){this.listeners={[w]:[],[R]:[],[O]:[],[y]:[]},this.controller=new AbortController,this.signal=this.controller.signal,this.resourceVersion=null,this.PREFIX="watch >",this.decoder=new TextDecoder,this.refreshToken=e=>{this.options.headers&&(this.options.headers.Authorization=`Bearer ${e}`)},this.checkType=e=>{if(![w,R,O,y].includes(e))throw new Error(`Bad type: ${e}`)},this.addListener=(e,r)=>{this.checkType(e),this.listeners[e].push(r)},this.informListeners=(e,r)=>{const o=this.listeners[e];o&&o.forEach(i=>{try{i(r)}catch(l){k(l)}})},this.handleEvents=e=>{Array.isArray(e)||(e=[e]);const r=this;setTimeout(()=>{const o={};e.forEach(i=>{i.type===X?r.resourceVersion=i?.object?.metadata?.resourceVersion??null:(o[i.type]||(o[i.type]=[]),o[i.type].push(i.object))}),Object.keys(o).forEach(i=>r.informListeners(i,o[i]))})},this.getResourceVersion=async()=>{if(this.resourceVersion)return this.resourceVersion;d(this.PREFIX,"get resource version from API");const{metadata:e,items:r}=await E("GET",this.url,this.options).then(o=>o.json());return this.resourceVersion=e.resourceVersion,r&&this.informListeners(w,r),this.resourceVersion},this.start=()=>{const e=this;return e.getCurrentToken&&e.refreshToken(e.getCurrentToken()),e.getResourceVersion().then(r=>(d(e.PREFIX,"current resource version",r),E("GET",e.url,{...e.options,params:{...e.options.params,watch:1,allowWatchBookmarks:!0,resourceVersion:r},signal:e.signal}))).then(async r=>{const o=r.body?.getReader();let i=!1,l="";for(;!i;){d(e.PREFIX,"read stream chunk");const f=await o?.read();i=f?.done??!0,l+=e.decoder.decode(f?.value||new Uint8Array);const b=l.split(/\n|\r|\r\n/);l=b.pop()??"";const D=[];b.forEach(A=>{const T=JSON.parse(A);if(T.type===y&&T?.object?.code===410){e.cancel(),setTimeout(()=>{d(e.PREFIX,"resource is gone 410","recreate watch request!"),e.start()});return}D.push(T)}),d(e.PREFIX,"inform listeners",b),e.handleEvents(D)}}).catch(r=>{if(r.name==="AbortError")return;const o=r.code??r?.response?.status;if(o===410){d(e.PREFIX,"resource is gone 410"),e.resourceVersion=null,setTimeout(()=>e.start(),0);return}if(o===404){e.handleEvents({type:y,object:r}),e.cancel();return}k("WATCH ERROR",r,r.code,o,r.response),console.dir(r),setTimeout(()=>{d(e.PREFIX,"recover connection","restart!"),e.start()},3e4)}),e.cancel},this.on=(e,r)=>(this.addListener(e,r),this),this.cancel=()=>{d(this.PREFIX,"cancel connection"),this.controller.abort()},this.url=n,this.options=s,this.getCurrentToken=u,s?.params?.resourceVersion&&(this.resourceVersion=s.params.resourceVersion,delete s.params.resourceVersion)}}const g=async t=>{const n=t.response?.data?new Error(t.response.data.message??t.message):t;return Promise.reject(n)};function W(t){const{apiEndpoint:n,ignoreSsl:s=!1,debug:u=!1}=t;let e=t.token;if(!n||!e)throw new Error(`Bad options: ${JSON.stringify(t,null,4)}. Please provide apiEndpoint and token`);s&&u===!0&&(console.warn(`⚠️ K8s Client: SSL certificate verification disabled for ${n}`),console.warn("🔒 This should only be used in development or secure internal networks"));const r=()=>({Authorization:`Bearer ${e}`,"Content-Type":"application/json"});function o(c,a={}){const h={...r(),...a.headers,...c.headers};return{debug:u,ignoreSsl:s,...a,...c,headers:h}}function i(c,a={}){return E("HEAD",p(n,c),o(a)).catch(g)}function l(c,a={}){return E("GET",p(n,c),o(a)).then(h=>h.json()).catch(g)}function f(c,a,h={}){return E("POST",p(n,c),o(h,{body:a})).then(L=>L.json()).catch(g)}function b(c,a,h={}){return E("PUT",p(n,c),o(h,{body:a})).then(m=>m.json()).catch(g)}function D(c,a,h={}){return E("PATCH",p(n,c),o(h,{headers:{"Content-Type":"application/merge-patch+json"},body:a})).then(m=>m.json()).catch(g)}function A(c,a,h={}){return E("DELETE",p(n,c),o(h,{body:a})).then(m=>m.json()).catch(g)}function T(c,a={}){return new C(p(n,c),o(a),()=>e)}function S(c){e=c}function F(){return e}return{WATCH_ERROR:y,WATCH_ADDED:w,WATCH_DELETED:O,WATCH_MODIFIED:R,head:i,get:l,post:f,put:b,patch:D,delete:A,watch:T,refreshToken:S,currentToken:F}}exports.ADDED=w;exports.DELETED=O;exports.ERROR=y;exports.MODIFIED=R;exports.Watch=C;exports.createClient=W;
package/build/index.es.js CHANGED
@@ -1,246 +1,252 @@
1
+ const L = {};
1
2
  function j(t) {
2
3
  return typeof t == "string" || t instanceof String;
3
4
  }
4
- function F(t) {
5
+ function V(t) {
5
6
  return typeof t == "number" && t.constructor === Number;
6
7
  }
7
- function V(t) {
8
+ function B(t) {
8
9
  return t !== null && typeof t == "object" && t.constructor === Object;
9
10
  }
10
- const B = (t) => {
11
+ const $ = (t) => {
11
12
  if (!t) return;
12
- const s = [];
13
- for (const r in t)
14
- if (Object.keys(t).includes(r)) {
15
- const d = t[r];
16
- s.push(encodeURIComponent(r) + "=" + encodeURIComponent(d));
13
+ const n = [];
14
+ for (const s in t)
15
+ if (Object.keys(t).includes(s)) {
16
+ const u = t[s];
17
+ n.push(encodeURIComponent(s) + "=" + encodeURIComponent(u));
17
18
  }
18
- return s.join("&");
19
+ return n.join("&");
19
20
  };
20
- function E(...t) {
21
+ function p(...t) {
21
22
  if (t.length < 2)
22
23
  throw new Error("Bad parameters: buildUrl needs at least two non-empty parameters.");
23
- const s = V(t[t.length - 1]) ? t.pop() : null;
24
- t.forEach((e) => {
25
- if (!e || !(j(e) || F(e)))
24
+ const n = B(t[t.length - 1]) ? t.pop() : null;
25
+ t.forEach((r) => {
26
+ if (!r || !(j(r) || V(r)))
26
27
  throw new Error(
27
28
  "Bad parameters: buildUrl accepts only strings and numbers, with a hash map as the last parameter"
28
29
  );
29
- if (j(e) && e.indexOf("?") >= 0)
30
+ if (j(r) && r.indexOf("?") >= 0)
30
31
  throw new Error(
31
32
  'Bad parameters: buildUrl does not accept strings with "?" character. Please use a hashmap as the last parameter instead!'
32
33
  );
33
34
  });
34
- let r = t.join("/");
35
- const [d, i] = r.split("://");
36
- if (!d || !i)
37
- throw new Error(`Bad URL: ${r}`);
38
- return r = `${d}://${i.replace(/\/\/+/g, "/")}`, s && (r += `?${B(s)}`), r;
35
+ let s = t.join("/");
36
+ const [u, e] = s.split("://");
37
+ if (!u || !e)
38
+ throw new Error(`Bad URL: ${s}`);
39
+ return s = `${u}://${e.replace(/\/\/+/g, "/")}`, n && (s += `?${$(n)}`), s;
39
40
  }
40
- const I = "k8sClient:", P = (t) => function(...s) {
41
+ const k = "[k8sClient]:", P = (t) => function(...n) {
41
42
  try {
42
- const r = [`${I}`, ...s];
43
- console[t](...r);
44
- } catch (r) {
45
- console.error(I, "Logging error:", r);
43
+ const s = [`${k}`, ...n];
44
+ console[t](...s);
45
+ } catch (s) {
46
+ console.error(k, "Logging error:", s);
46
47
  }
47
- }, k = P("error"), f = P("debug"), L = (t) => {
48
+ }, I = P("error"), l = P("debug"), H = (t) => {
48
49
  if (t.status >= 200 && t.status < 300)
49
50
  return t;
50
51
  {
51
- const s = new Error(t.statusText || `${t.status}`);
52
- throw s.response = t, s;
52
+ const n = new Error(t.statusText || `${t.status}`);
53
+ throw n.response = t, n;
53
54
  }
54
55
  };
55
- function m(t, s, r = {}) {
56
- r.params && (s = E(s, r.params));
56
+ function E(t, n, s = {}) {
57
+ s.params && (n = p(n, s.params));
58
+ const { ignoreSsl: u, ...e } = s;
59
+ let r;
60
+ u && n.startsWith("https:") && typeof window > "u" && (r = new L.Agent({
61
+ rejectUnauthorized: !1
62
+ }), process.env.NODE_ENV !== "test" && s.debug === !0 && l(`⚠️ SSL verification disabled for request to: ${n}`));
57
63
  const i = ["signal", "headers", "body", "mode", "cache", "credentials"].reduce(
58
- (e, n) => r[n] ? { ...e, [n]: r[n] } : e,
64
+ (d, f) => e[f] ? { ...d, [f]: e[f] } : d,
59
65
  { credentials: "same-origin", method: t }
60
66
  );
61
- return i.body && typeof i.body != "string" && (i.body = JSON.stringify(i.body)), f("fetch >", s, i), fetch(s, i).then(L);
67
+ return r && (i.agent = r), i.body && typeof i.body != "string" && (i.body = JSON.stringify(i.body)), s.debug === !0 && l("fetch >", n, {
68
+ ...i,
69
+ agent: r ? "HTTPS Agent (SSL ignored)" : i.agent
70
+ }), fetch(n, i).then(H);
62
71
  }
63
- const D = "ADDED", A = "MODIFIED", O = "DELETED", R = "ERROR", X = "BOOKMARK";
64
- class $ {
65
- constructor(s, r = {}, d) {
66
- var i;
72
+ const R = "ADDED", A = "MODIFIED", O = "DELETED", w = "ERROR", U = "BOOKMARK";
73
+ class X {
74
+ constructor(n, s = {}, u) {
67
75
  this.listeners = {
68
- [D]: [],
76
+ [R]: [],
69
77
  [A]: [],
70
78
  [O]: [],
71
- [R]: []
79
+ [w]: []
72
80
  }, this.controller = new AbortController(), this.signal = this.controller.signal, this.resourceVersion = null, this.PREFIX = "watch >", this.decoder = new TextDecoder(), this.refreshToken = (e) => {
73
81
  this.options.headers && (this.options.headers.Authorization = `Bearer ${e}`);
74
82
  }, this.checkType = (e) => {
75
- if (![D, A, O, R].includes(e))
83
+ if (![R, A, O, w].includes(e))
76
84
  throw new Error(`Bad type: ${e}`);
77
- }, this.addListener = (e, n) => {
78
- this.checkType(e), this.listeners[e].push(n);
79
- }, this.informListeners = (e, n) => {
80
- const a = this.listeners[e];
81
- a && a.forEach((c) => {
85
+ }, this.addListener = (e, r) => {
86
+ this.checkType(e), this.listeners[e].push(r);
87
+ }, this.informListeners = (e, r) => {
88
+ const o = this.listeners[e];
89
+ o && o.forEach((i) => {
82
90
  try {
83
- c(n);
84
- } catch (l) {
85
- k(l);
91
+ i(r);
92
+ } catch (d) {
93
+ I(d);
86
94
  }
87
95
  });
88
96
  }, this.handleEvents = (e) => {
89
97
  Array.isArray(e) || (e = [e]);
90
- const n = this;
98
+ const r = this;
91
99
  setTimeout(() => {
92
- const a = {};
93
- e.forEach((c) => {
94
- var l, y;
95
- c.type === X ? n.resourceVersion = ((y = (l = c == null ? void 0 : c.object) == null ? void 0 : l.metadata) == null ? void 0 : y.resourceVersion) ?? null : (a[c.type] || (a[c.type] = []), a[c.type].push(c.object));
96
- }), Object.keys(a).forEach((c) => n.informListeners(c, a[c]));
100
+ const o = {};
101
+ e.forEach((i) => {
102
+ i.type === U ? r.resourceVersion = i?.object?.metadata?.resourceVersion ?? null : (o[i.type] || (o[i.type] = []), o[i.type].push(i.object));
103
+ }), Object.keys(o).forEach((i) => r.informListeners(i, o[i]));
97
104
  });
98
105
  }, this.getResourceVersion = async () => {
99
106
  if (this.resourceVersion) return this.resourceVersion;
100
- f(this.PREFIX, "get resource version from API");
101
- const { metadata: e, items: n } = await m("GET", this.url, this.options).then(
102
- (a) => (
107
+ l(this.PREFIX, "get resource version from API");
108
+ const { metadata: e, items: r } = await E("GET", this.url, this.options).then(
109
+ (o) => (
103
110
  // 'Body.json()' type definition expects 'any' as a return value
104
- a.json()
111
+ o.json()
105
112
  )
106
113
  );
107
- return this.resourceVersion = e.resourceVersion, n && this.informListeners(D, n), this.resourceVersion;
114
+ return this.resourceVersion = e.resourceVersion, r && this.informListeners(R, r), this.resourceVersion;
108
115
  }, this.start = () => {
109
116
  const e = this;
110
- return e.getCurrentToken && e.refreshToken(e.getCurrentToken()), e.getResourceVersion().then((n) => (f(e.PREFIX, "current resource version", n), m("GET", e.url, {
117
+ return e.getCurrentToken && e.refreshToken(e.getCurrentToken()), e.getResourceVersion().then((r) => (l(e.PREFIX, "current resource version", r), E("GET", e.url, {
111
118
  ...e.options,
112
119
  params: {
113
120
  ...e.options.params,
114
121
  watch: 1,
115
122
  allowWatchBookmarks: !0,
116
- resourceVersion: n
123
+ resourceVersion: r
117
124
  },
118
125
  signal: e.signal
119
- }))).then(async (n) => {
120
- var y;
121
- const a = (y = n.body) == null ? void 0 : y.getReader();
122
- let c = !1, l = "";
123
- for (; !c; ) {
124
- f(e.PREFIX, "read stream chunk");
125
- const p = await (a == null ? void 0 : a.read());
126
- c = (p == null ? void 0 : p.done) ?? !0, l += e.decoder.decode((p == null ? void 0 : p.value) || new Uint8Array());
127
- const w = l.split(/\n|\r|\r\n/);
128
- l = w.pop() ?? "";
129
- const g = [];
130
- w.forEach((h) => {
131
- var u;
132
- const o = JSON.parse(h);
133
- if (o.type === R && ((u = o == null ? void 0 : o.object) == null ? void 0 : u.code) === 410) {
126
+ }))).then(async (r) => {
127
+ const o = r.body?.getReader();
128
+ let i = !1, d = "";
129
+ for (; !i; ) {
130
+ l(e.PREFIX, "read stream chunk");
131
+ const f = await o?.read();
132
+ i = f?.done ?? !0, d += e.decoder.decode(f?.value || new Uint8Array());
133
+ const y = d.split(/\n|\r|\r\n/);
134
+ d = y.pop() ?? "";
135
+ const T = [];
136
+ y.forEach((D) => {
137
+ const b = JSON.parse(D);
138
+ if (b.type === w && b?.object?.code === 410) {
134
139
  e.cancel(), setTimeout(() => {
135
- f(e.PREFIX, "resource is gone 410", "recreate watch request!"), e.start();
140
+ l(e.PREFIX, "resource is gone 410", "recreate watch request!"), e.start();
136
141
  });
137
142
  return;
138
143
  }
139
- g.push(o);
140
- }), f(e.PREFIX, "inform listeners", w), e.handleEvents(g);
144
+ T.push(b);
145
+ }), l(e.PREFIX, "inform listeners", y), e.handleEvents(T);
141
146
  }
142
- }).catch((n) => {
143
- var c;
144
- if (n.name === "AbortError") return;
145
- const a = n.code ?? ((c = n == null ? void 0 : n.response) == null ? void 0 : c.status);
146
- if (a === 410) {
147
- f(e.PREFIX, "resource is gone 410"), e.resourceVersion = null, setTimeout(() => e.start(), 0);
147
+ }).catch((r) => {
148
+ if (r.name === "AbortError") return;
149
+ const o = r.code ?? r?.response?.status;
150
+ if (o === 410) {
151
+ l(e.PREFIX, "resource is gone 410"), e.resourceVersion = null, setTimeout(() => e.start(), 0);
148
152
  return;
149
153
  }
150
- if (a === 404) {
151
- e.handleEvents({ type: R, object: n }), e.cancel();
154
+ if (o === 404) {
155
+ e.handleEvents({ type: w, object: r }), e.cancel();
152
156
  return;
153
157
  }
154
- k("WATCH ERROR", n, n.code, a, n.response), console.dir(n), setTimeout(() => {
155
- f(e.PREFIX, "recover connection", "restart!"), e.start();
158
+ I("WATCH ERROR", r, r.code, o, r.response), console.dir(r), setTimeout(() => {
159
+ l(e.PREFIX, "recover connection", "restart!"), e.start();
156
160
  }, 3e4);
157
161
  }), e.cancel;
158
- }, this.on = (e, n) => (this.addListener(e, n), this), this.cancel = () => {
159
- f(this.PREFIX, "cancel connection"), this.controller.abort();
160
- }, this.url = s, this.options = r, this.getCurrentToken = d, (i = r == null ? void 0 : r.params) != null && i.resourceVersion && (this.resourceVersion = r.params.resourceVersion, delete r.params.resourceVersion);
162
+ }, this.on = (e, r) => (this.addListener(e, r), this), this.cancel = () => {
163
+ l(this.PREFIX, "cancel connection"), this.controller.abort();
164
+ }, this.url = n, this.options = s, this.getCurrentToken = u, s?.params?.resourceVersion && (this.resourceVersion = s.params.resourceVersion, delete s.params.resourceVersion);
161
165
  }
162
166
  }
163
- const b = async (t) => {
164
- var r;
165
- const s = (r = t.response) != null && r.data ? new Error(t.response.data.message ?? t.message) : t;
166
- return Promise.reject(s);
167
+ const g = async (t) => {
168
+ const n = t.response?.data ? new Error(t.response.data.message ?? t.message) : t;
169
+ return Promise.reject(n);
167
170
  };
168
- function H(t) {
169
- const { apiEndpoint: s } = t;
170
- let r = t.token;
171
- if (!s || !r)
171
+ function W(t) {
172
+ const { apiEndpoint: n, ignoreSsl: s = !1, debug: u = !1 } = t;
173
+ let e = t.token;
174
+ if (!n || !e)
172
175
  throw new Error(`Bad options: ${JSON.stringify(t, null, 4)}. Please provide apiEndpoint and token`);
173
- const d = () => ({
174
- Authorization: `Bearer ${r}`,
176
+ s && u === !0 && (console.warn(`⚠️ K8s Client: SSL certificate verification disabled for ${n}`), console.warn("🔒 This should only be used in development or secure internal networks"));
177
+ const r = () => ({
178
+ Authorization: `Bearer ${e}`,
175
179
  "Content-Type": "application/json"
176
180
  });
177
- function i(h, o = {}) {
178
- const u = {
179
- ...d(),
180
- ...o.headers,
181
- ...h.headers
181
+ function o(c, a = {}) {
182
+ const h = {
183
+ ...r(),
184
+ ...a.headers,
185
+ ...c.headers
182
186
  };
183
187
  return {
184
- ...o,
185
- ...h,
186
- headers: u
188
+ debug: u,
189
+ ignoreSsl: s,
190
+ ...a,
191
+ ...c,
192
+ headers: h
187
193
  };
188
194
  }
189
- function e(h, o = {}) {
190
- return m("HEAD", E(s, h), i(o)).catch(b);
195
+ function i(c, a = {}) {
196
+ return E("HEAD", p(n, c), o(a)).catch(g);
191
197
  }
192
- function n(h, o = {}) {
193
- return m("GET", E(s, h), i(o)).then((u) => u.json()).catch(b);
198
+ function d(c, a = {}) {
199
+ return E("GET", p(n, c), o(a)).then((h) => h.json()).catch(g);
194
200
  }
195
- function a(h, o, u = {}) {
196
- return m("POST", E(s, h), i(u, { body: o })).then((C) => C.json()).catch(b);
201
+ function f(c, a, h = {}) {
202
+ return E("POST", p(n, c), o(h, { body: a })).then((F) => F.json()).catch(g);
197
203
  }
198
- function c(h, o, u = {}) {
199
- return m("PUT", E(s, h), i(u, { body: o })).then((T) => T.json()).catch(b);
204
+ function y(c, a, h = {}) {
205
+ return E("PUT", p(n, c), o(h, { body: a })).then((m) => m.json()).catch(g);
200
206
  }
201
- function l(h, o, u = {}) {
202
- return m(
207
+ function T(c, a, h = {}) {
208
+ return E(
203
209
  "PATCH",
204
- E(s, h),
205
- i(u, {
210
+ p(n, c),
211
+ o(h, {
206
212
  headers: { "Content-Type": "application/merge-patch+json" },
207
- body: o
213
+ body: a
208
214
  })
209
- ).then((T) => T.json()).catch(b);
215
+ ).then((m) => m.json()).catch(g);
210
216
  }
211
- function y(h, o, u = {}) {
212
- return m("DELETE", E(s, h), i(u, { body: o })).then((T) => T.json()).catch(b);
217
+ function D(c, a, h = {}) {
218
+ return E("DELETE", p(n, c), o(h, { body: a })).then((m) => m.json()).catch(g);
213
219
  }
214
- function p(h, o = {}) {
215
- return new $(E(s, h), i(o), () => r);
220
+ function b(c, a = {}) {
221
+ return new X(p(n, c), o(a), () => e);
216
222
  }
217
- function w(h) {
218
- r = h;
223
+ function C(c) {
224
+ e = c;
219
225
  }
220
- function g() {
221
- return r;
226
+ function S() {
227
+ return e;
222
228
  }
223
229
  return {
224
- WATCH_ERROR: R,
225
- WATCH_ADDED: D,
230
+ WATCH_ERROR: w,
231
+ WATCH_ADDED: R,
226
232
  WATCH_DELETED: O,
227
233
  WATCH_MODIFIED: A,
228
- head: e,
229
- get: n,
230
- post: a,
231
- put: c,
232
- patch: l,
233
- delete: y,
234
- watch: p,
235
- refreshToken: w,
236
- currentToken: g
234
+ head: i,
235
+ get: d,
236
+ post: f,
237
+ put: y,
238
+ patch: T,
239
+ delete: D,
240
+ watch: b,
241
+ refreshToken: C,
242
+ currentToken: S
237
243
  };
238
244
  }
239
245
  export {
240
- D as ADDED,
246
+ R as ADDED,
241
247
  O as DELETED,
242
- R as ERROR,
248
+ w as ERROR,
243
249
  A as MODIFIED,
244
- $ as Watch,
245
- H as createClient
250
+ X as Watch,
251
+ W as createClient
246
252
  };
@@ -1,11 +1,13 @@
1
1
  interface RequestOptions {
2
2
  params?: Record<string, any>;
3
3
  signal?: AbortSignal;
4
- headers?: HeadersInit | null;
4
+ headers?: Record<string, any>;
5
5
  body?: Object | null;
6
6
  mode?: RequestMode;
7
7
  cache?: RequestCache;
8
8
  credentials?: RequestCredentials;
9
+ ignoreSsl?: boolean;
10
+ debug?: boolean;
9
11
  [key: string]: any;
10
12
  }
11
13
  /**
@@ -13,9 +15,10 @@ interface RequestOptions {
13
15
  *
14
16
  * @param {string} method Http method.
15
17
  * @param {string} url The URL to send the request to.
16
- * @param {RequestOptions} options params, headers, and other options supported by fetch.
18
+ * @param {RequestOptions} options params, headers, ignoreSsl, and other options supported by fetch.
17
19
  * @return {Promise<Response>} The response promise.
18
20
  */
19
21
  declare function request(method: string, url: string, options?: RequestOptions): Promise<Response>;
20
22
  export default request;
23
+ export type { RequestOptions };
21
24
  //# sourceMappingURL=request.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"request.d.ts","sourceRoot":"","sources":["../src/request.ts"],"names":[],"mappings":"AAUA,UAAU,cAAc;IACtB,MAAM,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,CAAA;IAC5B,MAAM,CAAC,EAAE,WAAW,CAAA;IACpB,OAAO,CAAC,EAAE,WAAW,GAAG,IAAI,CAAA;IAC5B,IAAI,CAAC,EAAE,MAAM,GAAG,IAAI,CAAA;IACpB,IAAI,CAAC,EAAE,WAAW,CAAA;IAClB,KAAK,CAAC,EAAE,YAAY,CAAA;IACpB,WAAW,CAAC,EAAE,kBAAkB,CAAA;IAChC,CAAC,GAAG,EAAE,MAAM,GAAG,GAAG,CAAA;CACnB;AAaD;;;;;;;GAOG;AACH,iBAAS,OAAO,CAAC,MAAM,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,EAAE,OAAO,GAAE,cAAmB,GAAG,OAAO,CAAC,QAAQ,CAAC,CA2B7F;AAED,eAAe,OAAO,CAAA"}
1
+ {"version":3,"file":"request.d.ts","sourceRoot":"","sources":["../src/request.ts"],"names":[],"mappings":"AAUA,UAAU,cAAc;IACtB,MAAM,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,CAAA;IAC5B,MAAM,CAAC,EAAE,WAAW,CAAA;IACpB,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,CAAA;IAC7B,IAAI,CAAC,EAAE,MAAM,GAAG,IAAI,CAAA;IACpB,IAAI,CAAC,EAAE,WAAW,CAAA;IAClB,KAAK,CAAC,EAAE,YAAY,CAAA;IACpB,WAAW,CAAC,EAAE,kBAAkB,CAAA;IAChC,SAAS,CAAC,EAAE,OAAO,CAAA;IACnB,KAAK,CAAC,EAAE,OAAO,CAAA;IACf,CAAC,GAAG,EAAE,MAAM,GAAG,GAAG,CAAA;CACnB;AAaD;;;;;;;GAOG;AACH,iBAAS,OAAO,CAAC,MAAM,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,EAAE,OAAO,GAAE,cAAmB,GAAG,OAAO,CAAC,QAAQ,CAAC,CAqD7F;AAED,eAAe,OAAO,CAAA;AACtB,YAAY,EAAE,cAAc,EAAE,CAAA"}
package/build/watch.d.ts CHANGED
@@ -11,6 +11,8 @@ interface WatchOptions {
11
11
  mode?: RequestMode;
12
12
  cache?: RequestCache;
13
13
  credentials?: RequestCredentials;
14
+ ignoreSsl?: boolean;
15
+ debug?: boolean;
14
16
  }
15
17
  declare class Watch {
16
18
  private readonly listeners;
@@ -1 +1 @@
1
- {"version":3,"file":"watch.d.ts","sourceRoot":"","sources":["../src/watch.ts"],"names":[],"mappings":"AASA,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,OAAO,KAAK,IAAI,CAAA;AAmBzC,UAAU,YAAY;IACpB,MAAM,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAA;IAC/B,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAA;IAChC,MAAM,CAAC,EAAE,WAAW,CAAA;IACpB,IAAI,CAAC,EAAE,MAAM,GAAG,IAAI,CAAA;IACpB,IAAI,CAAC,EAAE,WAAW,CAAA;IAClB,KAAK,CAAC,EAAE,YAAY,CAAA;IACpB,WAAW,CAAC,EAAE,kBAAkB,CAAA;CACjC;AAED,cAAM,KAAK;IACT,OAAO,CAAC,QAAQ,CAAC,SAAS,CAKzB;IACD,OAAO,CAAC,QAAQ,CAAC,UAAU,CAAyC;IACpE,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAsC;IAC7D,OAAO,CAAC,eAAe,CAAsB;IAC7C,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAY;IACnC,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAoB;IAC5C,OAAO,CAAC,QAAQ,CAAC,GAAG,CAAQ;IAC5B,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAc;IACtC,OAAO,CAAC,QAAQ,CAAC,eAAe,CAAC,CAAc;gBAEnC,GAAG,EAAE,MAAM,EAAE,OAAO,GAAE,YAAiB,EAAE,eAAe,CAAC,EAAE,MAAM,MAAM;IAYnF,YAAY,GAAI,UAAU,MAAM,UAI/B;IAED,OAAO,CAAC,SAAS,CAIhB;IAED,OAAO,CAAC,WAAW,CAGlB;IAED,OAAO,CAAC,eAAe,CAYtB;IAED,OAAO,CAAC,YAAY,CAsBnB;IAED,OAAO,CAAC,kBAAkB,CAazB;IAED,KAAK,mBAmFJ;IAED,EAAE,GAAI,MAAM,MAAM,EAAE,UAAU,QAAQ,UAGrC;IAED,MAAM,aAGL;CACF;AAED,OAAO,EAAE,KAAK,EAAE,QAAQ,EAAE,OAAO,EAAE,KAAK,EAAE,KAAK,EAAE,CAAA"}
1
+ {"version":3,"file":"watch.d.ts","sourceRoot":"","sources":["../src/watch.ts"],"names":[],"mappings":"AASA,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,OAAO,KAAK,IAAI,CAAA;AAmBzC,UAAU,YAAY;IACpB,MAAM,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAA;IAC/B,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAA;IAChC,MAAM,CAAC,EAAE,WAAW,CAAA;IACpB,IAAI,CAAC,EAAE,MAAM,GAAG,IAAI,CAAA;IACpB,IAAI,CAAC,EAAE,WAAW,CAAA;IAClB,KAAK,CAAC,EAAE,YAAY,CAAA;IACpB,WAAW,CAAC,EAAE,kBAAkB,CAAA;IAChC,SAAS,CAAC,EAAE,OAAO,CAAA;IACnB,KAAK,CAAC,EAAE,OAAO,CAAA;CAChB;AAED,cAAM,KAAK;IACT,OAAO,CAAC,QAAQ,CAAC,SAAS,CAKzB;IACD,OAAO,CAAC,QAAQ,CAAC,UAAU,CAAyC;IACpE,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAsC;IAC7D,OAAO,CAAC,eAAe,CAAsB;IAC7C,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAY;IACnC,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAoB;IAC5C,OAAO,CAAC,QAAQ,CAAC,GAAG,CAAQ;IAC5B,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAc;IACtC,OAAO,CAAC,QAAQ,CAAC,eAAe,CAAC,CAAc;gBAEnC,GAAG,EAAE,MAAM,EAAE,OAAO,GAAE,YAAiB,EAAE,eAAe,CAAC,EAAE,MAAM,MAAM;IAYnF,YAAY,GAAI,UAAU,MAAM,UAI/B;IAED,OAAO,CAAC,SAAS,CAIhB;IAED,OAAO,CAAC,WAAW,CAGlB;IAED,OAAO,CAAC,eAAe,CAYtB;IAED,OAAO,CAAC,YAAY,CAsBnB;IAED,OAAO,CAAC,kBAAkB,CAazB;IAED,KAAK,mBAmFJ;IAED,EAAE,GAAI,MAAM,MAAM,EAAE,UAAU,QAAQ,UAGrC;IAED,MAAM,aAGL;CACF;AAED,OAAO,EAAE,KAAK,EAAE,QAAQ,EAAE,OAAO,EAAE,KAAK,EAAE,KAAK,EAAE,CAAA"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cloudoperators/juno-k8s-client",
3
- "version": "1.0.7",
3
+ "version": "1.1.0",
4
4
  "author": "UI-Team",
5
5
  "description": "JavaScript client for Kubernetes API",
6
6
  "main": "build/index.cjs.js",
@@ -24,11 +24,11 @@
24
24
  "client"
25
25
  ],
26
26
  "devDependencies": {
27
- "vite": "^6.3.5",
28
- "vitest": "^3.0.7",
27
+ "vite": "^7.0.3",
28
+ "vitest": "^3.2.4",
29
29
  "@testing-library/jest-dom": "^6.6.3",
30
- "vite-plugin-dts": "^4.0.3",
31
- "@cloudoperators/juno-config": "0.0.2"
30
+ "vite-plugin-dts": "^4.5.4",
31
+ "@cloudoperators/juno-config": "0.0.5"
32
32
  },
33
33
  "scripts": {
34
34
  "test": "vitest run",