@omirion/orbit-sdk 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.
package/dist/index.js ADDED
@@ -0,0 +1,1661 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __export = (target, all) => {
3
+ for (var name in all)
4
+ __defProp(target, name, { get: all[name], enumerable: true });
5
+ };
6
+
7
+ // src/generated/core/bodySerializer.gen.ts
8
+ var serializeFormDataPair = (data, key, value) => {
9
+ if (typeof value === "string" || value instanceof Blob) {
10
+ data.append(key, value);
11
+ } else if (value instanceof Date) {
12
+ data.append(key, value.toISOString());
13
+ } else {
14
+ data.append(key, JSON.stringify(value));
15
+ }
16
+ };
17
+ var formDataBodySerializer = {
18
+ bodySerializer: (body) => {
19
+ const data = new FormData();
20
+ Object.entries(body).forEach(([key, value]) => {
21
+ if (value === void 0 || value === null) {
22
+ return;
23
+ }
24
+ if (Array.isArray(value)) {
25
+ value.forEach((v) => serializeFormDataPair(data, key, v));
26
+ } else {
27
+ serializeFormDataPair(data, key, value);
28
+ }
29
+ });
30
+ return data;
31
+ }
32
+ };
33
+ var jsonBodySerializer = {
34
+ bodySerializer: (body) => JSON.stringify(body, (_key, value) => typeof value === "bigint" ? value.toString() : value)
35
+ };
36
+
37
+ // src/generated/core/serverSentEvents.gen.ts
38
+ function createSseClient({
39
+ onRequest,
40
+ onSseError,
41
+ onSseEvent,
42
+ responseTransformer,
43
+ responseValidator,
44
+ sseDefaultRetryDelay,
45
+ sseMaxRetryAttempts,
46
+ sseMaxRetryDelay,
47
+ sseSleepFn,
48
+ url,
49
+ ...options
50
+ }) {
51
+ let lastEventId;
52
+ const sleep = sseSleepFn ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
53
+ const createStream = async function* () {
54
+ let retryDelay = sseDefaultRetryDelay ?? 3e3;
55
+ let attempt = 0;
56
+ const signal = options.signal ?? new AbortController().signal;
57
+ while (true) {
58
+ if (signal.aborted) break;
59
+ attempt++;
60
+ const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers);
61
+ if (lastEventId !== void 0) {
62
+ headers.set("Last-Event-ID", lastEventId);
63
+ }
64
+ try {
65
+ const requestInit = {
66
+ redirect: "follow",
67
+ ...options,
68
+ body: options.serializedBody,
69
+ headers,
70
+ signal
71
+ };
72
+ let request = new Request(url, requestInit);
73
+ if (onRequest) {
74
+ request = await onRequest(url, requestInit);
75
+ }
76
+ const _fetch = options.fetch ?? globalThis.fetch;
77
+ const response = await _fetch(request);
78
+ if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`);
79
+ if (!response.body) throw new Error("No body in SSE response");
80
+ const reader = response.body.pipeThrough(new TextDecoderStream()).getReader();
81
+ let buffer = "";
82
+ const abortHandler = () => {
83
+ try {
84
+ reader.cancel();
85
+ } catch {
86
+ }
87
+ };
88
+ signal.addEventListener("abort", abortHandler);
89
+ try {
90
+ while (true) {
91
+ const { done, value } = await reader.read();
92
+ if (done) break;
93
+ buffer += value;
94
+ buffer = buffer.replace(/\r\n?/g, "\n");
95
+ const chunks = buffer.split("\n\n");
96
+ buffer = chunks.pop() ?? "";
97
+ for (const chunk of chunks) {
98
+ const lines = chunk.split("\n");
99
+ const dataLines = [];
100
+ let eventName;
101
+ for (const line of lines) {
102
+ if (line.startsWith("data:")) {
103
+ dataLines.push(line.replace(/^data:\s*/, ""));
104
+ } else if (line.startsWith("event:")) {
105
+ eventName = line.replace(/^event:\s*/, "");
106
+ } else if (line.startsWith("id:")) {
107
+ lastEventId = line.replace(/^id:\s*/, "");
108
+ } else if (line.startsWith("retry:")) {
109
+ const parsed = Number.parseInt(line.replace(/^retry:\s*/, ""), 10);
110
+ if (!Number.isNaN(parsed)) {
111
+ retryDelay = parsed;
112
+ }
113
+ }
114
+ }
115
+ let data;
116
+ let parsedJson = false;
117
+ if (dataLines.length) {
118
+ const rawData = dataLines.join("\n");
119
+ try {
120
+ data = JSON.parse(rawData);
121
+ parsedJson = true;
122
+ } catch {
123
+ data = rawData;
124
+ }
125
+ }
126
+ if (parsedJson) {
127
+ if (responseValidator) {
128
+ await responseValidator(data);
129
+ }
130
+ if (responseTransformer) {
131
+ data = await responseTransformer(data);
132
+ }
133
+ }
134
+ onSseEvent?.({
135
+ data,
136
+ event: eventName,
137
+ id: lastEventId,
138
+ retry: retryDelay
139
+ });
140
+ if (dataLines.length) {
141
+ yield data;
142
+ }
143
+ }
144
+ }
145
+ } finally {
146
+ signal.removeEventListener("abort", abortHandler);
147
+ reader.releaseLock();
148
+ }
149
+ break;
150
+ } catch (error) {
151
+ onSseError?.(error);
152
+ if (sseMaxRetryAttempts !== void 0 && attempt >= sseMaxRetryAttempts) {
153
+ break;
154
+ }
155
+ const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 3e4);
156
+ await sleep(backoff);
157
+ }
158
+ }
159
+ };
160
+ const stream = createStream();
161
+ return { stream };
162
+ }
163
+
164
+ // src/generated/core/pathSerializer.gen.ts
165
+ var separatorArrayExplode = (style) => {
166
+ switch (style) {
167
+ case "label":
168
+ return ".";
169
+ case "matrix":
170
+ return ";";
171
+ case "simple":
172
+ return ",";
173
+ default:
174
+ return "&";
175
+ }
176
+ };
177
+ var separatorArrayNoExplode = (style) => {
178
+ switch (style) {
179
+ case "form":
180
+ return ",";
181
+ case "pipeDelimited":
182
+ return "|";
183
+ case "spaceDelimited":
184
+ return "%20";
185
+ default:
186
+ return ",";
187
+ }
188
+ };
189
+ var separatorObjectExplode = (style) => {
190
+ switch (style) {
191
+ case "label":
192
+ return ".";
193
+ case "matrix":
194
+ return ";";
195
+ case "simple":
196
+ return ",";
197
+ default:
198
+ return "&";
199
+ }
200
+ };
201
+ var serializeArrayParam = ({
202
+ allowReserved,
203
+ explode,
204
+ name,
205
+ style,
206
+ value
207
+ }) => {
208
+ if (!explode) {
209
+ const joinedValues2 = (allowReserved ? value : value.map((v) => encodeURIComponent(v))).join(separatorArrayNoExplode(style));
210
+ switch (style) {
211
+ case "label":
212
+ return `.${joinedValues2}`;
213
+ case "matrix":
214
+ return `;${name}=${joinedValues2}`;
215
+ case "simple":
216
+ return joinedValues2;
217
+ default:
218
+ return `${name}=${joinedValues2}`;
219
+ }
220
+ }
221
+ const separator = separatorArrayExplode(style);
222
+ const joinedValues = value.map((v) => {
223
+ if (style === "label" || style === "simple") {
224
+ return allowReserved ? v : encodeURIComponent(v);
225
+ }
226
+ return serializePrimitiveParam({
227
+ allowReserved,
228
+ name,
229
+ value: v
230
+ });
231
+ }).join(separator);
232
+ return style === "label" || style === "matrix" ? separator + joinedValues : joinedValues;
233
+ };
234
+ var serializePrimitiveParam = ({
235
+ allowReserved,
236
+ name,
237
+ value
238
+ }) => {
239
+ if (value === void 0 || value === null) {
240
+ return "";
241
+ }
242
+ if (typeof value === "object") {
243
+ throw new Error(
244
+ "Deeply-nested arrays/objects aren\u2019t supported. Provide your own `querySerializer()` to handle these."
245
+ );
246
+ }
247
+ return `${name}=${allowReserved ? value : encodeURIComponent(value)}`;
248
+ };
249
+ var serializeObjectParam = ({
250
+ allowReserved,
251
+ explode,
252
+ name,
253
+ style,
254
+ value,
255
+ valueOnly
256
+ }) => {
257
+ if (value instanceof Date) {
258
+ return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`;
259
+ }
260
+ if (style !== "deepObject" && !explode) {
261
+ let values = [];
262
+ Object.entries(value).forEach(([key, v]) => {
263
+ values = [...values, key, allowReserved ? v : encodeURIComponent(v)];
264
+ });
265
+ const joinedValues2 = values.join(",");
266
+ switch (style) {
267
+ case "form":
268
+ return `${name}=${joinedValues2}`;
269
+ case "label":
270
+ return `.${joinedValues2}`;
271
+ case "matrix":
272
+ return `;${name}=${joinedValues2}`;
273
+ default:
274
+ return joinedValues2;
275
+ }
276
+ }
277
+ const separator = separatorObjectExplode(style);
278
+ const joinedValues = Object.entries(value).map(
279
+ ([key, v]) => serializePrimitiveParam({
280
+ allowReserved,
281
+ name: style === "deepObject" ? `${name}[${key}]` : key,
282
+ value: v
283
+ })
284
+ ).join(separator);
285
+ return style === "label" || style === "matrix" ? separator + joinedValues : joinedValues;
286
+ };
287
+
288
+ // src/generated/core/utils.gen.ts
289
+ var PATH_PARAM_RE = /\{[^{}]+\}/g;
290
+ var defaultPathSerializer = ({ path, url: _url }) => {
291
+ let url = _url;
292
+ const matches = _url.match(PATH_PARAM_RE);
293
+ if (matches) {
294
+ for (const match of matches) {
295
+ let explode = false;
296
+ let name = match.substring(1, match.length - 1);
297
+ let style = "simple";
298
+ if (name.endsWith("*")) {
299
+ explode = true;
300
+ name = name.substring(0, name.length - 1);
301
+ }
302
+ if (name.startsWith(".")) {
303
+ name = name.substring(1);
304
+ style = "label";
305
+ } else if (name.startsWith(";")) {
306
+ name = name.substring(1);
307
+ style = "matrix";
308
+ }
309
+ const value = path[name];
310
+ if (value === void 0 || value === null) {
311
+ continue;
312
+ }
313
+ if (Array.isArray(value)) {
314
+ url = url.replace(match, serializeArrayParam({ explode, name, style, value }));
315
+ continue;
316
+ }
317
+ if (typeof value === "object") {
318
+ url = url.replace(
319
+ match,
320
+ serializeObjectParam({
321
+ explode,
322
+ name,
323
+ style,
324
+ value,
325
+ valueOnly: true
326
+ })
327
+ );
328
+ continue;
329
+ }
330
+ if (style === "matrix") {
331
+ url = url.replace(
332
+ match,
333
+ `;${serializePrimitiveParam({
334
+ name,
335
+ value
336
+ })}`
337
+ );
338
+ continue;
339
+ }
340
+ const replaceValue = encodeURIComponent(
341
+ style === "label" ? `.${value}` : value
342
+ );
343
+ url = url.replace(match, replaceValue);
344
+ }
345
+ }
346
+ return url;
347
+ };
348
+ var getUrl = ({
349
+ baseUrl,
350
+ path,
351
+ query,
352
+ querySerializer,
353
+ url: _url
354
+ }) => {
355
+ const pathUrl = _url.startsWith("/") ? _url : `/${_url}`;
356
+ let url = (baseUrl ?? "") + pathUrl;
357
+ if (path) {
358
+ url = defaultPathSerializer({ path, url });
359
+ }
360
+ let search = query ? querySerializer(query) : "";
361
+ if (search.startsWith("?")) {
362
+ search = search.substring(1);
363
+ }
364
+ if (search) {
365
+ url += `?${search}`;
366
+ }
367
+ return url;
368
+ };
369
+ function getValidRequestBody(options) {
370
+ const hasBody = options.body !== void 0;
371
+ const isSerializedBody = hasBody && options.bodySerializer;
372
+ if (isSerializedBody) {
373
+ if ("serializedBody" in options) {
374
+ const hasSerializedBody = options.serializedBody !== void 0 && options.serializedBody !== "";
375
+ return hasSerializedBody ? options.serializedBody : null;
376
+ }
377
+ return options.body !== "" ? options.body : null;
378
+ }
379
+ if (hasBody) {
380
+ return options.body;
381
+ }
382
+ return void 0;
383
+ }
384
+
385
+ // src/generated/core/auth.gen.ts
386
+ var getAuthToken = async (auth, callback) => {
387
+ const token = typeof callback === "function" ? await callback(auth) : callback;
388
+ if (!token) {
389
+ return;
390
+ }
391
+ if (auth.scheme === "bearer") {
392
+ return `Bearer ${token}`;
393
+ }
394
+ if (auth.scheme === "basic") {
395
+ return `Basic ${btoa(token)}`;
396
+ }
397
+ return token;
398
+ };
399
+
400
+ // src/generated/client/utils.gen.ts
401
+ var createQuerySerializer = ({
402
+ parameters = {},
403
+ ...args
404
+ } = {}) => {
405
+ const querySerializer = (queryParams) => {
406
+ const search = [];
407
+ if (queryParams && typeof queryParams === "object") {
408
+ for (const name in queryParams) {
409
+ const value = queryParams[name];
410
+ if (value === void 0 || value === null) {
411
+ continue;
412
+ }
413
+ const options = parameters[name] || args;
414
+ if (Array.isArray(value)) {
415
+ const serializedArray = serializeArrayParam({
416
+ allowReserved: options.allowReserved,
417
+ explode: true,
418
+ name,
419
+ style: "form",
420
+ value,
421
+ ...options.array
422
+ });
423
+ if (serializedArray) search.push(serializedArray);
424
+ } else if (typeof value === "object") {
425
+ const serializedObject = serializeObjectParam({
426
+ allowReserved: options.allowReserved,
427
+ explode: true,
428
+ name,
429
+ style: "deepObject",
430
+ value,
431
+ ...options.object
432
+ });
433
+ if (serializedObject) search.push(serializedObject);
434
+ } else {
435
+ const serializedPrimitive = serializePrimitiveParam({
436
+ allowReserved: options.allowReserved,
437
+ name,
438
+ value
439
+ });
440
+ if (serializedPrimitive) search.push(serializedPrimitive);
441
+ }
442
+ }
443
+ }
444
+ return search.join("&");
445
+ };
446
+ return querySerializer;
447
+ };
448
+ var getParseAs = (contentType) => {
449
+ if (!contentType) {
450
+ return "stream";
451
+ }
452
+ const cleanContent = contentType.split(";")[0]?.trim();
453
+ if (!cleanContent) {
454
+ return;
455
+ }
456
+ if (cleanContent.startsWith("application/json") || cleanContent.endsWith("+json")) {
457
+ return "json";
458
+ }
459
+ if (cleanContent === "multipart/form-data") {
460
+ return "formData";
461
+ }
462
+ if (["application/", "audio/", "image/", "video/"].some((type) => cleanContent.startsWith(type))) {
463
+ return "blob";
464
+ }
465
+ if (cleanContent.startsWith("text/")) {
466
+ return "text";
467
+ }
468
+ return;
469
+ };
470
+ var checkForExistence = (options, name) => {
471
+ if (!name) {
472
+ return false;
473
+ }
474
+ if (options.headers.has(name) || options.query?.[name] || options.headers.get("Cookie")?.includes(`${name}=`)) {
475
+ return true;
476
+ }
477
+ return false;
478
+ };
479
+ async function setAuthParams(options) {
480
+ for (const auth of options.security ?? []) {
481
+ if (checkForExistence(options, auth.name)) {
482
+ continue;
483
+ }
484
+ const token = await getAuthToken(auth, options.auth);
485
+ if (!token) {
486
+ continue;
487
+ }
488
+ const name = auth.name ?? "Authorization";
489
+ switch (auth.in) {
490
+ case "query":
491
+ if (!options.query) {
492
+ options.query = {};
493
+ }
494
+ options.query[name] = token;
495
+ break;
496
+ case "cookie":
497
+ options.headers.append("Cookie", `${name}=${token}`);
498
+ break;
499
+ case "header":
500
+ default:
501
+ options.headers.set(name, token);
502
+ break;
503
+ }
504
+ }
505
+ }
506
+ var buildUrl = (options) => getUrl({
507
+ baseUrl: options.baseUrl,
508
+ path: options.path,
509
+ query: options.query,
510
+ querySerializer: typeof options.querySerializer === "function" ? options.querySerializer : createQuerySerializer(options.querySerializer),
511
+ url: options.url
512
+ });
513
+ var mergeConfigs = (a, b) => {
514
+ const config = { ...a, ...b };
515
+ if (config.baseUrl?.endsWith("/")) {
516
+ config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1);
517
+ }
518
+ config.headers = mergeHeaders(a.headers, b.headers);
519
+ return config;
520
+ };
521
+ var headersEntries = (headers) => {
522
+ const entries = [];
523
+ headers.forEach((value, key) => {
524
+ entries.push([key, value]);
525
+ });
526
+ return entries;
527
+ };
528
+ var mergeHeaders = (...headers) => {
529
+ const mergedHeaders = new Headers();
530
+ for (const header of headers) {
531
+ if (!header) {
532
+ continue;
533
+ }
534
+ const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header);
535
+ for (const [key, value] of iterator) {
536
+ if (value === null) {
537
+ mergedHeaders.delete(key);
538
+ } else if (Array.isArray(value)) {
539
+ for (const v of value) {
540
+ mergedHeaders.append(key, v);
541
+ }
542
+ } else if (value !== void 0) {
543
+ mergedHeaders.set(
544
+ key,
545
+ typeof value === "object" ? JSON.stringify(value) : value
546
+ );
547
+ }
548
+ }
549
+ }
550
+ return mergedHeaders;
551
+ };
552
+ var Interceptors = class {
553
+ fns = [];
554
+ clear() {
555
+ this.fns = [];
556
+ }
557
+ eject(id) {
558
+ const index = this.getInterceptorIndex(id);
559
+ if (this.fns[index]) {
560
+ this.fns[index] = null;
561
+ }
562
+ }
563
+ exists(id) {
564
+ const index = this.getInterceptorIndex(id);
565
+ return Boolean(this.fns[index]);
566
+ }
567
+ getInterceptorIndex(id) {
568
+ if (typeof id === "number") {
569
+ return this.fns[id] ? id : -1;
570
+ }
571
+ return this.fns.indexOf(id);
572
+ }
573
+ update(id, fn) {
574
+ const index = this.getInterceptorIndex(id);
575
+ if (this.fns[index]) {
576
+ this.fns[index] = fn;
577
+ return id;
578
+ }
579
+ return false;
580
+ }
581
+ use(fn) {
582
+ this.fns.push(fn);
583
+ return this.fns.length - 1;
584
+ }
585
+ };
586
+ var createInterceptors = () => ({
587
+ error: new Interceptors(),
588
+ request: new Interceptors(),
589
+ response: new Interceptors()
590
+ });
591
+ var defaultQuerySerializer = createQuerySerializer({
592
+ allowReserved: false,
593
+ array: {
594
+ explode: true,
595
+ style: "form"
596
+ },
597
+ object: {
598
+ explode: true,
599
+ style: "deepObject"
600
+ }
601
+ });
602
+ var defaultHeaders = {
603
+ "Content-Type": "application/json"
604
+ };
605
+ var createConfig = (override = {}) => ({
606
+ ...jsonBodySerializer,
607
+ headers: defaultHeaders,
608
+ parseAs: "auto",
609
+ querySerializer: defaultQuerySerializer,
610
+ ...override
611
+ });
612
+
613
+ // src/generated/client/client.gen.ts
614
+ var createClient = (config = {}) => {
615
+ let _config = mergeConfigs(createConfig(), config);
616
+ const getConfig = () => ({ ..._config });
617
+ const setConfig = (config2) => {
618
+ _config = mergeConfigs(_config, config2);
619
+ return getConfig();
620
+ };
621
+ const interceptors = createInterceptors();
622
+ const beforeRequest = async (options) => {
623
+ const opts = {
624
+ ..._config,
625
+ ...options,
626
+ fetch: options.fetch ?? _config.fetch ?? globalThis.fetch,
627
+ headers: mergeHeaders(_config.headers, options.headers),
628
+ serializedBody: void 0
629
+ };
630
+ if (opts.security) {
631
+ await setAuthParams(opts);
632
+ }
633
+ if (opts.requestValidator) {
634
+ await opts.requestValidator(opts);
635
+ }
636
+ if (opts.body !== void 0 && opts.bodySerializer) {
637
+ opts.serializedBody = opts.bodySerializer(opts.body);
638
+ }
639
+ if (opts.body === void 0 || opts.serializedBody === "") {
640
+ opts.headers.delete("Content-Type");
641
+ }
642
+ const resolvedOpts = opts;
643
+ const url = buildUrl(resolvedOpts);
644
+ return { opts: resolvedOpts, url };
645
+ };
646
+ const request = async (options) => {
647
+ const throwOnError = options.throwOnError ?? _config.throwOnError;
648
+ const responseStyle = options.responseStyle ?? _config.responseStyle;
649
+ let request2;
650
+ let response;
651
+ try {
652
+ const { opts, url } = await beforeRequest(options);
653
+ const requestInit = {
654
+ redirect: "follow",
655
+ ...opts,
656
+ body: getValidRequestBody(opts)
657
+ };
658
+ request2 = new Request(url, requestInit);
659
+ for (const fn of interceptors.request.fns) {
660
+ if (fn) {
661
+ request2 = await fn(request2, opts);
662
+ }
663
+ }
664
+ const _fetch = opts.fetch;
665
+ response = await _fetch(request2);
666
+ for (const fn of interceptors.response.fns) {
667
+ if (fn) {
668
+ response = await fn(response, request2, opts);
669
+ }
670
+ }
671
+ const result = {
672
+ request: request2,
673
+ response
674
+ };
675
+ if (response.ok) {
676
+ const parseAs = (opts.parseAs === "auto" ? getParseAs(response.headers.get("Content-Type")) : opts.parseAs) ?? "json";
677
+ if (response.status === 204 || response.headers.get("Content-Length") === "0") {
678
+ let emptyData;
679
+ switch (parseAs) {
680
+ case "arrayBuffer":
681
+ case "blob":
682
+ case "text":
683
+ emptyData = await response[parseAs]();
684
+ break;
685
+ case "formData":
686
+ emptyData = new FormData();
687
+ break;
688
+ case "stream":
689
+ emptyData = response.body;
690
+ break;
691
+ case "json":
692
+ default:
693
+ emptyData = {};
694
+ break;
695
+ }
696
+ return opts.responseStyle === "data" ? emptyData : {
697
+ data: emptyData,
698
+ ...result
699
+ };
700
+ }
701
+ let data;
702
+ switch (parseAs) {
703
+ case "arrayBuffer":
704
+ case "blob":
705
+ case "formData":
706
+ case "text":
707
+ data = await response[parseAs]();
708
+ break;
709
+ case "json": {
710
+ const text = await response.text();
711
+ data = text ? JSON.parse(text) : {};
712
+ break;
713
+ }
714
+ case "stream":
715
+ return opts.responseStyle === "data" ? response.body : {
716
+ data: response.body,
717
+ ...result
718
+ };
719
+ }
720
+ if (parseAs === "json") {
721
+ if (opts.responseValidator) {
722
+ await opts.responseValidator(data);
723
+ }
724
+ if (opts.responseTransformer) {
725
+ data = await opts.responseTransformer(data);
726
+ }
727
+ }
728
+ return opts.responseStyle === "data" ? data : {
729
+ data,
730
+ ...result
731
+ };
732
+ }
733
+ const textError = await response.text();
734
+ let jsonError;
735
+ try {
736
+ jsonError = JSON.parse(textError);
737
+ } catch {
738
+ }
739
+ throw jsonError ?? textError;
740
+ } catch (error) {
741
+ let finalError = error;
742
+ for (const fn of interceptors.error.fns) {
743
+ if (fn) {
744
+ finalError = await fn(finalError, response, request2, options);
745
+ }
746
+ }
747
+ finalError = finalError || {};
748
+ if (throwOnError) {
749
+ throw finalError;
750
+ }
751
+ return responseStyle === "data" ? void 0 : {
752
+ error: finalError,
753
+ request: request2,
754
+ response
755
+ };
756
+ }
757
+ };
758
+ const makeMethodFn = (method) => (options) => request({ ...options, method });
759
+ const makeSseFn = (method) => async (options) => {
760
+ const { opts, url } = await beforeRequest(options);
761
+ return createSseClient({
762
+ ...opts,
763
+ body: opts.body,
764
+ method,
765
+ onRequest: async (url2, init) => {
766
+ let request2 = new Request(url2, init);
767
+ for (const fn of interceptors.request.fns) {
768
+ if (fn) {
769
+ request2 = await fn(request2, opts);
770
+ }
771
+ }
772
+ return request2;
773
+ },
774
+ serializedBody: getValidRequestBody(opts),
775
+ url
776
+ });
777
+ };
778
+ const _buildUrl = (options) => buildUrl({ ..._config, ...options });
779
+ return {
780
+ buildUrl: _buildUrl,
781
+ connect: makeMethodFn("CONNECT"),
782
+ delete: makeMethodFn("DELETE"),
783
+ get: makeMethodFn("GET"),
784
+ getConfig,
785
+ head: makeMethodFn("HEAD"),
786
+ interceptors,
787
+ options: makeMethodFn("OPTIONS"),
788
+ patch: makeMethodFn("PATCH"),
789
+ post: makeMethodFn("POST"),
790
+ put: makeMethodFn("PUT"),
791
+ request,
792
+ setConfig,
793
+ sse: {
794
+ connect: makeSseFn("CONNECT"),
795
+ delete: makeSseFn("DELETE"),
796
+ get: makeSseFn("GET"),
797
+ head: makeSseFn("HEAD"),
798
+ options: makeSseFn("OPTIONS"),
799
+ patch: makeSseFn("PATCH"),
800
+ post: makeSseFn("POST"),
801
+ put: makeSseFn("PUT"),
802
+ trace: makeSseFn("TRACE")
803
+ },
804
+ trace: makeMethodFn("TRACE")
805
+ };
806
+ };
807
+
808
+ // src/generated/client.gen.ts
809
+ var client = createClient(createConfig({ baseUrl: "https://orbit.omirion.com" }));
810
+
811
+ // src/generated/sdk.gen.ts
812
+ var getIdentity = (options) => (options?.client ?? client).get({
813
+ security: [{ scheme: "bearer", type: "http" }],
814
+ url: "/api/v1/me",
815
+ ...options
816
+ });
817
+ var listProjects = (options) => (options?.client ?? client).get({
818
+ security: [{ scheme: "bearer", type: "http" }],
819
+ url: "/api/v1/projects",
820
+ ...options
821
+ });
822
+ var getProject = (options) => (options.client ?? client).get({
823
+ security: [{ scheme: "bearer", type: "http" }],
824
+ url: "/api/v1/projects/{id}",
825
+ ...options
826
+ });
827
+ var createProjectAppToken = (options) => (options.client ?? client).post({
828
+ security: [{ scheme: "bearer", type: "http" }],
829
+ url: "/api/v1/projects/{id}/app-token",
830
+ ...options
831
+ });
832
+ var rotateProjectAppToken = (options) => (options.client ?? client).post({
833
+ security: [{ scheme: "bearer", type: "http" }],
834
+ url: "/api/v1/projects/{id}/app-token/rotate",
835
+ ...options
836
+ });
837
+ var listDevices = (options) => (options?.client ?? client).get({
838
+ security: [{ scheme: "bearer", type: "http" }],
839
+ url: "/api/v1/devices",
840
+ ...options
841
+ });
842
+ var deleteDevice = (options) => (options.client ?? client).delete({
843
+ security: [{ scheme: "bearer", type: "http" }],
844
+ url: "/api/v1/devices/{id}",
845
+ ...options
846
+ });
847
+ var getDevice = (options) => (options.client ?? client).get({
848
+ security: [{ scheme: "bearer", type: "http" }],
849
+ url: "/api/v1/devices/{id}",
850
+ ...options
851
+ });
852
+ var resetDeviceToken = (options) => (options.client ?? client).post({
853
+ security: [{ scheme: "bearer", type: "http" }],
854
+ url: "/api/v1/devices/{id}/token/reset",
855
+ ...options
856
+ });
857
+ var getLatestTelemetry = (options) => (options.client ?? client).get({
858
+ security: [{ scheme: "bearer", type: "http" }],
859
+ url: "/api/v1/devices/{id}/telemetry/latest",
860
+ ...options
861
+ });
862
+ var getTelemetryHistory = (options) => (options.client ?? client).get({
863
+ security: [{ scheme: "bearer", type: "http" }],
864
+ url: "/api/v1/devices/{id}/telemetry",
865
+ ...options
866
+ });
867
+ var getTelemetryManifest = (options) => (options.client ?? client).get({
868
+ security: [{ scheme: "bearer", type: "http" }],
869
+ url: "/api/v1/devices/{id}/telemetry/manifest",
870
+ ...options
871
+ });
872
+ var listAdmissions = (options) => (options?.client ?? client).get({
873
+ security: [{ scheme: "bearer", type: "http" }],
874
+ url: "/api/v1/admissions",
875
+ ...options
876
+ });
877
+ var getAdmission = (options) => (options.client ?? client).get({
878
+ security: [{ scheme: "bearer", type: "http" }],
879
+ url: "/api/v1/admissions/{id}",
880
+ ...options
881
+ });
882
+ var acceptAdmission = (options) => (options.client ?? client).post({
883
+ security: [{ scheme: "bearer", type: "http" }],
884
+ url: "/api/v1/admissions/{id}/accept",
885
+ ...options,
886
+ headers: {
887
+ "Content-Type": "application/json",
888
+ ...options.headers
889
+ }
890
+ });
891
+ var rejectAdmission = (options) => (options.client ?? client).post({
892
+ security: [{ scheme: "bearer", type: "http" }],
893
+ url: "/api/v1/admissions/{id}/reject",
894
+ ...options
895
+ });
896
+ var dismissAdmission = (options) => (options.client ?? client).post({
897
+ security: [{ scheme: "bearer", type: "http" }],
898
+ url: "/api/v1/admissions/{id}/dismiss",
899
+ ...options
900
+ });
901
+ var uploadFirmware = (options) => (options?.client ?? client).post({
902
+ ...formDataBodySerializer,
903
+ security: [{ scheme: "bearer", type: "http" }],
904
+ url: "/api/v1/firmware/upload",
905
+ ...options,
906
+ headers: {
907
+ "Content-Type": null,
908
+ ...options?.headers
909
+ }
910
+ });
911
+ var listFirmwareBundles = (options) => (options?.client ?? client).get({
912
+ security: [{ scheme: "bearer", type: "http" }],
913
+ url: "/api/v1/firmware/bundles",
914
+ ...options
915
+ });
916
+ var deleteFirmwareBundle = (options) => (options.client ?? client).delete({
917
+ security: [{ scheme: "bearer", type: "http" }],
918
+ url: "/api/v1/firmware/bundles/{id}",
919
+ ...options
920
+ });
921
+ var getFirmwareBundle = (options) => (options.client ?? client).get({
922
+ security: [{ scheme: "bearer", type: "http" }],
923
+ url: "/api/v1/firmware/bundles/{id}",
924
+ ...options
925
+ });
926
+ var listFirmwareDeployments = (options) => (options?.client ?? client).get({
927
+ security: [{ scheme: "bearer", type: "http" }],
928
+ url: "/api/v1/firmware/deployments",
929
+ ...options
930
+ });
931
+ var triggerFirmwareDeployment = (options) => (options?.client ?? client).post({
932
+ security: [{ scheme: "bearer", type: "http" }],
933
+ url: "/api/v1/firmware/deployments",
934
+ ...options,
935
+ headers: {
936
+ "Content-Type": "application/json",
937
+ ...options?.headers
938
+ }
939
+ });
940
+ var getFirmwareDeployment = (options) => (options.client ?? client).get({
941
+ security: [{ scheme: "bearer", type: "http" }],
942
+ url: "/api/v1/firmware/deployments/{id}",
943
+ ...options
944
+ });
945
+ var cancelFirmwareDeployment = (options) => (options.client ?? client).post({
946
+ security: [{ scheme: "bearer", type: "http" }],
947
+ url: "/api/v1/firmware/deployments/{id}/cancel",
948
+ ...options,
949
+ headers: {
950
+ "Content-Type": "application/json",
951
+ ...options.headers
952
+ }
953
+ });
954
+ var rollbackFirmwareDeployment = (options) => (options.client ?? client).post({
955
+ security: [{ scheme: "bearer", type: "http" }],
956
+ url: "/api/v1/firmware/deployments/{id}/rollback",
957
+ ...options,
958
+ headers: {
959
+ "Content-Type": "application/json",
960
+ ...options.headers
961
+ }
962
+ });
963
+ var execDeviceCommand = (options) => (options.client ?? client).post({
964
+ security: [{ scheme: "bearer", type: "http" }],
965
+ url: "/api/v1/devices/{id}/command",
966
+ ...options,
967
+ headers: {
968
+ "Content-Type": "application/json",
969
+ ...options.headers
970
+ }
971
+ });
972
+ var getDeviceCommandInvocation = (options) => (options.client ?? client).get({
973
+ security: [{ scheme: "bearer", type: "http" }],
974
+ url: "/api/v1/devices/{id}/commands/{invocationId}",
975
+ ...options
976
+ });
977
+ var getDeviceCommands = (options) => (options.client ?? client).get({
978
+ security: [{ scheme: "bearer", type: "http" }],
979
+ url: "/api/v1/devices/{id}/commands",
980
+ ...options
981
+ });
982
+ var deleteCommandManifest = (options) => (options.client ?? client).delete({
983
+ security: [{ scheme: "bearer", type: "http" }],
984
+ url: "/api/v1/projects/{projectId}/device-types/{slug}/commands",
985
+ ...options
986
+ });
987
+ var getCommandManifest = (options) => (options.client ?? client).get({
988
+ security: [{ scheme: "bearer", type: "http" }],
989
+ url: "/api/v1/projects/{projectId}/device-types/{slug}/commands",
990
+ ...options
991
+ });
992
+ var updateCommandManifest = (options) => (options.client ?? client).put({
993
+ security: [{ scheme: "bearer", type: "http" }],
994
+ url: "/api/v1/projects/{projectId}/device-types/{slug}/commands",
995
+ ...options,
996
+ headers: {
997
+ "Content-Type": "application/json",
998
+ ...options.headers
999
+ }
1000
+ });
1001
+ var listDeviceTypes = (options) => (options.client ?? client).get({
1002
+ security: [{ scheme: "bearer", type: "http" }],
1003
+ url: "/api/v1/projects/{projectId}/device-types",
1004
+ ...options
1005
+ });
1006
+ var createDeviceType = (options) => (options.client ?? client).post({
1007
+ security: [{ scheme: "bearer", type: "http" }],
1008
+ url: "/api/v1/projects/{projectId}/device-types",
1009
+ ...options,
1010
+ headers: {
1011
+ "Content-Type": "application/json",
1012
+ ...options.headers
1013
+ }
1014
+ });
1015
+ var deleteDeviceType = (options) => (options.client ?? client).delete({
1016
+ security: [{ scheme: "bearer", type: "http" }],
1017
+ url: "/api/v1/projects/{projectId}/device-types/{slug}",
1018
+ ...options
1019
+ });
1020
+ var getDeviceType = (options) => (options.client ?? client).get({
1021
+ security: [{ scheme: "bearer", type: "http" }],
1022
+ url: "/api/v1/projects/{projectId}/device-types/{slug}",
1023
+ ...options
1024
+ });
1025
+ var updateDeviceType = (options) => (options.client ?? client).patch({
1026
+ security: [{ scheme: "bearer", type: "http" }],
1027
+ url: "/api/v1/projects/{projectId}/device-types/{slug}",
1028
+ ...options,
1029
+ headers: {
1030
+ "Content-Type": "application/json",
1031
+ ...options.headers
1032
+ }
1033
+ });
1034
+ var listWebhooks = (options) => (options?.client ?? client).get({
1035
+ security: [{ scheme: "bearer", type: "http" }],
1036
+ url: "/api/v1/webhooks",
1037
+ ...options
1038
+ });
1039
+ var createWebhook = (options) => (options?.client ?? client).post({
1040
+ security: [{ scheme: "bearer", type: "http" }],
1041
+ url: "/api/v1/webhooks",
1042
+ ...options,
1043
+ headers: {
1044
+ "Content-Type": "application/json",
1045
+ ...options?.headers
1046
+ }
1047
+ });
1048
+ var deleteWebhook = (options) => (options.client ?? client).delete({
1049
+ security: [{ scheme: "bearer", type: "http" }],
1050
+ url: "/api/v1/webhooks/{id}",
1051
+ ...options
1052
+ });
1053
+ var getWebhook = (options) => (options.client ?? client).get({
1054
+ security: [{ scheme: "bearer", type: "http" }],
1055
+ url: "/api/v1/webhooks/{id}",
1056
+ ...options
1057
+ });
1058
+ var updateWebhook = (options) => (options.client ?? client).patch({
1059
+ security: [{ scheme: "bearer", type: "http" }],
1060
+ url: "/api/v1/webhooks/{id}",
1061
+ ...options,
1062
+ headers: {
1063
+ "Content-Type": "application/json",
1064
+ ...options.headers
1065
+ }
1066
+ });
1067
+ var listWebhookDeliveries = (options) => (options.client ?? client).get({
1068
+ security: [{ scheme: "bearer", type: "http" }],
1069
+ url: "/api/v1/webhooks/{id}/deliveries",
1070
+ ...options
1071
+ });
1072
+
1073
+ // src/errors.ts
1074
+ var OrbitError = class extends Error {
1075
+ /** HTTP status, when the failure came from a response. */
1076
+ status;
1077
+ /** Stable machine-readable code (e.g. `E_RESOURCE_NOT_FOUND`), when present. */
1078
+ code;
1079
+ /** Offending field for validation errors, when present. */
1080
+ field;
1081
+ /** Raw parsed response body. */
1082
+ body;
1083
+ /** The raw `Response`, when one was received. */
1084
+ response;
1085
+ constructor(message, options = {}) {
1086
+ super(message, options.cause !== void 0 ? { cause: options.cause } : void 0);
1087
+ this.name = new.target.name;
1088
+ this.status = options.status;
1089
+ this.code = options.code;
1090
+ this.field = options.field;
1091
+ this.body = options.body;
1092
+ this.response = options.response;
1093
+ }
1094
+ };
1095
+ var AuthenticationError = class extends OrbitError {
1096
+ };
1097
+ var InsufficientScopeError = class extends OrbitError {
1098
+ };
1099
+ var ResourceNotFoundError = class extends OrbitError {
1100
+ };
1101
+ var BadRequestError = class extends OrbitError {
1102
+ };
1103
+ var ValidationError = class extends OrbitError {
1104
+ fieldErrors;
1105
+ constructor(message, options = {}) {
1106
+ super(message, options);
1107
+ this.fieldErrors = options.fieldErrors ?? [];
1108
+ }
1109
+ };
1110
+ var BundleExistsError = class extends OrbitError {
1111
+ };
1112
+ var DeviceRpcError = class extends OrbitError {
1113
+ };
1114
+ var ServerError = class extends OrbitError {
1115
+ };
1116
+ var NetworkError = class extends OrbitError {
1117
+ };
1118
+ var RateLimitError = class extends OrbitError {
1119
+ retryAfterSeconds;
1120
+ constructor(message, options = {}) {
1121
+ super(message, options);
1122
+ this.retryAfterSeconds = options.retryAfterSeconds;
1123
+ }
1124
+ };
1125
+ function extractErrorFields(body) {
1126
+ if (!body || typeof body !== "object") return {};
1127
+ const record = body;
1128
+ if (typeof record.error === "string") {
1129
+ return {
1130
+ code: record.error,
1131
+ message: typeof record.message === "string" ? record.message : record.error
1132
+ };
1133
+ }
1134
+ if (Array.isArray(record.errors) && record.errors.length > 0) {
1135
+ const first = record.errors[0];
1136
+ return {
1137
+ code: typeof first.code === "string" ? first.code : void 0,
1138
+ message: typeof first.message === "string" ? first.message : void 0,
1139
+ field: typeof first.field === "string" ? first.field : first.field === null ? null : void 0
1140
+ };
1141
+ }
1142
+ if (typeof record.message === "string") return { message: record.message };
1143
+ return {};
1144
+ }
1145
+ function extractFieldErrors(body) {
1146
+ if (!body || typeof body !== "object") return [];
1147
+ const { errors } = body;
1148
+ if (!Array.isArray(errors)) return [];
1149
+ return errors.flatMap((entry) => {
1150
+ const record = entry;
1151
+ if (typeof record.message !== "string") return [];
1152
+ return [{ message: record.message, field: typeof record.field === "string" ? record.field : null }];
1153
+ });
1154
+ }
1155
+ var DEFAULT_MESSAGES = {
1156
+ 400: "Bad request.",
1157
+ 401: "Authentication failed.",
1158
+ 403: "The token is missing a required ability.",
1159
+ 404: "Resource not found.",
1160
+ 409: "Conflict.",
1161
+ 422: "Request validation failed.",
1162
+ 429: "Rate limited.",
1163
+ 502: "The device is offline or the command transport failed."
1164
+ };
1165
+ function parseRetryAfterSeconds(response) {
1166
+ const header = response?.headers?.get("retry-after");
1167
+ if (!header) return void 0;
1168
+ const seconds = Number(header);
1169
+ return Number.isFinite(seconds) ? seconds : void 0;
1170
+ }
1171
+ function normalizeError(status, body, response) {
1172
+ const { code, message, field } = extractErrorFields(body);
1173
+ const base = { status, code, field, body, response };
1174
+ const msg = message ?? DEFAULT_MESSAGES[status] ?? `Request failed with status ${status}.`;
1175
+ switch (status) {
1176
+ case 400:
1177
+ return new BadRequestError(msg, base);
1178
+ case 401:
1179
+ return new AuthenticationError(msg, base);
1180
+ case 403:
1181
+ return new InsufficientScopeError(msg, base);
1182
+ case 404:
1183
+ return new ResourceNotFoundError(msg, base);
1184
+ case 409:
1185
+ return new BundleExistsError(msg, base);
1186
+ case 422:
1187
+ return new ValidationError(msg, { ...base, fieldErrors: extractFieldErrors(body) });
1188
+ case 429:
1189
+ return new RateLimitError(msg, { ...base, retryAfterSeconds: parseRetryAfterSeconds(response) });
1190
+ case 502:
1191
+ return new DeviceRpcError(msg, base);
1192
+ default:
1193
+ if (status >= 500) return new ServerError(msg, base);
1194
+ return new OrbitError(msg, base);
1195
+ }
1196
+ }
1197
+
1198
+ // src/pagination.ts
1199
+ async function* paginate(fetchPage) {
1200
+ let cursor;
1201
+ for (; ; ) {
1202
+ const page = await fetchPage(cursor);
1203
+ for (const item of page.data) yield item;
1204
+ if (!page.hasMore || !page.nextCursor) return;
1205
+ cursor = page.nextCursor;
1206
+ }
1207
+ }
1208
+
1209
+ // src/usb.ts
1210
+ var SECURITY = [{ scheme: "bearer", type: "http" }];
1211
+ function listExportable(client2, deviceId) {
1212
+ return client2.get({
1213
+ security: SECURITY,
1214
+ url: `/api/v1/devices/${encodeURIComponent(deviceId)}/usb/exportable`,
1215
+ throwOnError: false
1216
+ });
1217
+ }
1218
+ function createTicket(client2, body) {
1219
+ return client2.post({
1220
+ security: SECURITY,
1221
+ url: "/api/v1/usb/ticket",
1222
+ body,
1223
+ throwOnError: false
1224
+ });
1225
+ }
1226
+
1227
+ // src/terminal.ts
1228
+ var SECURITY2 = [{ scheme: "bearer", type: "http" }];
1229
+ function createTicket2(client2, body) {
1230
+ return client2.post({
1231
+ security: SECURITY2,
1232
+ url: "/api/v1/terminal/ticket",
1233
+ body,
1234
+ throwOnError: false
1235
+ });
1236
+ }
1237
+
1238
+ // src/client.ts
1239
+ var DEFAULT_BASE_URL = "https://orbit.omirion.com";
1240
+ var RETRYABLE_STATUS = /* @__PURE__ */ new Set([429, 502, 503, 504]);
1241
+ var OrbitClient = class {
1242
+ #client;
1243
+ #maxRetries;
1244
+ #retryBaseDelayMs;
1245
+ /**
1246
+ * Who this token authenticates as, what it may do, and which projects it
1247
+ * reaches. Requires no ability, the cheapest way to verify a token works.
1248
+ */
1249
+ me;
1250
+ /**
1251
+ * Projects as a resource. Requires `api:projects:read`; {@link me} returns
1252
+ * the same ids under no ability.
1253
+ */
1254
+ projects;
1255
+ /**
1256
+ * Device types: the models a fleet identifies as. Reads need
1257
+ * `api:devices:read`; writes need `api:device-types:manage`.
1258
+ */
1259
+ deviceTypes;
1260
+ devices;
1261
+ admissions;
1262
+ telemetry;
1263
+ firmware;
1264
+ commands;
1265
+ /**
1266
+ * USB/IP passthrough. Requires the `api:usb:attach` ability, which grants raw
1267
+ * USB access to whatever hardware is attached to the device, so treat a token
1268
+ * carrying it accordingly.
1269
+ *
1270
+ * Hand-written rather than generated; see `usb.ts` for why.
1271
+ */
1272
+ usb;
1273
+ /**
1274
+ * Device shell. Requires the `api:terminal:open` ability, which is the widest
1275
+ * grant the API offers: the agent runs as root, so the session is a root
1276
+ * shell bounded by no manifest. Treat a token carrying it accordingly.
1277
+ *
1278
+ * Hand-written rather than generated; see `terminal.ts` for why.
1279
+ */
1280
+ terminal;
1281
+ webhooks;
1282
+ constructor(options) {
1283
+ if (!options || !options.token) {
1284
+ throw new OrbitError("An API token is required to construct OrbitClient.");
1285
+ }
1286
+ this.#client = createClient(
1287
+ createConfig({
1288
+ baseUrl: options.baseUrl ?? DEFAULT_BASE_URL,
1289
+ auth: () => options.token,
1290
+ // Without an explicit Accept the server may content-negotiate errors
1291
+ // into plain text, outside the JSON envelope the SDK parses.
1292
+ headers: { accept: "application/json" },
1293
+ ...options.fetch ? { fetch: options.fetch } : {}
1294
+ })
1295
+ );
1296
+ this.#maxRetries = options.maxRetries ?? 2;
1297
+ this.#retryBaseDelayMs = options.retryBaseDelayMs ?? 500;
1298
+ const client2 = this.#client;
1299
+ const run = this.#run.bind(this);
1300
+ this.me = () => run(() => getIdentity({ client: client2, throwOnError: false }));
1301
+ this.projects = {
1302
+ list: (params = {}) => run(() => listProjects({ client: client2, query: params, throwOnError: false })),
1303
+ iterate: (params = {}) => paginate(async (cursor) => {
1304
+ const page = await run(
1305
+ () => listProjects({ client: client2, query: { ...params, cursor }, throwOnError: false })
1306
+ );
1307
+ return { data: page.data, nextCursor: page.meta.nextCursor, hasMore: page.meta.hasMore };
1308
+ }),
1309
+ get: (id) => run(() => getProject({ client: client2, path: { id }, throwOnError: false })),
1310
+ appToken: {
1311
+ create: (projectId) => run(
1312
+ () => createProjectAppToken({ client: client2, path: { id: projectId }, throwOnError: false })
1313
+ ),
1314
+ rotate: (projectId) => run(
1315
+ () => rotateProjectAppToken({ client: client2, path: { id: projectId }, throwOnError: false })
1316
+ )
1317
+ }
1318
+ };
1319
+ this.deviceTypes = {
1320
+ list: (projectId, params = {}) => run(
1321
+ () => listDeviceTypes({ client: client2, path: { projectId }, query: params, throwOnError: false })
1322
+ ),
1323
+ iterate: (projectId, params = {}) => paginate(async (cursor) => {
1324
+ const page = await run(
1325
+ () => listDeviceTypes({
1326
+ client: client2,
1327
+ path: { projectId },
1328
+ query: { ...params, cursor },
1329
+ throwOnError: false
1330
+ })
1331
+ );
1332
+ return { data: page.data, nextCursor: page.meta.nextCursor, hasMore: page.meta.hasMore };
1333
+ }),
1334
+ get: (projectId, slug) => run(
1335
+ () => getDeviceType({ client: client2, path: { projectId, slug }, throwOnError: false })
1336
+ ),
1337
+ create: (projectId, body) => run(
1338
+ () => createDeviceType({ client: client2, path: { projectId }, body, throwOnError: false })
1339
+ ),
1340
+ update: (projectId, slug, body) => run(
1341
+ () => updateDeviceType({ client: client2, path: { projectId, slug }, body, throwOnError: false })
1342
+ ),
1343
+ delete: async (projectId, slug) => {
1344
+ await run(
1345
+ () => deleteDeviceType({ client: client2, path: { projectId, slug }, throwOnError: false })
1346
+ );
1347
+ }
1348
+ };
1349
+ this.devices = {
1350
+ list: (params = {}) => run(() => listDevices({ client: client2, query: params, throwOnError: false })),
1351
+ get: (id) => run(() => getDevice({ client: client2, path: { id }, throwOnError: false })),
1352
+ iterate: (params = {}) => paginate(async (cursor) => {
1353
+ const page = await run(
1354
+ () => listDevices({ client: client2, query: { ...params, cursor }, throwOnError: false })
1355
+ );
1356
+ return { data: page.data, nextCursor: page.meta.nextCursor, hasMore: page.meta.hasMore };
1357
+ }),
1358
+ delete: async (id) => {
1359
+ await run(() => deleteDevice({ client: client2, path: { id }, throwOnError: false }));
1360
+ },
1361
+ resetToken: (id) => run(() => resetDeviceToken({ client: client2, path: { id }, throwOnError: false }))
1362
+ };
1363
+ this.admissions = {
1364
+ list: (params = {}) => run(
1365
+ () => listAdmissions({ client: client2, query: params, throwOnError: false })
1366
+ ),
1367
+ iterate: (params = {}) => paginate(async (cursor) => {
1368
+ const page = await run(
1369
+ () => listAdmissions({ client: client2, query: { ...params, cursor }, throwOnError: false })
1370
+ );
1371
+ return { data: page.data, nextCursor: page.meta.nextCursor, hasMore: page.meta.hasMore };
1372
+ }),
1373
+ get: (id) => run(() => getAdmission({ client: client2, path: { id }, throwOnError: false })),
1374
+ accept: (id, params) => run(
1375
+ () => acceptAdmission({ client: client2, path: { id }, body: params, throwOnError: false })
1376
+ ),
1377
+ reject: (id) => run(() => rejectAdmission({ client: client2, path: { id }, throwOnError: false })),
1378
+ dismiss: (id) => run(() => dismissAdmission({ client: client2, path: { id }, throwOnError: false }))
1379
+ };
1380
+ this.telemetry = {
1381
+ latest: (deviceId) => run(
1382
+ () => getLatestTelemetry({ client: client2, path: { id: deviceId }, throwOnError: false })
1383
+ ),
1384
+ history: (deviceId, params = {}) => run(
1385
+ () => getTelemetryHistory({ client: client2, path: { id: deviceId }, query: params, throwOnError: false })
1386
+ ).then((result) => result.data),
1387
+ manifest: (deviceId) => run(
1388
+ () => getTelemetryManifest({ client: client2, path: { id: deviceId }, throwOnError: false })
1389
+ )
1390
+ };
1391
+ this.firmware = {
1392
+ upload: (params) => run(
1393
+ () => uploadFirmware({ client: client2, body: params, throwOnError: false })
1394
+ ).then((result) => result.bundle),
1395
+ deleteBundle: async (id) => {
1396
+ await run(() => deleteFirmwareBundle({ client: client2, path: { id }, throwOnError: false }));
1397
+ },
1398
+ bundles: {
1399
+ list: (params = {}) => run(
1400
+ () => listFirmwareBundles({ client: client2, query: params, throwOnError: false })
1401
+ ),
1402
+ iterate: (params = {}) => paginate(async (cursor) => {
1403
+ const page = await run(
1404
+ () => listFirmwareBundles({ client: client2, query: { ...params, cursor }, throwOnError: false })
1405
+ );
1406
+ return { data: page.data, nextCursor: page.meta.nextCursor, hasMore: page.meta.hasMore };
1407
+ }),
1408
+ get: (id) => run(() => getFirmwareBundle({ client: client2, path: { id }, throwOnError: false }))
1409
+ },
1410
+ deployments: {
1411
+ trigger: (params) => run(
1412
+ () => triggerFirmwareDeployment({ client: client2, body: params, throwOnError: false })
1413
+ ).then((result) => result.deployments),
1414
+ list: (params = {}) => run(
1415
+ () => listFirmwareDeployments({ client: client2, query: params, throwOnError: false })
1416
+ ),
1417
+ iterate: (params = {}) => paginate(async (cursor) => {
1418
+ const page = await run(
1419
+ () => listFirmwareDeployments({ client: client2, query: { ...params, cursor }, throwOnError: false })
1420
+ );
1421
+ return {
1422
+ data: page.data,
1423
+ nextCursor: page.meta.nextCursor,
1424
+ hasMore: page.meta.hasMore
1425
+ };
1426
+ }),
1427
+ get: (id) => run(
1428
+ () => getFirmwareDeployment({ client: client2, path: { id }, throwOnError: false })
1429
+ ),
1430
+ cancel: (id, params = {}) => run(
1431
+ () => cancelFirmwareDeployment({ client: client2, path: { id }, body: params, throwOnError: false })
1432
+ ),
1433
+ rollback: (id, params = {}) => run(
1434
+ () => rollbackFirmwareDeployment({ client: client2, path: { id }, body: params, throwOnError: false })
1435
+ )
1436
+ }
1437
+ };
1438
+ this.commands = {
1439
+ exec: (deviceId, command) => run(
1440
+ () => execDeviceCommand({ client: client2, path: { id: deviceId }, body: command, throwOnError: false })
1441
+ ),
1442
+ get: (deviceId, invocationId) => run(
1443
+ () => getDeviceCommandInvocation({
1444
+ client: client2,
1445
+ path: { id: deviceId, invocationId },
1446
+ throwOnError: false
1447
+ })
1448
+ ),
1449
+ manifest: (deviceId) => run(
1450
+ () => getDeviceCommands({ client: client2, path: { id: deviceId }, throwOnError: false })
1451
+ )
1452
+ };
1453
+ this.usb = {
1454
+ list: (deviceId) => run(() => listExportable(client2, deviceId)).then(
1455
+ (result) => result.exports
1456
+ ),
1457
+ ticket: (params) => run(() => createTicket(client2, params))
1458
+ };
1459
+ this.terminal = {
1460
+ ticket: (params) => run(() => createTicket2(client2, params))
1461
+ };
1462
+ this.webhooks = {
1463
+ list: (params = {}) => run(
1464
+ () => listWebhooks({ client: client2, query: params, throwOnError: false })
1465
+ ),
1466
+ iterate: (params = {}) => paginate(async (cursor) => {
1467
+ const page = await run(
1468
+ () => listWebhooks({ client: client2, query: { ...params, cursor }, throwOnError: false })
1469
+ );
1470
+ return { data: page.data, nextCursor: page.meta.nextCursor, hasMore: page.meta.hasMore };
1471
+ }),
1472
+ create: (params) => run(
1473
+ () => createWebhook({ client: client2, body: params, throwOnError: false })
1474
+ ),
1475
+ get: (id) => run(() => getWebhook({ client: client2, path: { id }, throwOnError: false })),
1476
+ update: (id, params) => run(
1477
+ () => updateWebhook({ client: client2, path: { id }, body: params, throwOnError: false })
1478
+ ),
1479
+ delete: async (id) => {
1480
+ await run(() => deleteWebhook({ client: client2, path: { id }, throwOnError: false }));
1481
+ },
1482
+ deliveries: (id, params = {}) => run(
1483
+ () => listWebhookDeliveries({ client: client2, path: { id }, query: params, throwOnError: false })
1484
+ ),
1485
+ iterateDeliveries: (id, params = {}) => paginate(async (cursor) => {
1486
+ const page = await run(
1487
+ () => listWebhookDeliveries({
1488
+ client: client2,
1489
+ path: { id },
1490
+ query: { ...params, cursor },
1491
+ throwOnError: false
1492
+ })
1493
+ );
1494
+ return { data: page.data, nextCursor: page.meta.nextCursor, hasMore: page.meta.hasMore };
1495
+ })
1496
+ };
1497
+ }
1498
+ async #run(thunk) {
1499
+ let attempt = 0;
1500
+ for (; ; ) {
1501
+ let result;
1502
+ try {
1503
+ result = await thunk();
1504
+ } catch (cause) {
1505
+ if (attempt < this.#maxRetries) {
1506
+ await this.#sleep(this.#backoff(attempt));
1507
+ attempt++;
1508
+ continue;
1509
+ }
1510
+ throw new NetworkError("The request failed before a response was received.", { cause });
1511
+ }
1512
+ const { data, error, response } = result;
1513
+ const status = response?.status ?? 0;
1514
+ if (error === void 0 && status >= 200 && status < 300) {
1515
+ return data;
1516
+ }
1517
+ if (response === void 0) {
1518
+ if (attempt < this.#maxRetries) {
1519
+ await this.#sleep(this.#backoff(attempt));
1520
+ attempt++;
1521
+ continue;
1522
+ }
1523
+ throw new NetworkError("The request failed before a response was received.", {
1524
+ cause: error
1525
+ });
1526
+ }
1527
+ if (RETRYABLE_STATUS.has(status) && attempt < this.#maxRetries) {
1528
+ const retryAfter = parseRetryAfterSeconds(response);
1529
+ await this.#sleep(retryAfter !== void 0 ? retryAfter * 1e3 : this.#backoff(attempt));
1530
+ attempt++;
1531
+ continue;
1532
+ }
1533
+ throw normalizeError(status, error ?? data, response);
1534
+ }
1535
+ }
1536
+ #backoff(attempt) {
1537
+ const base = this.#retryBaseDelayMs * 2 ** attempt;
1538
+ return Math.floor(base * (0.5 + Math.random() * 0.5));
1539
+ }
1540
+ #sleep(ms) {
1541
+ if (ms <= 0) return Promise.resolve();
1542
+ return new Promise((resolve) => setTimeout(resolve, ms));
1543
+ }
1544
+ };
1545
+
1546
+ // src/telemetry.ts
1547
+ function decodeSample(sample, manifest) {
1548
+ const byKey = new Map(manifest.metrics.map((metric) => [metric.key, metric]));
1549
+ return Object.entries(sample.metrics).map(([key, value]) => {
1550
+ const definition = byKey.get(key);
1551
+ if (!definition) return { key, label: key, value };
1552
+ return {
1553
+ key,
1554
+ label: definition.label,
1555
+ value,
1556
+ unit: definition.unit,
1557
+ type: definition.type,
1558
+ deviceClass: definition.deviceClass,
1559
+ group: definition.group,
1560
+ definition
1561
+ };
1562
+ });
1563
+ }
1564
+ function decodeSamples(samples, manifest) {
1565
+ return samples.map((sample) => ({
1566
+ recordedAt: sample.recordedAt,
1567
+ metrics: decodeSample(sample, manifest)
1568
+ }));
1569
+ }
1570
+
1571
+ // src/webhooks.ts
1572
+ var WEBHOOK_REPLAY_TOLERANCE_SECONDS = 300;
1573
+ async function hmacSha256Hex(secret, message) {
1574
+ const encoder = new TextEncoder();
1575
+ const key = await crypto.subtle.importKey(
1576
+ "raw",
1577
+ encoder.encode(secret),
1578
+ { name: "HMAC", hash: "SHA-256" },
1579
+ false,
1580
+ ["sign"]
1581
+ );
1582
+ const signature = await crypto.subtle.sign("HMAC", key, encoder.encode(message));
1583
+ return Array.from(new Uint8Array(signature)).map((b) => b.toString(16).padStart(2, "0")).join("");
1584
+ }
1585
+ function timingSafeEqual(a, b) {
1586
+ const encoder = new TextEncoder();
1587
+ const ab = encoder.encode(a);
1588
+ const bb = encoder.encode(b);
1589
+ if (ab.length !== bb.length) return false;
1590
+ let diff = 0;
1591
+ for (let i = 0; i < ab.length; i++) diff |= (ab[i] ?? 0) ^ (bb[i] ?? 0);
1592
+ return diff === 0;
1593
+ }
1594
+ async function signWebhookPayload(secret, timestamp, rawBody) {
1595
+ return hmacSha256Hex(secret, `${timestamp}.${rawBody}`);
1596
+ }
1597
+ async function verifyWebhookSignature(params) {
1598
+ const timestamp = Number(params.timestamp);
1599
+ if (!Number.isFinite(timestamp)) return false;
1600
+ const tolerance = params.toleranceSeconds ?? WEBHOOK_REPLAY_TOLERANCE_SECONDS;
1601
+ const now = params.nowSeconds ?? Math.floor(Date.now() / 1e3);
1602
+ if (Math.abs(now - timestamp) > tolerance) return false;
1603
+ const expected = await signWebhookPayload(params.secret, timestamp, params.rawBody);
1604
+ return timingSafeEqual(expected, params.signature);
1605
+ }
1606
+ async function parseWebhookEvent(params) {
1607
+ if (!await verifyWebhookSignature(params)) return null;
1608
+ return JSON.parse(params.rawBody);
1609
+ }
1610
+
1611
+ // src/generated/index.ts
1612
+ var generated_exports = {};
1613
+ __export(generated_exports, {
1614
+ acceptAdmission: () => acceptAdmission,
1615
+ cancelFirmwareDeployment: () => cancelFirmwareDeployment,
1616
+ createDeviceType: () => createDeviceType,
1617
+ createProjectAppToken: () => createProjectAppToken,
1618
+ createWebhook: () => createWebhook,
1619
+ deleteCommandManifest: () => deleteCommandManifest,
1620
+ deleteDevice: () => deleteDevice,
1621
+ deleteDeviceType: () => deleteDeviceType,
1622
+ deleteFirmwareBundle: () => deleteFirmwareBundle,
1623
+ deleteWebhook: () => deleteWebhook,
1624
+ dismissAdmission: () => dismissAdmission,
1625
+ execDeviceCommand: () => execDeviceCommand,
1626
+ getAdmission: () => getAdmission,
1627
+ getCommandManifest: () => getCommandManifest,
1628
+ getDevice: () => getDevice,
1629
+ getDeviceCommandInvocation: () => getDeviceCommandInvocation,
1630
+ getDeviceCommands: () => getDeviceCommands,
1631
+ getDeviceType: () => getDeviceType,
1632
+ getFirmwareBundle: () => getFirmwareBundle,
1633
+ getFirmwareDeployment: () => getFirmwareDeployment,
1634
+ getIdentity: () => getIdentity,
1635
+ getLatestTelemetry: () => getLatestTelemetry,
1636
+ getProject: () => getProject,
1637
+ getTelemetryHistory: () => getTelemetryHistory,
1638
+ getTelemetryManifest: () => getTelemetryManifest,
1639
+ getWebhook: () => getWebhook,
1640
+ listAdmissions: () => listAdmissions,
1641
+ listDeviceTypes: () => listDeviceTypes,
1642
+ listDevices: () => listDevices,
1643
+ listFirmwareBundles: () => listFirmwareBundles,
1644
+ listFirmwareDeployments: () => listFirmwareDeployments,
1645
+ listProjects: () => listProjects,
1646
+ listWebhookDeliveries: () => listWebhookDeliveries,
1647
+ listWebhooks: () => listWebhooks,
1648
+ rejectAdmission: () => rejectAdmission,
1649
+ resetDeviceToken: () => resetDeviceToken,
1650
+ rollbackFirmwareDeployment: () => rollbackFirmwareDeployment,
1651
+ rotateProjectAppToken: () => rotateProjectAppToken,
1652
+ triggerFirmwareDeployment: () => triggerFirmwareDeployment,
1653
+ updateCommandManifest: () => updateCommandManifest,
1654
+ updateDeviceType: () => updateDeviceType,
1655
+ updateWebhook: () => updateWebhook,
1656
+ uploadFirmware: () => uploadFirmware
1657
+ });
1658
+
1659
+ export { AuthenticationError, BadRequestError, BundleExistsError, DeviceRpcError, InsufficientScopeError, NetworkError, OrbitClient, OrbitError, RateLimitError, ResourceNotFoundError, ServerError, ValidationError, WEBHOOK_REPLAY_TOLERANCE_SECONDS, decodeSample, decodeSamples, normalizeError, paginate, parseRetryAfterSeconds, parseWebhookEvent, generated_exports as raw, signWebhookPayload, verifyWebhookSignature };
1660
+ //# sourceMappingURL=index.js.map
1661
+ //# sourceMappingURL=index.js.map