@calimero-network/mero-js 0.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.
Files changed (85) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +443 -0
  3. package/dist/admin-api/admin-client.d.ts +38 -0
  4. package/dist/admin-api/admin-client.d.ts.map +1 -0
  5. package/dist/admin-api/admin-client.js +104 -0
  6. package/dist/admin-api/admin-client.js.map +1 -0
  7. package/dist/admin-api/admin-factory.d.ts +8 -0
  8. package/dist/admin-api/admin-factory.d.ts.map +1 -0
  9. package/dist/admin-api/admin-factory.js +42 -0
  10. package/dist/admin-api/admin-factory.js.map +1 -0
  11. package/dist/admin-api/admin-types.d.ts +213 -0
  12. package/dist/admin-api/admin-types.d.ts.map +1 -0
  13. package/dist/admin-api/admin-types.js +3 -0
  14. package/dist/admin-api/admin-types.js.map +1 -0
  15. package/dist/admin-api/index.d.ts +4 -0
  16. package/dist/admin-api/index.d.ts.map +1 -0
  17. package/dist/admin-api/index.js +5 -0
  18. package/dist/admin-api/index.js.map +1 -0
  19. package/dist/auth-api/auth-client.d.ts +34 -0
  20. package/dist/auth-api/auth-client.d.ts.map +1 -0
  21. package/dist/auth-api/auth-client.js +112 -0
  22. package/dist/auth-api/auth-client.js.map +1 -0
  23. package/dist/auth-api/auth-factory.d.ts +8 -0
  24. package/dist/auth-api/auth-factory.d.ts.map +1 -0
  25. package/dist/auth-api/auth-factory.js +42 -0
  26. package/dist/auth-api/auth-factory.js.map +1 -0
  27. package/dist/auth-api/auth-types.d.ts +127 -0
  28. package/dist/auth-api/auth-types.d.ts.map +1 -0
  29. package/dist/auth-api/auth-types.js +3 -0
  30. package/dist/auth-api/auth-types.js.map +1 -0
  31. package/dist/auth-api/index.d.ts +4 -0
  32. package/dist/auth-api/index.d.ts.map +1 -0
  33. package/dist/auth-api/index.js +5 -0
  34. package/dist/auth-api/index.js.map +1 -0
  35. package/dist/http-client/api-response.d.ts +16 -0
  36. package/dist/http-client/api-response.d.ts.map +1 -0
  37. package/dist/http-client/api-response.js +2 -0
  38. package/dist/http-client/api-response.js.map +1 -0
  39. package/dist/http-client/http-factory.d.ts +32 -0
  40. package/dist/http-client/http-factory.d.ts.map +1 -0
  41. package/dist/http-client/http-factory.js +52 -0
  42. package/dist/http-client/http-factory.js.map +1 -0
  43. package/dist/http-client/http-types.d.ts +42 -0
  44. package/dist/http-client/http-types.d.ts.map +1 -0
  45. package/dist/http-client/http-types.js +2 -0
  46. package/dist/http-client/http-types.js.map +1 -0
  47. package/dist/http-client/index.d.ts +8 -0
  48. package/dist/http-client/index.d.ts.map +1 -0
  49. package/dist/http-client/index.js +12 -0
  50. package/dist/http-client/index.js.map +1 -0
  51. package/dist/http-client/retry.d.ts +6 -0
  52. package/dist/http-client/retry.d.ts.map +1 -0
  53. package/dist/http-client/retry.js +83 -0
  54. package/dist/http-client/retry.js.map +1 -0
  55. package/dist/http-client/signal-utils.d.ts +3 -0
  56. package/dist/http-client/signal-utils.d.ts.map +1 -0
  57. package/dist/http-client/signal-utils.js +42 -0
  58. package/dist/http-client/signal-utils.js.map +1 -0
  59. package/dist/http-client/web-client.d.ts +38 -0
  60. package/dist/http-client/web-client.d.ts.map +1 -0
  61. package/dist/http-client/web-client.js +296 -0
  62. package/dist/http-client/web-client.js.map +1 -0
  63. package/dist/index.browser.mjs +2 -0
  64. package/dist/index.browser.mjs.map +7 -0
  65. package/dist/index.cjs +995 -0
  66. package/dist/index.cjs.map +7 -0
  67. package/dist/index.d.ts +6 -0
  68. package/dist/index.d.ts.map +1 -0
  69. package/dist/index.js +12 -0
  70. package/dist/index.js.map +1 -0
  71. package/dist/index.mjs +973 -0
  72. package/dist/index.mjs.map +7 -0
  73. package/dist/mero-js.d.ts +77 -0
  74. package/dist/mero-js.d.ts.map +1 -0
  75. package/dist/mero-js.js +175 -0
  76. package/dist/mero-js.js.map +1 -0
  77. package/dist/types/api-response.d.ts +16 -0
  78. package/dist/types/api-response.d.ts.map +1 -0
  79. package/dist/types/api-response.js +2 -0
  80. package/dist/types/api-response.js.map +1 -0
  81. package/dist/types/index.d.ts +2 -0
  82. package/dist/types/index.d.ts.map +1 -0
  83. package/dist/types/index.js +2 -0
  84. package/dist/types/index.js.map +1 -0
  85. package/package.json +86 -0
package/dist/index.mjs ADDED
@@ -0,0 +1,973 @@
1
+ // src/http-client/signal-utils.ts
2
+ function combineSignals(signals) {
3
+ const list = signals.filter(Boolean);
4
+ if (list.length === 0) return void 0;
5
+ const AbortSignalAny = AbortSignal;
6
+ if (typeof AbortSignalAny.any === "function") {
7
+ try {
8
+ return AbortSignalAny.any(list);
9
+ } catch {
10
+ }
11
+ }
12
+ const controller = new AbortController();
13
+ const onAbort = (evt) => {
14
+ controller.abort(evt.target.reason);
15
+ for (const s of list) s.removeEventListener("abort", onAbort);
16
+ };
17
+ for (const s of list) {
18
+ if (s.aborted) return AbortSignal.abort(s.reason);
19
+ s.addEventListener("abort", onAbort, { once: true });
20
+ }
21
+ return controller.signal;
22
+ }
23
+ function createTimeoutSignal(timeoutMs) {
24
+ if (typeof AbortSignal.timeout === "function") {
25
+ return AbortSignal.timeout(timeoutMs);
26
+ }
27
+ const controller = new AbortController();
28
+ setTimeout(() => {
29
+ controller.abort(new DOMException("Timeout", "TimeoutError"));
30
+ }, timeoutMs);
31
+ return controller.signal;
32
+ }
33
+
34
+ // src/http-client/web-client.ts
35
+ var HTTPError = class extends Error {
36
+ constructor(status, statusText, url, headers, bodyText) {
37
+ super(`HTTP ${status} ${statusText}`);
38
+ this.status = status;
39
+ this.statusText = statusText;
40
+ this.url = url;
41
+ this.headers = headers;
42
+ this.bodyText = bodyText;
43
+ this.name = "HTTPError";
44
+ }
45
+ toJSON() {
46
+ return {
47
+ status: this.status,
48
+ statusText: this.statusText,
49
+ url: this.url,
50
+ headers: headersToRecord(this.headers),
51
+ bodyText: this.bodyText
52
+ };
53
+ }
54
+ };
55
+ function headersToRecord(headers) {
56
+ const record = {};
57
+ headers.forEach((value, key) => {
58
+ record[key] = value;
59
+ });
60
+ return record;
61
+ }
62
+ var WebHttpClient = class {
63
+ constructor(transport) {
64
+ this.transport = transport;
65
+ }
66
+ async get(path, init) {
67
+ return this.request(path, { ...init, method: "GET" });
68
+ }
69
+ async post(path, body, init) {
70
+ return this.request(path, {
71
+ ...init,
72
+ method: "POST",
73
+ body: body ? JSON.stringify(body) : void 0,
74
+ headers: {
75
+ "Content-Type": "application/json",
76
+ ...init?.headers
77
+ }
78
+ });
79
+ }
80
+ async put(path, body, init) {
81
+ return this.request(path, {
82
+ ...init,
83
+ method: "PUT",
84
+ body: body ? JSON.stringify(body) : void 0,
85
+ headers: {
86
+ "Content-Type": "application/json",
87
+ ...init?.headers
88
+ }
89
+ });
90
+ }
91
+ async delete(path, init) {
92
+ return this.request(path, { ...init, method: "DELETE" });
93
+ }
94
+ async patch(path, body, init) {
95
+ return this.request(path, {
96
+ ...init,
97
+ method: "PATCH",
98
+ body: body ? JSON.stringify(body) : void 0,
99
+ headers: {
100
+ "Content-Type": "application/json",
101
+ ...init?.headers
102
+ }
103
+ });
104
+ }
105
+ async head(path, init) {
106
+ const response = await this.makeRequest(path, {
107
+ ...init,
108
+ method: "HEAD",
109
+ parse: "response"
110
+ });
111
+ return {
112
+ headers: headersToRecord(response.headers),
113
+ status: response.status
114
+ };
115
+ }
116
+ async request(path, init) {
117
+ return this.makeRequest(path, init);
118
+ }
119
+ async makeRequest(path, init) {
120
+ const url = this.buildUrl(path);
121
+ const hasTauriInternals = typeof window !== "undefined" && "__TAURI_INTERNALS__" in window;
122
+ const hasTauri = typeof window !== "undefined" && "__TAURI__" in window;
123
+ const isTauri = hasTauriInternals || hasTauri || this.transport.credentials === "omit";
124
+ if (isTauri) {
125
+ const headers2 = await this.buildHeaders(init?.headers);
126
+ let headersObj2;
127
+ if (headers2 instanceof Headers) {
128
+ headersObj2 = {};
129
+ headers2.forEach((value, key) => {
130
+ headersObj2[key] = value;
131
+ });
132
+ } else {
133
+ headersObj2 = headers2;
134
+ }
135
+ const requestInit2 = {};
136
+ if (init?.method && init.method !== "GET") {
137
+ requestInit2.method = init.method;
138
+ }
139
+ if (headersObj2 && Object.keys(headersObj2).length > 0) {
140
+ requestInit2.headers = headersObj2;
141
+ }
142
+ if (init?.body !== void 0 && init.body !== null) {
143
+ requestInit2.body = init.body;
144
+ }
145
+ if (this.transport.credentials !== void 0) {
146
+ requestInit2.credentials = this.transport.credentials;
147
+ }
148
+ try {
149
+ const response = await globalThis.fetch(url, requestInit2);
150
+ if (!response.ok) {
151
+ const bodyText = await this.getBodyText(response);
152
+ throw new HTTPError(
153
+ response.status,
154
+ response.statusText,
155
+ url,
156
+ response.headers,
157
+ bodyText
158
+ );
159
+ }
160
+ return this.parseResponse(response, init?.parse);
161
+ } catch (error) {
162
+ if (error instanceof HTTPError) {
163
+ throw error;
164
+ }
165
+ throw new HTTPError(
166
+ 0,
167
+ "Network Error",
168
+ url,
169
+ new Headers(),
170
+ error instanceof Error ? error.message : "Unknown error"
171
+ );
172
+ }
173
+ }
174
+ const signal = this.createAbortSignal(init);
175
+ const headers = await this.buildHeaders(init?.headers);
176
+ let headersObj;
177
+ if (headers instanceof Headers) {
178
+ headersObj = {};
179
+ headers.forEach((value, key) => {
180
+ headersObj[key] = value;
181
+ });
182
+ } else {
183
+ headersObj = headers;
184
+ }
185
+ const requestInit = {
186
+ method: init?.method || "GET",
187
+ headers: headersObj
188
+ };
189
+ if (init?.body !== void 0) {
190
+ requestInit.body = init.body;
191
+ }
192
+ if (signal) {
193
+ requestInit.signal = signal;
194
+ }
195
+ if (this.transport.credentials !== void 0) {
196
+ requestInit.credentials = this.transport.credentials;
197
+ }
198
+ if (init?.mode !== void 0) {
199
+ requestInit.mode = init.mode;
200
+ }
201
+ if (init?.cache !== void 0) {
202
+ requestInit.cache = init.cache;
203
+ }
204
+ if (init?.redirect !== void 0) {
205
+ requestInit.redirect = init.redirect;
206
+ }
207
+ if (init?.referrer !== void 0) {
208
+ requestInit.referrer = init.referrer;
209
+ }
210
+ if (init?.referrerPolicy !== void 0) {
211
+ requestInit.referrerPolicy = init.referrerPolicy;
212
+ }
213
+ if (init?.integrity !== void 0) {
214
+ requestInit.integrity = init.integrity;
215
+ }
216
+ if (init?.keepalive !== void 0) {
217
+ requestInit.keepalive = init.keepalive;
218
+ }
219
+ try {
220
+ const response = await this.transport.fetch(url, requestInit);
221
+ if (!response.ok) {
222
+ const bodyText = await this.getBodyText(response);
223
+ throw new HTTPError(
224
+ response.status,
225
+ response.statusText,
226
+ url,
227
+ response.headers,
228
+ bodyText
229
+ );
230
+ }
231
+ return this.parseResponse(response, init?.parse);
232
+ } catch (error) {
233
+ if (error instanceof HTTPError) {
234
+ throw error;
235
+ }
236
+ throw new HTTPError(
237
+ 0,
238
+ "Network Error",
239
+ url,
240
+ new Headers(),
241
+ error instanceof Error ? error.message : "Unknown error"
242
+ );
243
+ }
244
+ }
245
+ buildUrl(path) {
246
+ if (path.startsWith("http://") || path.startsWith("https://")) {
247
+ return path;
248
+ }
249
+ const baseUrl = this.transport.baseUrl;
250
+ if (path.startsWith("/")) {
251
+ const base = baseUrl.endsWith("/") ? baseUrl.slice(0, -1) : baseUrl;
252
+ return `${base}${path}`;
253
+ } else {
254
+ const base = baseUrl.endsWith("/") ? baseUrl : `${baseUrl}/`;
255
+ return `${base}${path}`;
256
+ }
257
+ }
258
+ createAbortSignal(init) {
259
+ const isTauri = typeof window !== "undefined" && "__TAURI_INTERNALS__" in window;
260
+ if (isTauri) {
261
+ return void 0;
262
+ }
263
+ const signals = [];
264
+ if (this.transport.defaultAbortSignal) {
265
+ signals.push(this.transport.defaultAbortSignal);
266
+ }
267
+ if (init?.signal) {
268
+ signals.push(init.signal);
269
+ }
270
+ const timeoutMs = init?.timeoutMs || this.transport.timeoutMs;
271
+ if (timeoutMs) {
272
+ signals.push(createTimeoutSignal(timeoutMs));
273
+ }
274
+ return signals.length > 0 ? combineSignals(signals) : void 0;
275
+ }
276
+ async buildHeaders(initHeaders) {
277
+ const headers = {
278
+ ...this.transport.defaultHeaders
279
+ };
280
+ if (this.transport.getAuthToken) {
281
+ try {
282
+ const token = await this.transport.getAuthToken();
283
+ if (token && token.trim() !== "") {
284
+ headers.Authorization = `Bearer ${token}`;
285
+ }
286
+ } catch (error) {
287
+ }
288
+ }
289
+ if (initHeaders) {
290
+ if (initHeaders instanceof Headers) {
291
+ initHeaders.forEach((value, key) => {
292
+ headers[key] = value;
293
+ });
294
+ } else if (Array.isArray(initHeaders)) {
295
+ initHeaders.forEach(([key, value]) => {
296
+ headers[key] = value;
297
+ });
298
+ } else {
299
+ Object.assign(headers, initHeaders);
300
+ }
301
+ }
302
+ return headers;
303
+ }
304
+ async parseResponse(response, parse) {
305
+ switch (parse) {
306
+ case "text":
307
+ return await response.text();
308
+ case "blob":
309
+ return await response.blob();
310
+ case "arrayBuffer":
311
+ return await response.arrayBuffer();
312
+ case "response":
313
+ return response;
314
+ case "json":
315
+ default:
316
+ return await response.json();
317
+ }
318
+ }
319
+ async getBodyText(response) {
320
+ try {
321
+ const text = await response.text();
322
+ return text.length > 65536 ? text.slice(0, 65536) + "..." : text;
323
+ } catch {
324
+ return "";
325
+ }
326
+ }
327
+ };
328
+
329
+ // src/http-client/http-factory.ts
330
+ function createHttpClient(transport) {
331
+ return new WebHttpClient(transport);
332
+ }
333
+ function createBrowserHttpClient(options) {
334
+ const transport = {
335
+ fetch: globalThis.fetch,
336
+ baseUrl: options.baseUrl,
337
+ getAuthToken: options.getAuthToken,
338
+ onTokenRefresh: options.onTokenRefresh,
339
+ defaultHeaders: options.defaultHeaders,
340
+ timeoutMs: options.timeoutMs,
341
+ credentials: options.credentials,
342
+ // No default credentials
343
+ defaultAbortSignal: options.defaultAbortSignal
344
+ };
345
+ return createHttpClient(transport);
346
+ }
347
+ function createNodeHttpClient(options) {
348
+ const fetchImpl = options.fetch ?? globalThis.fetch;
349
+ if (!fetchImpl) {
350
+ throw new Error(
351
+ "No fetch implementation available. Please provide a fetch implementation (e.g., undici.fetch) or use Node.js 18+ which has native fetch support."
352
+ );
353
+ }
354
+ const transport = {
355
+ fetch: fetchImpl,
356
+ baseUrl: options.baseUrl,
357
+ getAuthToken: options.getAuthToken,
358
+ onTokenRefresh: options.onTokenRefresh,
359
+ defaultHeaders: options.defaultHeaders,
360
+ timeoutMs: options.timeoutMs,
361
+ credentials: options.credentials,
362
+ // Node.js doesn't have default credentials
363
+ defaultAbortSignal: options.defaultAbortSignal
364
+ };
365
+ return createHttpClient(transport);
366
+ }
367
+ function createUniversalHttpClient(options) {
368
+ if (typeof window !== "undefined") {
369
+ return createBrowserHttpClient(options);
370
+ } else {
371
+ return createNodeHttpClient(options);
372
+ }
373
+ }
374
+
375
+ // src/http-client/retry.ts
376
+ function defaultRetryCondition(error, attempt) {
377
+ if (attempt <= 0) return false;
378
+ const errorWithName = error;
379
+ const name = errorWithName?.name;
380
+ if (name === "TimeoutError") return true;
381
+ if (name === "AbortError") return false;
382
+ const errorWithStatus = error;
383
+ if ("status" in errorWithStatus && typeof errorWithStatus.status === "number") {
384
+ const status = errorWithStatus.status;
385
+ return status >= 500 || status === 429;
386
+ }
387
+ if (name === "TypeError") return true;
388
+ return false;
389
+ }
390
+ function calculateDelay(attempt) {
391
+ const baseDelayMs = 250;
392
+ const delay = baseDelayMs * Math.pow(2, attempt - 1);
393
+ const jitter = (Math.random() - 0.5) * 0.4 * delay;
394
+ return Math.max(0, delay + jitter);
395
+ }
396
+ async function withRetry(fn, options = {}) {
397
+ const { attempts = 3 } = options;
398
+ let lastError;
399
+ for (let attempt = 1; attempt <= attempts; attempt++) {
400
+ try {
401
+ return await fn(attempt);
402
+ } catch (error) {
403
+ lastError = error;
404
+ if (!defaultRetryCondition(lastError, attempts - attempt)) {
405
+ throw lastError;
406
+ }
407
+ let delayMs = calculateDelay(attempt);
408
+ const errorWithHeaders = lastError;
409
+ const hdrs = errorWithHeaders.headers;
410
+ const retryAfter = hdrs?.get?.("Retry-After");
411
+ if (retryAfter) {
412
+ const seconds = parseInt(retryAfter, 10);
413
+ if (!isNaN(seconds)) {
414
+ delayMs = Math.max(delayMs, seconds * 1e3);
415
+ } else {
416
+ const date = new Date(retryAfter);
417
+ if (!isNaN(date.getTime())) {
418
+ const waitTime = Math.max(0, date.getTime() - Date.now());
419
+ delayMs = Math.max(delayMs, Math.min(waitTime, 6e4));
420
+ }
421
+ }
422
+ }
423
+ await new Promise((resolve) => setTimeout(resolve, delayMs));
424
+ }
425
+ }
426
+ throw lastError || new Error("Retry failed without error");
427
+ }
428
+ function createRetryableMethod(method, retryOptions = {}) {
429
+ return async (...args) => {
430
+ return withRetry(() => method(...args), retryOptions);
431
+ };
432
+ }
433
+
434
+ // src/auth-api/auth-client.ts
435
+ var AuthApiClient = class {
436
+ constructor(httpClient) {
437
+ this.httpClient = httpClient;
438
+ }
439
+ // Health and Status Endpoints
440
+ async getHealth() {
441
+ const response = await this.httpClient.get("/auth/health");
442
+ if (!response.data) {
443
+ throw new Error("Health response data is null");
444
+ }
445
+ return response.data;
446
+ }
447
+ async getIdentity() {
448
+ const response = await this.httpClient.get(
449
+ "/admin/identity"
450
+ );
451
+ if (!response.data) {
452
+ throw new Error("Identity response data is null");
453
+ }
454
+ return response.data;
455
+ }
456
+ async getProviders() {
457
+ const response = await this.httpClient.get(
458
+ "/auth/providers"
459
+ );
460
+ if (!response.data) {
461
+ throw new Error("Providers response data is null");
462
+ }
463
+ return response.data;
464
+ }
465
+ // Authentication Endpoints
466
+ async getLoginPage() {
467
+ return this.httpClient.get("/auth/login", { parse: "text" });
468
+ }
469
+ async generateTokens(request) {
470
+ return this.httpClient.post("/auth/token", request);
471
+ }
472
+ async refreshToken(request) {
473
+ return this.httpClient.post("/auth/refresh", request);
474
+ }
475
+ async generateMockTokens(request) {
476
+ return this.httpClient.post("/auth/mock-token", request);
477
+ }
478
+ async getChallenge() {
479
+ return this.httpClient.get("/auth/challenge");
480
+ }
481
+ async validateToken(token) {
482
+ try {
483
+ const response = await this.validateTokenGet(token);
484
+ return {
485
+ valid: response.status === 200,
486
+ headers: response.headers,
487
+ status: response.status
488
+ };
489
+ } catch (error) {
490
+ return {
491
+ valid: false,
492
+ headers: {},
493
+ status: 401
494
+ };
495
+ }
496
+ }
497
+ async validateTokenGet(token) {
498
+ const response = await this.httpClient.head("/auth/validate", {
499
+ headers: { Authorization: `Bearer ${token}` }
500
+ });
501
+ return {
502
+ status: response.status,
503
+ headers: response.headers
504
+ };
505
+ }
506
+ async isAuthed() {
507
+ return this.httpClient.get("/auth/is-authed");
508
+ }
509
+ // Token Management Endpoints
510
+ async revokeTokens(request) {
511
+ return this.httpClient.post("/admin/revoke", request);
512
+ }
513
+ // Key Management Endpoints
514
+ async listRootKeys() {
515
+ const response = await this.httpClient.get("/admin/keys");
516
+ if (!response.data) {
517
+ throw new Error("Root keys response data is null");
518
+ }
519
+ return response.data;
520
+ }
521
+ async createRootKey(request) {
522
+ return this.httpClient.post("/admin/keys", request);
523
+ }
524
+ async deleteRootKey(keyId) {
525
+ return this.httpClient.delete(`/admin/keys/${keyId}`);
526
+ }
527
+ // Client Management Endpoints
528
+ async listClientKeys() {
529
+ const response = await this.httpClient.get(
530
+ "/admin/keys/clients"
531
+ );
532
+ if (!response.data) {
533
+ throw new Error("Client keys response data is null");
534
+ }
535
+ return response.data;
536
+ }
537
+ async generateClientKey(request) {
538
+ return this.httpClient.post("/admin/client-key", request);
539
+ }
540
+ async deleteClientKey(keyId, clientId) {
541
+ return this.httpClient.delete(
542
+ `/admin/keys/${keyId}/clients/${clientId}`
543
+ );
544
+ }
545
+ // Permission Management Endpoints
546
+ async getKeyPermissions(keyId) {
547
+ return this.httpClient.get(
548
+ `/admin/keys/${keyId}/permissions`
549
+ );
550
+ }
551
+ async updateKeyPermissions(keyId, permissions) {
552
+ return this.httpClient.put(
553
+ `/admin/keys/${keyId}/permissions`,
554
+ { permissions }
555
+ );
556
+ }
557
+ };
558
+
559
+ // src/auth-api/auth-factory.ts
560
+ var MockHttpClient = class {
561
+ async get() {
562
+ throw new Error(
563
+ "HTTP client not implemented - use createAuthApiClientFromHttpClient with a real HTTP client"
564
+ );
565
+ }
566
+ async post() {
567
+ throw new Error(
568
+ "HTTP client not implemented - use createAuthApiClientFromHttpClient with a real HTTP client"
569
+ );
570
+ }
571
+ async put() {
572
+ throw new Error(
573
+ "HTTP client not implemented - use createAuthApiClientFromHttpClient with a real HTTP client"
574
+ );
575
+ }
576
+ async delete() {
577
+ throw new Error(
578
+ "HTTP client not implemented - use createAuthApiClientFromHttpClient with a real HTTP client"
579
+ );
580
+ }
581
+ async patch() {
582
+ throw new Error(
583
+ "HTTP client not implemented - use createAuthApiClientFromHttpClient with a real HTTP client"
584
+ );
585
+ }
586
+ async head() {
587
+ throw new Error(
588
+ "HTTP client not implemented - use createAuthApiClientFromHttpClient with a real HTTP client"
589
+ );
590
+ }
591
+ async request() {
592
+ throw new Error(
593
+ "HTTP client not implemented - use createAuthApiClientFromHttpClient with a real HTTP client"
594
+ );
595
+ }
596
+ };
597
+ function createBrowserAuthApiClient(_config) {
598
+ const httpClient = new MockHttpClient();
599
+ return new AuthApiClient(httpClient);
600
+ }
601
+ function createNodeAuthApiClient(_config) {
602
+ const httpClient = new MockHttpClient();
603
+ return new AuthApiClient(httpClient);
604
+ }
605
+ function createAuthApiClient(_config) {
606
+ const httpClient = new MockHttpClient();
607
+ return new AuthApiClient(httpClient);
608
+ }
609
+ function createAuthApiClientFromHttpClient(httpClient, _config) {
610
+ return new AuthApiClient(httpClient);
611
+ }
612
+
613
+ // src/admin-api/admin-client.ts
614
+ var AdminApiClient = class {
615
+ constructor(httpClient) {
616
+ this.httpClient = httpClient;
617
+ }
618
+ // Health and Status Endpoints
619
+ async healthCheck() {
620
+ const response = await this.httpClient.get("/health");
621
+ if (!response.data) {
622
+ throw new Error("Health response data is null");
623
+ }
624
+ return response.data;
625
+ }
626
+ async isAuthed() {
627
+ return this.httpClient.get("/is-authed");
628
+ }
629
+ // Application Management Endpoints
630
+ async installApplication(request) {
631
+ return this.httpClient.post(
632
+ "/install-application",
633
+ request
634
+ );
635
+ }
636
+ async installDevApplication(request) {
637
+ return this.httpClient.post(
638
+ "/install-dev-application",
639
+ request
640
+ );
641
+ }
642
+ async uninstallApplication(appId) {
643
+ return this.httpClient.delete(
644
+ `/applications/${appId}`
645
+ );
646
+ }
647
+ async listApplications() {
648
+ return this.httpClient.get("/applications");
649
+ }
650
+ async getApplication(appId) {
651
+ return this.httpClient.get(
652
+ `/applications/${appId}`
653
+ );
654
+ }
655
+ // Context Management Endpoints
656
+ async createContext(request) {
657
+ return this.httpClient.post("/contexts", request);
658
+ }
659
+ async deleteContext(contextId) {
660
+ return this.httpClient.delete(
661
+ `/contexts/${contextId}`
662
+ );
663
+ }
664
+ async getContexts() {
665
+ return this.httpClient.get("/contexts");
666
+ }
667
+ async getContext(contextId) {
668
+ return this.httpClient.get(`/contexts/${contextId}`);
669
+ }
670
+ // Blob Management Endpoints
671
+ async uploadBlob(request) {
672
+ return this.httpClient.post("/blobs", request);
673
+ }
674
+ async deleteBlob(blobId) {
675
+ return this.httpClient.delete(`/blobs/${blobId}`);
676
+ }
677
+ async listBlobs() {
678
+ return this.httpClient.get("/blobs");
679
+ }
680
+ async getBlob(blobId) {
681
+ return this.httpClient.get(`/blobs/${blobId}`);
682
+ }
683
+ // Alias Management Endpoints
684
+ async createAlias(request) {
685
+ return this.httpClient.post("/alias", request);
686
+ }
687
+ async deleteAlias(aliasId) {
688
+ return this.httpClient.delete(`/alias/${aliasId}`);
689
+ }
690
+ async listAliases() {
691
+ return this.httpClient.get("/alias");
692
+ }
693
+ async getAlias(aliasId) {
694
+ return this.httpClient.get(`/alias/${aliasId}`);
695
+ }
696
+ // Network Management Endpoints
697
+ async getNetworkPeers() {
698
+ return this.httpClient.get("/network/peers");
699
+ }
700
+ async getNetworkStats() {
701
+ return this.httpClient.get("/network/stats");
702
+ }
703
+ async getNetworkConfig() {
704
+ return this.httpClient.get("/network/config");
705
+ }
706
+ async updateNetworkConfig(request) {
707
+ return this.httpClient.put(
708
+ "/network/config",
709
+ request
710
+ );
711
+ }
712
+ async getPeersCount() {
713
+ return this.httpClient.get("/network/peers/count");
714
+ }
715
+ // System Management Endpoints
716
+ async getSystemInfo() {
717
+ return this.httpClient.get("/system/info");
718
+ }
719
+ async getSystemLogs() {
720
+ return this.httpClient.get("/system/logs");
721
+ }
722
+ async getSystemMetrics() {
723
+ return this.httpClient.get("/system/metrics");
724
+ }
725
+ async restartSystem() {
726
+ return this.httpClient.post("/system/restart");
727
+ }
728
+ async shutdownSystem() {
729
+ return this.httpClient.post("/system/shutdown");
730
+ }
731
+ };
732
+
733
+ // src/admin-api/admin-factory.ts
734
+ var MockHttpClient2 = class {
735
+ async get() {
736
+ throw new Error(
737
+ "HTTP client not implemented - use createAdminApiClientFromHttpClient with a real HTTP client"
738
+ );
739
+ }
740
+ async post() {
741
+ throw new Error(
742
+ "HTTP client not implemented - use createAdminApiClientFromHttpClient with a real HTTP client"
743
+ );
744
+ }
745
+ async put() {
746
+ throw new Error(
747
+ "HTTP client not implemented - use createAdminApiClientFromHttpClient with a real HTTP client"
748
+ );
749
+ }
750
+ async delete() {
751
+ throw new Error(
752
+ "HTTP client not implemented - use createAdminApiClientFromHttpClient with a real HTTP client"
753
+ );
754
+ }
755
+ async patch() {
756
+ throw new Error(
757
+ "HTTP client not implemented - use createAdminApiClientFromHttpClient with a real HTTP client"
758
+ );
759
+ }
760
+ async head() {
761
+ throw new Error(
762
+ "HTTP client not implemented - use createAdminApiClientFromHttpClient with a real HTTP client"
763
+ );
764
+ }
765
+ async request() {
766
+ throw new Error(
767
+ "HTTP client not implemented - use createAdminApiClientFromHttpClient with a real HTTP client"
768
+ );
769
+ }
770
+ };
771
+ function createBrowserAdminApiClient(_config) {
772
+ const httpClient = new MockHttpClient2();
773
+ return new AdminApiClient(httpClient);
774
+ }
775
+ function createNodeAdminApiClient(_config) {
776
+ const httpClient = new MockHttpClient2();
777
+ return new AdminApiClient(httpClient);
778
+ }
779
+ function createAdminApiClient(_config) {
780
+ const httpClient = new MockHttpClient2();
781
+ return new AdminApiClient(httpClient);
782
+ }
783
+ function createAdminApiClientFromHttpClient(httpClient, _config) {
784
+ return new AdminApiClient(httpClient);
785
+ }
786
+
787
+ // src/mero-js.ts
788
+ var MeroJs = class {
789
+ constructor(config) {
790
+ this.tokenData = null;
791
+ this.refreshPromise = null;
792
+ this.config = {
793
+ timeoutMs: 1e4,
794
+ ...config
795
+ };
796
+ const isTauri = typeof window !== "undefined" && "__TAURI_INTERNALS__" in window;
797
+ this.httpClient = createBrowserHttpClient({
798
+ baseUrl: this.config.baseUrl,
799
+ getAuthToken: async () => {
800
+ const token = await this.getValidToken();
801
+ return token?.access_token || "";
802
+ },
803
+ timeoutMs: this.config.timeoutMs,
804
+ credentials: this.config.requestCredentials ?? (isTauri ? "omit" : void 0)
805
+ });
806
+ this.authClient = createAuthApiClientFromHttpClient(this.httpClient, {
807
+ baseUrl: this.config.baseUrl,
808
+ getAuthToken: async () => {
809
+ const token = await this.getValidToken();
810
+ return token?.access_token || "";
811
+ },
812
+ timeoutMs: this.config.timeoutMs
813
+ });
814
+ this.adminClient = createAdminApiClientFromHttpClient(this.httpClient, {
815
+ baseUrl: this.config.baseUrl,
816
+ getAuthToken: async () => {
817
+ const token = await this.getValidToken();
818
+ return token?.access_token || "";
819
+ },
820
+ timeoutMs: this.config.timeoutMs
821
+ });
822
+ }
823
+ /**
824
+ * Get the Auth API client
825
+ */
826
+ get auth() {
827
+ return this.authClient;
828
+ }
829
+ /**
830
+ * Get the Admin API client
831
+ */
832
+ get admin() {
833
+ return this.adminClient;
834
+ }
835
+ /**
836
+ * Authenticate with the provided credentials
837
+ * This will create the root key on first use
838
+ */
839
+ async authenticate(credentials) {
840
+ const creds = credentials || this.config.credentials;
841
+ if (!creds) {
842
+ throw new Error("No credentials provided for authentication");
843
+ }
844
+ try {
845
+ const requestBody = {
846
+ auth_method: "user_password",
847
+ public_key: creds.username,
848
+ client_name: "mero-js-sdk",
849
+ permissions: ["admin"],
850
+ timestamp: Math.floor(Date.now() / 1e3),
851
+ provider_data: {
852
+ username: creds.username,
853
+ password: creds.password
854
+ }
855
+ };
856
+ const response = await this.authClient.generateTokens(requestBody);
857
+ this.tokenData = {
858
+ access_token: response.data.access_token,
859
+ refresh_token: response.data.refresh_token,
860
+ expires_at: Date.now() + 24 * 60 * 60 * 1e3
861
+ // Default to 24 hours
862
+ };
863
+ return this.tokenData;
864
+ } catch (error) {
865
+ throw new Error(
866
+ `Authentication failed: ${error instanceof Error ? error.message : "Unknown error"}`
867
+ );
868
+ }
869
+ }
870
+ /**
871
+ * Get a valid token, refreshing if necessary
872
+ */
873
+ async getValidToken() {
874
+ if (!this.tokenData) {
875
+ return null;
876
+ }
877
+ const bufferTime = 5 * 60 * 1e3;
878
+ if (Date.now() >= this.tokenData.expires_at - bufferTime) {
879
+ return await this.refreshToken();
880
+ }
881
+ return this.tokenData;
882
+ }
883
+ /**
884
+ * Refresh the access token using the refresh token
885
+ */
886
+ async refreshToken() {
887
+ if (!this.tokenData?.refresh_token) {
888
+ throw new Error("No refresh token available");
889
+ }
890
+ if (this.refreshPromise) {
891
+ return this.refreshPromise;
892
+ }
893
+ this.refreshPromise = this.performTokenRefresh();
894
+ try {
895
+ const newToken = await this.refreshPromise;
896
+ return newToken;
897
+ } finally {
898
+ this.refreshPromise = null;
899
+ }
900
+ }
901
+ /**
902
+ * Perform the actual token refresh
903
+ */
904
+ async performTokenRefresh() {
905
+ if (!this.tokenData?.refresh_token) {
906
+ throw new Error("No refresh token available");
907
+ }
908
+ try {
909
+ const response = await this.authClient.refreshToken({
910
+ access_token: this.tokenData.access_token,
911
+ refresh_token: this.tokenData.refresh_token
912
+ });
913
+ this.tokenData = {
914
+ access_token: response.data.access_token,
915
+ refresh_token: response.data.refresh_token,
916
+ expires_at: Date.now() + 24 * 60 * 60 * 1e3
917
+ // Default to 24 hours
918
+ };
919
+ return this.tokenData;
920
+ } catch (error) {
921
+ this.clearToken();
922
+ throw new Error(
923
+ `Token refresh failed: ${error instanceof Error ? error.message : "Unknown error"}`
924
+ );
925
+ }
926
+ }
927
+ /**
928
+ * Clear the current token
929
+ */
930
+ clearToken() {
931
+ this.tokenData = null;
932
+ }
933
+ /**
934
+ * Check if the SDK is authenticated
935
+ */
936
+ isAuthenticated() {
937
+ return this.tokenData !== null;
938
+ }
939
+ /**
940
+ * Get the current token data (for debugging)
941
+ */
942
+ getTokenData() {
943
+ return this.tokenData;
944
+ }
945
+ };
946
+ function createMeroJs(config) {
947
+ return new MeroJs(config);
948
+ }
949
+ export {
950
+ AdminApiClient,
951
+ AuthApiClient,
952
+ HTTPError,
953
+ MeroJs,
954
+ WebHttpClient,
955
+ combineSignals,
956
+ createAdminApiClient,
957
+ createAdminApiClientFromHttpClient,
958
+ createAuthApiClient,
959
+ createAuthApiClientFromHttpClient,
960
+ createBrowserAdminApiClient,
961
+ createBrowserAuthApiClient,
962
+ createBrowserHttpClient,
963
+ createHttpClient,
964
+ createMeroJs,
965
+ createNodeAdminApiClient,
966
+ createNodeAuthApiClient,
967
+ createNodeHttpClient,
968
+ createRetryableMethod,
969
+ createTimeoutSignal,
970
+ createUniversalHttpClient,
971
+ withRetry
972
+ };
973
+ //# sourceMappingURL=index.mjs.map