@cycleplatform/api-client-typescript 0.3.15 → 0.3.22

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 CHANGED
@@ -1,148 +1,168 @@
1
- const B = /\{[^{}]+\}/g, F = () => {
1
+ const Q = /\{[^{}]+\}/g, _ = () => {
2
2
  var r, t;
3
3
  return typeof process == "object" && Number.parseInt((t = (r = process == null ? void 0 : process.versions) == null ? void 0 : r.node) == null ? void 0 : t.substring(0, 2)) >= 18 && process.versions.undici;
4
4
  };
5
- function M() {
5
+ function X() {
6
6
  return Math.random().toString(36).slice(2, 11);
7
7
  }
8
- function W(r) {
8
+ function Z(r) {
9
9
  let {
10
10
  baseUrl: t = "",
11
11
  Request: e = globalThis.Request,
12
- fetch: s = globalThis.fetch,
12
+ fetch: o = globalThis.fetch,
13
13
  querySerializer: n,
14
- bodySerializer: o,
14
+ bodySerializer: s,
15
15
  headers: i,
16
16
  requestInitExt: l = void 0,
17
- ...y
17
+ ...h
18
18
  } = { ...r };
19
- l = F() ? l : void 0, t = U(t);
20
- const h = [];
19
+ l = _() ? l : void 0, t = L(t);
20
+ const g = [];
21
21
  async function p(c, a) {
22
22
  const {
23
- baseUrl: m,
24
- fetch: I = s,
25
- Request: Y = e,
26
- headers: J,
27
- params: g = {},
23
+ baseUrl: b,
24
+ fetch: I = o,
25
+ Request: k = e,
26
+ headers: O,
27
+ params: R = {},
28
28
  parseAs: A = "json",
29
- querySerializer: j,
30
- bodySerializer: k = o ?? Q,
31
- body: v,
29
+ querySerializer: E,
30
+ bodySerializer: D = s ?? V,
31
+ body: H,
32
+ middleware: N = [],
32
33
  ...x
33
34
  } = a || {};
34
- m && (t = U(m));
35
- let z = typeof n == "function" ? n : O(n);
36
- j && (z = typeof j == "function" ? j : O({
35
+ let C = t;
36
+ b && (C = L(b) ?? t);
37
+ let q = typeof n == "function" ? n : P(n);
38
+ E && (q = typeof E == "function" ? E : P({
37
39
  ...typeof n == "object" ? n : {},
38
- ...j
40
+ ...E
39
41
  }));
40
- const q = v === void 0 ? void 0 : k(v), L = (
42
+ const z = H === void 0 ? void 0 : D(
43
+ H,
44
+ // Note: we declare mergeHeaders() both here and below because it’s a bit of a chicken-or-egg situation:
45
+ // bodySerializer() needs all headers so we aren’t dropping ones set by the user, however,
46
+ // the result of this ALSO sets the lowest-priority content-type header. So we re-merge below,
47
+ // setting the content-type at the very beginning to be overwritten.
48
+ // Lastly, based on the way headers work, it’s not a simple “present-or-not” check becauase null intentionally un-sets headers.
49
+ M(i, O, R.header)
50
+ ), W = M(
41
51
  // with no body, we should not to set Content-Type
42
- q === void 0 || // if serialized body is FormData; browser will correctly set Content-Type & boundary expression
43
- q instanceof FormData ? {} : {
52
+ z === void 0 || // if serialized body is FormData; browser will correctly set Content-Type & boundary expression
53
+ z instanceof FormData ? {} : {
44
54
  "Content-Type": "application/json"
45
- }
46
- ), N = {
55
+ },
56
+ i,
57
+ O,
58
+ R.header
59
+ ), y = [...g, ...N], G = {
47
60
  redirect: "follow",
48
- ...y,
61
+ ...h,
49
62
  ...x,
50
- body: q,
51
- headers: X(L, i, J, g.header)
63
+ body: z,
64
+ headers: W
52
65
  };
53
- let E, S, b = new e(_(c, { baseUrl: t, params: g, querySerializer: z }), N);
54
- for (const u in x)
55
- u in b || (b[u] = x[u]);
56
- if (h.length) {
57
- E = M(), S = Object.freeze({
58
- baseUrl: t,
66
+ let T, v, m = new k(
67
+ Y(c, { baseUrl: C, params: R, querySerializer: q }),
68
+ G
69
+ ), f;
70
+ for (const d in x)
71
+ d in m || (m[d] = x[d]);
72
+ if (y.length) {
73
+ T = X(), v = Object.freeze({
74
+ baseUrl: C,
59
75
  fetch: I,
60
76
  parseAs: A,
61
- querySerializer: z,
62
- bodySerializer: k
77
+ querySerializer: q,
78
+ bodySerializer: D
63
79
  });
64
- for (const u of h)
65
- if (u && typeof u == "object" && typeof u.onRequest == "function") {
66
- const d = await u.onRequest({
67
- request: b,
80
+ for (const d of y)
81
+ if (d && typeof d == "object" && typeof d.onRequest == "function") {
82
+ const u = await d.onRequest({
83
+ request: m,
68
84
  schemaPath: c,
69
- params: g,
70
- options: S,
71
- id: E
85
+ params: R,
86
+ options: v,
87
+ id: T
72
88
  });
73
- if (d) {
74
- if (!(d instanceof e))
75
- throw new Error("onRequest: must return new Request() when modifying the request");
76
- b = d;
77
- }
89
+ if (u)
90
+ if (u instanceof k)
91
+ m = u;
92
+ else if (u instanceof Response) {
93
+ f = u;
94
+ break;
95
+ } else
96
+ throw new Error("onRequest: must return new Request() or Response() when modifying the request");
78
97
  }
79
98
  }
80
- let f;
81
- try {
82
- f = await I(b, l);
83
- } catch (u) {
84
- let d = u;
85
- if (h.length)
86
- for (let w = h.length - 1; w >= 0; w--) {
87
- const T = h[w];
88
- if (T && typeof T == "object" && typeof T.onError == "function") {
89
- const R = await T.onError({
90
- request: b,
91
- error: d,
99
+ if (!f) {
100
+ try {
101
+ f = await I(m, l);
102
+ } catch (d) {
103
+ let u = d;
104
+ if (y.length)
105
+ for (let w = y.length - 1; w >= 0; w--) {
106
+ const S = y[w];
107
+ if (S && typeof S == "object" && typeof S.onError == "function") {
108
+ const j = await S.onError({
109
+ request: m,
110
+ error: u,
111
+ schemaPath: c,
112
+ params: R,
113
+ options: v,
114
+ id: T
115
+ });
116
+ if (j) {
117
+ if (j instanceof Response) {
118
+ u = void 0, f = j;
119
+ break;
120
+ }
121
+ if (j instanceof Error) {
122
+ u = j;
123
+ continue;
124
+ }
125
+ throw new Error("onError: must return new Response() or instance of Error");
126
+ }
127
+ }
128
+ }
129
+ if (u)
130
+ throw u;
131
+ }
132
+ if (y.length)
133
+ for (let d = y.length - 1; d >= 0; d--) {
134
+ const u = y[d];
135
+ if (u && typeof u == "object" && typeof u.onResponse == "function") {
136
+ const w = await u.onResponse({
137
+ request: m,
138
+ response: f,
92
139
  schemaPath: c,
93
- params: g,
94
- options: S,
95
- id: E
140
+ params: R,
141
+ options: v,
142
+ id: T
96
143
  });
97
- if (R) {
98
- if (R instanceof Response) {
99
- d = void 0, f = R;
100
- break;
101
- }
102
- if (R instanceof Error) {
103
- d = R;
104
- continue;
105
- }
106
- throw new Error("onError: must return new Response() or instance of Error");
144
+ if (w) {
145
+ if (!(w instanceof Response))
146
+ throw new Error("onResponse: must return new Response() when modifying the response");
147
+ f = w;
107
148
  }
108
149
  }
109
150
  }
110
- if (d)
111
- throw d;
112
151
  }
113
- if (h.length)
114
- for (let u = h.length - 1; u >= 0; u--) {
115
- const d = h[u];
116
- if (d && typeof d == "object" && typeof d.onResponse == "function") {
117
- const w = await d.onResponse({
118
- request: b,
119
- response: f,
120
- schemaPath: c,
121
- params: g,
122
- options: S,
123
- id: E
124
- });
125
- if (w) {
126
- if (!(w instanceof Response))
127
- throw new Error("onResponse: must return new Response() when modifying the response");
128
- f = w;
129
- }
130
- }
131
- }
132
- if (f.status === 204 || f.headers.get("Content-Length") === "0")
152
+ if (f.status === 204 || m.method === "HEAD" || f.headers.get("Content-Length") === "0")
133
153
  return f.ok ? { data: void 0, response: f } : { error: void 0, response: f };
134
154
  if (f.ok)
135
155
  return A === "stream" ? { data: f.body, response: f } : { data: await f[A](), response: f };
136
- let C = await f.text();
156
+ let U = await f.text();
137
157
  try {
138
- C = JSON.parse(C);
158
+ U = JSON.parse(U);
139
159
  } catch {
140
160
  }
141
- return { error: C, response: f };
161
+ return { error: U, response: f };
142
162
  }
143
163
  return {
144
- request(c, a, m) {
145
- return p(a, { ...m, method: c.toUpperCase() });
164
+ request(c, a, b) {
165
+ return p(a, { ...b, method: c.toUpperCase() });
146
166
  },
147
167
  /** Call a GET endpoint */
148
168
  GET(c, a) {
@@ -182,14 +202,14 @@ function W(r) {
182
202
  if (a) {
183
203
  if (typeof a != "object" || !("onRequest" in a || "onResponse" in a || "onError" in a))
184
204
  throw new Error("Middleware must be an object with one of `onRequest()`, `onResponse() or `onError()`");
185
- h.push(a);
205
+ g.push(a);
186
206
  }
187
207
  },
188
208
  /** Unregister middleware */
189
209
  eject(...c) {
190
210
  for (const a of c) {
191
- const m = h.indexOf(a);
192
- m !== -1 && h.splice(m, 1);
211
+ const b = g.indexOf(a);
212
+ b !== -1 && g.splice(b, 1);
193
213
  }
194
214
  }
195
215
  };
@@ -203,18 +223,18 @@ function $(r, t, e) {
203
223
  );
204
224
  return `${r}=${(e == null ? void 0 : e.allowReserved) === !0 ? t : encodeURIComponent(t)}`;
205
225
  }
206
- function H(r, t, e) {
226
+ function F(r, t, e) {
207
227
  if (!t || typeof t != "object")
208
228
  return "";
209
- const s = [], n = {
229
+ const o = [], n = {
210
230
  simple: ",",
211
231
  label: ".",
212
232
  matrix: ";"
213
233
  }[e.style] || "&";
214
234
  if (e.style !== "deepObject" && e.explode === !1) {
215
235
  for (const l in t)
216
- s.push(l, e.allowReserved === !0 ? t[l] : encodeURIComponent(t[l]));
217
- const i = s.join(",");
236
+ o.push(l, e.allowReserved === !0 ? t[l] : encodeURIComponent(t[l]));
237
+ const i = o.join(",");
218
238
  switch (e.style) {
219
239
  case "form":
220
240
  return `${r}=${i}`;
@@ -228,16 +248,16 @@ function H(r, t, e) {
228
248
  }
229
249
  for (const i in t) {
230
250
  const l = e.style === "deepObject" ? `${r}[${i}]` : i;
231
- s.push($(l, t[i], e));
251
+ o.push($(l, t[i], e));
232
252
  }
233
- const o = s.join(n);
234
- return e.style === "label" || e.style === "matrix" ? `${n}${o}` : o;
253
+ const s = o.join(n);
254
+ return e.style === "label" || e.style === "matrix" ? `${n}${s}` : s;
235
255
  }
236
- function P(r, t, e) {
256
+ function J(r, t, e) {
237
257
  if (!Array.isArray(t))
238
258
  return "";
239
259
  if (e.explode === !1) {
240
- const o = { form: ",", spaceDelimited: "%20", pipeDelimited: "|" }[e.style] || ",", i = (e.allowReserved === !0 ? t : t.map((l) => encodeURIComponent(l))).join(o);
260
+ const s = { form: ",", spaceDelimited: "%20", pipeDelimited: "|" }[e.style] || ",", i = (e.allowReserved === !0 ? t : t.map((l) => encodeURIComponent(l))).join(s);
241
261
  switch (e.style) {
242
262
  case "simple":
243
263
  return i;
@@ -251,23 +271,23 @@ function P(r, t, e) {
251
271
  return `${r}=${i}`;
252
272
  }
253
273
  }
254
- const s = { simple: ",", label: ".", matrix: ";" }[e.style] || "&", n = [];
255
- for (const o of t)
256
- e.style === "simple" || e.style === "label" ? n.push(e.allowReserved === !0 ? o : encodeURIComponent(o)) : n.push($(r, o, e));
257
- return e.style === "label" || e.style === "matrix" ? `${s}${n.join(s)}` : n.join(s);
274
+ const o = { simple: ",", label: ".", matrix: ";" }[e.style] || "&", n = [];
275
+ for (const s of t)
276
+ e.style === "simple" || e.style === "label" ? n.push(e.allowReserved === !0 ? s : encodeURIComponent(s)) : n.push($(r, s, e));
277
+ return e.style === "label" || e.style === "matrix" ? `${o}${n.join(o)}` : n.join(o);
258
278
  }
259
- function O(r) {
279
+ function P(r) {
260
280
  return function(e) {
261
- const s = [];
281
+ const o = [];
262
282
  if (e && typeof e == "object")
263
283
  for (const n in e) {
264
- const o = e[n];
265
- if (o != null) {
266
- if (Array.isArray(o)) {
267
- if (o.length === 0)
284
+ const s = e[n];
285
+ if (s != null) {
286
+ if (Array.isArray(s)) {
287
+ if (s.length === 0)
268
288
  continue;
269
- s.push(
270
- P(n, o, {
289
+ o.push(
290
+ J(n, s, {
271
291
  style: "form",
272
292
  explode: !0,
273
293
  ...r == null ? void 0 : r.array,
@@ -276,9 +296,9 @@ function O(r) {
276
296
  );
277
297
  continue;
278
298
  }
279
- if (typeof o == "object") {
280
- s.push(
281
- H(n, o, {
299
+ if (typeof s == "object") {
300
+ o.push(
301
+ F(n, s, {
282
302
  style: "deepObject",
283
303
  explode: !0,
284
304
  ...r == null ? void 0 : r.object,
@@ -287,72 +307,72 @@ function O(r) {
287
307
  );
288
308
  continue;
289
309
  }
290
- s.push($(n, o, r));
310
+ o.push($(n, s, r));
291
311
  }
292
312
  }
293
- return s.join("&");
313
+ return o.join("&");
294
314
  };
295
315
  }
296
- function G(r, t) {
316
+ function K(r, t) {
297
317
  let e = r;
298
- for (const s of r.match(B) ?? []) {
299
- let n = s.substring(1, s.length - 1), o = !1, i = "simple";
300
- if (n.endsWith("*") && (o = !0, n = n.substring(0, n.length - 1)), n.startsWith(".") ? (i = "label", n = n.substring(1)) : n.startsWith(";") && (i = "matrix", n = n.substring(1)), !t || t[n] === void 0 || t[n] === null)
318
+ for (const o of r.match(Q) ?? []) {
319
+ let n = o.substring(1, o.length - 1), s = !1, i = "simple";
320
+ if (n.endsWith("*") && (s = !0, n = n.substring(0, n.length - 1)), n.startsWith(".") ? (i = "label", n = n.substring(1)) : n.startsWith(";") && (i = "matrix", n = n.substring(1)), !t || t[n] === void 0 || t[n] === null)
301
321
  continue;
302
322
  const l = t[n];
303
323
  if (Array.isArray(l)) {
304
- e = e.replace(s, P(n, l, { style: i, explode: o }));
324
+ e = e.replace(o, J(n, l, { style: i, explode: s }));
305
325
  continue;
306
326
  }
307
327
  if (typeof l == "object") {
308
- e = e.replace(s, H(n, l, { style: i, explode: o }));
328
+ e = e.replace(o, F(n, l, { style: i, explode: s }));
309
329
  continue;
310
330
  }
311
331
  if (i === "matrix") {
312
- e = e.replace(s, `;${$(n, l)}`);
332
+ e = e.replace(o, `;${$(n, l)}`);
313
333
  continue;
314
334
  }
315
- e = e.replace(s, i === "label" ? `.${encodeURIComponent(l)}` : encodeURIComponent(l));
335
+ e = e.replace(o, i === "label" ? `.${encodeURIComponent(l)}` : encodeURIComponent(l));
316
336
  }
317
337
  return e;
318
338
  }
319
- function Q(r) {
320
- return r instanceof FormData ? r : JSON.stringify(r);
339
+ function V(r, t) {
340
+ return r instanceof FormData ? r : t && (t.get instanceof Function ? t.get("Content-Type") ?? t.get("content-type") : t["Content-Type"] ?? t["content-type"]) === "application/x-www-form-urlencoded" ? new URLSearchParams(r).toString() : JSON.stringify(r);
321
341
  }
322
- function _(r, t) {
342
+ function Y(r, t) {
323
343
  var n;
324
344
  let e = `${t.baseUrl}${r}`;
325
- (n = t.params) != null && n.path && (e = G(e, t.params.path));
326
- let s = t.querySerializer(t.params.query ?? {});
327
- return s.startsWith("?") && (s = s.substring(1)), s && (e += `?${s}`), e;
345
+ (n = t.params) != null && n.path && (e = K(e, t.params.path));
346
+ let o = t.querySerializer(t.params.query ?? {});
347
+ return o.startsWith("?") && (o = o.substring(1)), o && (e += `?${o}`), e;
328
348
  }
329
- function X(...r) {
349
+ function M(...r) {
330
350
  const t = new Headers();
331
351
  for (const e of r) {
332
352
  if (!e || typeof e != "object")
333
353
  continue;
334
- const s = e instanceof Headers ? e.entries() : Object.entries(e);
335
- for (const [n, o] of s)
336
- if (o === null)
354
+ const o = e instanceof Headers ? e.entries() : Object.entries(e);
355
+ for (const [n, s] of o)
356
+ if (s === null)
337
357
  t.delete(n);
338
- else if (Array.isArray(o))
339
- for (const i of o)
358
+ else if (Array.isArray(s))
359
+ for (const i of s)
340
360
  t.append(n, i);
341
- else o !== void 0 && t.set(n, o);
361
+ else s !== void 0 && t.set(n, s);
342
362
  }
343
363
  return t;
344
364
  }
345
- function U(r) {
365
+ function L(r) {
346
366
  return r.endsWith("/") ? r.substring(0, r.length - 1) : r;
347
367
  }
348
- class Z extends EventTarget {
349
- constructor(t, e, s) {
350
- super(), this.promise = this.track(t, e, s);
368
+ class ee extends EventTarget {
369
+ constructor(t, e, o) {
370
+ super(), this.promise = this.track(t, e, o);
351
371
  }
352
- async track(t, e, s) {
353
- const n = typeof e == "object" ? e.id : e, o = {
372
+ async track(t, e, o) {
373
+ const n = typeof e == "object" ? e.id : e, s = {
354
374
  pollingInterval: 2e3,
355
- ...s
375
+ ...o
356
376
  };
357
377
  let i = 0;
358
378
  for (; ; ) {
@@ -361,51 +381,51 @@ class Z extends EventTarget {
361
381
  });
362
382
  if (l.error) {
363
383
  if (i < 5 && l.error.error.code === "404.job") {
364
- i++, await this.delay(o.pollingInterval);
384
+ i++, await this.delay(s.pollingInterval);
365
385
  continue;
366
386
  }
367
387
  throw l.error;
368
388
  }
369
- const y = l.data.data, h = V(y);
389
+ const h = l.data.data, g = re(h);
370
390
  if (this.dispatchEvent(
371
391
  new CustomEvent("progress", {
372
- detail: { ...h, state: y.state.current }
392
+ detail: { ...g, state: h.state.current }
373
393
  })
374
- ), K(y)) {
375
- if (y.state.current === "error")
376
- throw y;
394
+ ), te(h)) {
395
+ if (h.state.current === "error")
396
+ throw h;
377
397
  return this.dispatchEvent(
378
398
  new CustomEvent("done", {
379
- detail: y
399
+ detail: h
380
400
  })
381
- ), y;
401
+ ), h;
382
402
  }
383
- await this.delay(o.pollingInterval);
403
+ await this.delay(s.pollingInterval);
384
404
  }
385
405
  }
386
406
  delay(t = 2e3) {
387
407
  return new Promise((e) => setTimeout(e, t));
388
408
  }
389
409
  }
390
- function K(r) {
410
+ function te(r) {
391
411
  return [
392
412
  "completed",
393
413
  "error",
394
414
  "expired"
395
415
  ].includes(r.state.current);
396
416
  }
397
- const D = "0001-01-01T00:00:00Z";
398
- function V(r) {
417
+ const B = "0001-01-01T00:00:00Z";
418
+ function re(r) {
399
419
  if (!r.tasks || r.tasks.length === 0)
400
420
  return { total: 0, completed: 0, failed: 0, percent: 100 };
401
421
  const t = r.tasks.reduce(
402
- (e, s) => {
403
- var o, i, l;
404
- const n = ((o = s.steps) == null ? void 0 : o.length) || 1;
405
- if (e.total += n, s.state.current === "pending")
422
+ (e, o) => {
423
+ var s, i, l;
424
+ const n = ((s = o.steps) == null ? void 0 : s.length) || 1;
425
+ if (e.total += n, o.state.current === "pending")
406
426
  return e;
407
- if (!((i = s.steps) != null && i.length)) {
408
- switch (s.state.current) {
427
+ if (!((i = o.steps) != null && i.length)) {
428
+ switch (o.state.current) {
409
429
  case "completed":
410
430
  e.completed += 1;
411
431
  break;
@@ -414,12 +434,12 @@ function V(r) {
414
434
  }
415
435
  return e;
416
436
  }
417
- return (l = s.steps) == null || l.forEach((y) => {
418
- if (y.completed !== D) {
437
+ return (l = o.steps) == null || l.forEach((h) => {
438
+ if (h.completed !== B) {
419
439
  e.completed += 1;
420
440
  return;
421
441
  }
422
- ["error", "completed"].includes(s.state.current || "") && y.started !== D && (e.failed += 1);
442
+ ["error", "completed"].includes(o.state.current || "") && h.started !== B && (e.failed += 1);
423
443
  }), e;
424
444
  },
425
445
  { total: 0, completed: 0, failed: 0 }
@@ -429,28 +449,28 @@ function V(r) {
429
449
  percent: t.completed / t.total * 100
430
450
  };
431
451
  }
432
- function ee(r, t, e) {
433
- return new Z(r, t, e);
452
+ function ne(r, t, e) {
453
+ return new ee(r, t, e);
434
454
  }
435
- function te({
455
+ function oe({
436
456
  apiKey: r,
437
457
  baseUrl: t = "https://api.cycle.io",
438
458
  hubId: e,
439
- fetch: s
459
+ fetch: o
440
460
  }) {
441
- const n = W({
461
+ const n = Z({
442
462
  baseUrl: t,
443
- fetch: s || fetch
444
- }), o = {
463
+ fetch: o || fetch
464
+ }), s = {
445
465
  async onRequest({ request: i }) {
446
466
  return i.headers.set("Authorization", `Bearer ${r}`), i.headers.set("X-Hub-Id", e), i;
447
467
  }
448
468
  };
449
- return n.use(o), n;
469
+ return n.use(s), n;
450
470
  }
451
471
  export {
452
- te as getClient,
453
- V as getJobProgress,
454
- ee as trackJob,
455
- D as zeroTimeString
472
+ oe as getClient,
473
+ re as getJobProgress,
474
+ ne as trackJob,
475
+ B as zeroTimeString
456
476
  };
@@ -1 +1 @@
1
- (function(p,R){typeof exports=="object"&&typeof module<"u"?R(exports):typeof define=="function"&&define.amd?define(["exports"],R):(p=typeof globalThis<"u"?globalThis:p||self,R(p["Cycle API Client"]={}))})(this,function(p){"use strict";const R=/\{[^{}]+\}/g,N=()=>{var r,t;return typeof process=="object"&&Number.parseInt((t=(r=process==null?void 0:process.versions)==null?void 0:r.node)==null?void 0:t.substring(0,2))>=18&&process.versions.undici};function B(){return Math.random().toString(36).slice(2,11)}function F(r){let{baseUrl:t="",Request:e=globalThis.Request,fetch:o=globalThis.fetch,querySerializer:n,bodySerializer:i,headers:s,requestInitExt:l=void 0,...y}={...r};l=N()?l:void 0,t=H(t);const h=[];async function m(f,a){const{baseUrl:b,fetch:J=o,Request:re=e,headers:Y,params:j={},parseAs:q="json",querySerializer:T,bodySerializer:L=i??G,body:M,...I}=a||{};b&&(t=H(b));let x=typeof n=="function"?n:D(n);T&&(x=typeof T=="function"?T:D({...typeof n=="object"?n:{},...T}));const k=M===void 0?void 0:L(M),ee=k===void 0||k instanceof FormData?{}:{"Content-Type":"application/json"},te={redirect:"follow",...y,...I,body:k,headers:_(ee,s,Y,j.header)};let $,A,w=new e(Q(f,{baseUrl:t,params:j,querySerializer:x}),te);for(const u in I)u in w||(w[u]=I[u]);if(h.length){$=B(),A=Object.freeze({baseUrl:t,fetch:J,parseAs:q,querySerializer:x,bodySerializer:L});for(const u of h)if(u&&typeof u=="object"&&typeof u.onRequest=="function"){const d=await u.onRequest({request:w,schemaPath:f,params:j,options:A,id:$});if(d){if(!(d instanceof e))throw new Error("onRequest: must return new Request() when modifying the request");w=d}}}let c;try{c=await J(w,l)}catch(u){let d=u;if(h.length)for(let g=h.length-1;g>=0;g--){const C=h[g];if(C&&typeof C=="object"&&typeof C.onError=="function"){const E=await C.onError({request:w,error:d,schemaPath:f,params:j,options:A,id:$});if(E){if(E instanceof Response){d=void 0,c=E;break}if(E instanceof Error){d=E;continue}throw new Error("onError: must return new Response() or instance of Error")}}}if(d)throw d}if(h.length)for(let u=h.length-1;u>=0;u--){const d=h[u];if(d&&typeof d=="object"&&typeof d.onResponse=="function"){const g=await d.onResponse({request:w,response:c,schemaPath:f,params:j,options:A,id:$});if(g){if(!(g instanceof Response))throw new Error("onResponse: must return new Response() when modifying the response");c=g}}}if(c.status===204||c.headers.get("Content-Length")==="0")return c.ok?{data:void 0,response:c}:{error:void 0,response:c};if(c.ok)return q==="stream"?{data:c.body,response:c}:{data:await c[q](),response:c};let v=await c.text();try{v=JSON.parse(v)}catch{}return{error:v,response:c}}return{request(f,a,b){return m(a,{...b,method:f.toUpperCase()})},GET(f,a){return m(f,{...a,method:"GET"})},PUT(f,a){return m(f,{...a,method:"PUT"})},POST(f,a){return m(f,{...a,method:"POST"})},DELETE(f,a){return m(f,{...a,method:"DELETE"})},OPTIONS(f,a){return m(f,{...a,method:"OPTIONS"})},HEAD(f,a){return m(f,{...a,method:"HEAD"})},PATCH(f,a){return m(f,{...a,method:"PATCH"})},TRACE(f,a){return m(f,{...a,method:"TRACE"})},use(...f){for(const a of f)if(a){if(typeof a!="object"||!("onRequest"in a||"onResponse"in a||"onError"in a))throw new Error("Middleware must be an object with one of `onRequest()`, `onResponse() or `onError()`");h.push(a)}},eject(...f){for(const a of f){const b=h.indexOf(a);b!==-1&&h.splice(b,1)}}}}function S(r,t,e){if(t==null)return"";if(typeof t=="object")throw new Error("Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.");return`${r}=${(e==null?void 0:e.allowReserved)===!0?t:encodeURIComponent(t)}`}function O(r,t,e){if(!t||typeof t!="object")return"";const o=[],n={simple:",",label:".",matrix:";"}[e.style]||"&";if(e.style!=="deepObject"&&e.explode===!1){for(const l in t)o.push(l,e.allowReserved===!0?t[l]:encodeURIComponent(t[l]));const s=o.join(",");switch(e.style){case"form":return`${r}=${s}`;case"label":return`.${s}`;case"matrix":return`;${r}=${s}`;default:return s}}for(const s in t){const l=e.style==="deepObject"?`${r}[${s}]`:s;o.push(S(l,t[s],e))}const i=o.join(n);return e.style==="label"||e.style==="matrix"?`${n}${i}`:i}function U(r,t,e){if(!Array.isArray(t))return"";if(e.explode===!1){const i={form:",",spaceDelimited:"%20",pipeDelimited:"|"}[e.style]||",",s=(e.allowReserved===!0?t:t.map(l=>encodeURIComponent(l))).join(i);switch(e.style){case"simple":return s;case"label":return`.${s}`;case"matrix":return`;${r}=${s}`;default:return`${r}=${s}`}}const o={simple:",",label:".",matrix:";"}[e.style]||"&",n=[];for(const i of t)e.style==="simple"||e.style==="label"?n.push(e.allowReserved===!0?i:encodeURIComponent(i)):n.push(S(r,i,e));return e.style==="label"||e.style==="matrix"?`${o}${n.join(o)}`:n.join(o)}function D(r){return function(e){const o=[];if(e&&typeof e=="object")for(const n in e){const i=e[n];if(i!=null){if(Array.isArray(i)){if(i.length===0)continue;o.push(U(n,i,{style:"form",explode:!0,...r==null?void 0:r.array,allowReserved:(r==null?void 0:r.allowReserved)||!1}));continue}if(typeof i=="object"){o.push(O(n,i,{style:"deepObject",explode:!0,...r==null?void 0:r.object,allowReserved:(r==null?void 0:r.allowReserved)||!1}));continue}o.push(S(n,i,r))}}return o.join("&")}}function W(r,t){let e=r;for(const o of r.match(R)??[]){let n=o.substring(1,o.length-1),i=!1,s="simple";if(n.endsWith("*")&&(i=!0,n=n.substring(0,n.length-1)),n.startsWith(".")?(s="label",n=n.substring(1)):n.startsWith(";")&&(s="matrix",n=n.substring(1)),!t||t[n]===void 0||t[n]===null)continue;const l=t[n];if(Array.isArray(l)){e=e.replace(o,U(n,l,{style:s,explode:i}));continue}if(typeof l=="object"){e=e.replace(o,O(n,l,{style:s,explode:i}));continue}if(s==="matrix"){e=e.replace(o,`;${S(n,l)}`);continue}e=e.replace(o,s==="label"?`.${encodeURIComponent(l)}`:encodeURIComponent(l))}return e}function G(r){return r instanceof FormData?r:JSON.stringify(r)}function Q(r,t){var n;let e=`${t.baseUrl}${r}`;(n=t.params)!=null&&n.path&&(e=W(e,t.params.path));let o=t.querySerializer(t.params.query??{});return o.startsWith("?")&&(o=o.substring(1)),o&&(e+=`?${o}`),e}function _(...r){const t=new Headers;for(const e of r){if(!e||typeof e!="object")continue;const o=e instanceof Headers?e.entries():Object.entries(e);for(const[n,i]of o)if(i===null)t.delete(n);else if(Array.isArray(i))for(const s of i)t.append(n,s);else i!==void 0&&t.set(n,i)}return t}function H(r){return r.endsWith("/")?r.substring(0,r.length-1):r}class X extends EventTarget{constructor(t,e,o){super(),this.promise=this.track(t,e,o)}async track(t,e,o){const n=typeof e=="object"?e.id:e,i={pollingInterval:2e3,...o};let s=0;for(;;){const l=await t.GET("/v1/jobs/{jobId}",{params:{path:{jobId:n}}});if(l.error){if(s<5&&l.error.error.code==="404.job"){s++,await this.delay(i.pollingInterval);continue}throw l.error}const y=l.data.data,h=P(y);if(this.dispatchEvent(new CustomEvent("progress",{detail:{...h,state:y.state.current}})),Z(y)){if(y.state.current==="error")throw y;return this.dispatchEvent(new CustomEvent("done",{detail:y})),y}await this.delay(i.pollingInterval)}}delay(t=2e3){return new Promise(e=>setTimeout(e,t))}}function Z(r){return["completed","error","expired"].includes(r.state.current)}const z="0001-01-01T00:00:00Z";function P(r){if(!r.tasks||r.tasks.length===0)return{total:0,completed:0,failed:0,percent:100};const t=r.tasks.reduce((e,o)=>{var i,s,l;const n=((i=o.steps)==null?void 0:i.length)||1;if(e.total+=n,o.state.current==="pending")return e;if(!((s=o.steps)!=null&&s.length)){switch(o.state.current){case"completed":e.completed+=1;break;case"error":e.failed+=1}return e}return(l=o.steps)==null||l.forEach(y=>{if(y.completed!==z){e.completed+=1;return}["error","completed"].includes(o.state.current||"")&&y.started!==z&&(e.failed+=1)}),e},{total:0,completed:0,failed:0});return{...t,percent:t.completed/t.total*100}}function K(r,t,e){return new X(r,t,e)}function V({apiKey:r,baseUrl:t="https://api.cycle.io",hubId:e,fetch:o}){const n=F({baseUrl:t,fetch:o||fetch}),i={async onRequest({request:s}){return s.headers.set("Authorization",`Bearer ${r}`),s.headers.set("X-Hub-Id",e),s}};return n.use(i),n}p.getClient=V,p.getJobProgress=P,p.trackJob=K,p.zeroTimeString=z,Object.defineProperty(p,Symbol.toStringTag,{value:"Module"})});
1
+ (function(p,E){typeof exports=="object"&&typeof module<"u"?E(exports):typeof define=="function"&&define.amd?define(["exports"],E):(p=typeof globalThis<"u"?globalThis:p||self,E(p["Cycle API Client"]={}))})(this,(function(p){"use strict";const E=/\{[^{}]+\}/g,Q=()=>{var r,t;return typeof process=="object"&&Number.parseInt((t=(r=process==null?void 0:process.versions)==null?void 0:r.node)==null?void 0:t.substring(0,2))>=18&&process.versions.undici};function _(){return Math.random().toString(36).slice(2,11)}function X(r){let{baseUrl:t="",Request:e=globalThis.Request,fetch:o=globalThis.fetch,querySerializer:n,bodySerializer:i,headers:s,requestInitExt:l=void 0,...h}={...r};l=Q()?l:void 0,t=J(t);const R=[];async function y(c,a){const{baseUrl:w,fetch:B=o,Request:F=e,headers:N,params:j={},parseAs:q="json",querySerializer:v,bodySerializer:W=i??K,body:G,middleware:ne=[],...x}=a||{};let I=t;w&&(I=J(w)??t);let U=typeof n=="function"?n:P(n);v&&(U=typeof v=="function"?v:P({...typeof n=="object"?n:{},...v}));const k=G===void 0?void 0:W(G,M(s,N,j.header)),oe=M(k===void 0||k instanceof FormData?{}:{"Content-Type":"application/json"},s,N,j.header),m=[...R,...ne],ie={redirect:"follow",...h,...x,body:k,headers:oe};let C,A,b=new F(V(c,{baseUrl:I,params:j,querySerializer:U}),ie),f;for(const d in x)d in b||(b[d]=x[d]);if(m.length){C=_(),A=Object.freeze({baseUrl:I,fetch:B,parseAs:q,querySerializer:U,bodySerializer:W});for(const d of m)if(d&&typeof d=="object"&&typeof d.onRequest=="function"){const u=await d.onRequest({request:b,schemaPath:c,params:j,options:A,id:C});if(u)if(u instanceof F)b=u;else if(u instanceof Response){f=u;break}else throw new Error("onRequest: must return new Request() or Response() when modifying the request")}}if(!f){try{f=await B(b,l)}catch(d){let u=d;if(m.length)for(let g=m.length-1;g>=0;g--){const $=m[g];if($&&typeof $=="object"&&typeof $.onError=="function"){const T=await $.onError({request:b,error:u,schemaPath:c,params:j,options:A,id:C});if(T){if(T instanceof Response){u=void 0,f=T;break}if(T instanceof Error){u=T;continue}throw new Error("onError: must return new Response() or instance of Error")}}}if(u)throw u}if(m.length)for(let d=m.length-1;d>=0;d--){const u=m[d];if(u&&typeof u=="object"&&typeof u.onResponse=="function"){const g=await u.onResponse({request:b,response:f,schemaPath:c,params:j,options:A,id:C});if(g){if(!(g instanceof Response))throw new Error("onResponse: must return new Response() when modifying the response");f=g}}}}if(f.status===204||b.method==="HEAD"||f.headers.get("Content-Length")==="0")return f.ok?{data:void 0,response:f}:{error:void 0,response:f};if(f.ok)return q==="stream"?{data:f.body,response:f}:{data:await f[q](),response:f};let O=await f.text();try{O=JSON.parse(O)}catch{}return{error:O,response:f}}return{request(c,a,w){return y(a,{...w,method:c.toUpperCase()})},GET(c,a){return y(c,{...a,method:"GET"})},PUT(c,a){return y(c,{...a,method:"PUT"})},POST(c,a){return y(c,{...a,method:"POST"})},DELETE(c,a){return y(c,{...a,method:"DELETE"})},OPTIONS(c,a){return y(c,{...a,method:"OPTIONS"})},HEAD(c,a){return y(c,{...a,method:"HEAD"})},PATCH(c,a){return y(c,{...a,method:"PATCH"})},TRACE(c,a){return y(c,{...a,method:"TRACE"})},use(...c){for(const a of c)if(a){if(typeof a!="object"||!("onRequest"in a||"onResponse"in a||"onError"in a))throw new Error("Middleware must be an object with one of `onRequest()`, `onResponse() or `onError()`");R.push(a)}},eject(...c){for(const a of c){const w=R.indexOf(a);w!==-1&&R.splice(w,1)}}}}function S(r,t,e){if(t==null)return"";if(typeof t=="object")throw new Error("Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.");return`${r}=${(e==null?void 0:e.allowReserved)===!0?t:encodeURIComponent(t)}`}function D(r,t,e){if(!t||typeof t!="object")return"";const o=[],n={simple:",",label:".",matrix:";"}[e.style]||"&";if(e.style!=="deepObject"&&e.explode===!1){for(const l in t)o.push(l,e.allowReserved===!0?t[l]:encodeURIComponent(t[l]));const s=o.join(",");switch(e.style){case"form":return`${r}=${s}`;case"label":return`.${s}`;case"matrix":return`;${r}=${s}`;default:return s}}for(const s in t){const l=e.style==="deepObject"?`${r}[${s}]`:s;o.push(S(l,t[s],e))}const i=o.join(n);return e.style==="label"||e.style==="matrix"?`${n}${i}`:i}function H(r,t,e){if(!Array.isArray(t))return"";if(e.explode===!1){const i={form:",",spaceDelimited:"%20",pipeDelimited:"|"}[e.style]||",",s=(e.allowReserved===!0?t:t.map(l=>encodeURIComponent(l))).join(i);switch(e.style){case"simple":return s;case"label":return`.${s}`;case"matrix":return`;${r}=${s}`;default:return`${r}=${s}`}}const o={simple:",",label:".",matrix:";"}[e.style]||"&",n=[];for(const i of t)e.style==="simple"||e.style==="label"?n.push(e.allowReserved===!0?i:encodeURIComponent(i)):n.push(S(r,i,e));return e.style==="label"||e.style==="matrix"?`${o}${n.join(o)}`:n.join(o)}function P(r){return function(e){const o=[];if(e&&typeof e=="object")for(const n in e){const i=e[n];if(i!=null){if(Array.isArray(i)){if(i.length===0)continue;o.push(H(n,i,{style:"form",explode:!0,...r==null?void 0:r.array,allowReserved:(r==null?void 0:r.allowReserved)||!1}));continue}if(typeof i=="object"){o.push(D(n,i,{style:"deepObject",explode:!0,...r==null?void 0:r.object,allowReserved:(r==null?void 0:r.allowReserved)||!1}));continue}o.push(S(n,i,r))}}return o.join("&")}}function Z(r,t){let e=r;for(const o of r.match(E)??[]){let n=o.substring(1,o.length-1),i=!1,s="simple";if(n.endsWith("*")&&(i=!0,n=n.substring(0,n.length-1)),n.startsWith(".")?(s="label",n=n.substring(1)):n.startsWith(";")&&(s="matrix",n=n.substring(1)),!t||t[n]===void 0||t[n]===null)continue;const l=t[n];if(Array.isArray(l)){e=e.replace(o,H(n,l,{style:s,explode:i}));continue}if(typeof l=="object"){e=e.replace(o,D(n,l,{style:s,explode:i}));continue}if(s==="matrix"){e=e.replace(o,`;${S(n,l)}`);continue}e=e.replace(o,s==="label"?`.${encodeURIComponent(l)}`:encodeURIComponent(l))}return e}function K(r,t){return r instanceof FormData?r:t&&(t.get instanceof Function?t.get("Content-Type")??t.get("content-type"):t["Content-Type"]??t["content-type"])==="application/x-www-form-urlencoded"?new URLSearchParams(r).toString():JSON.stringify(r)}function V(r,t){var n;let e=`${t.baseUrl}${r}`;(n=t.params)!=null&&n.path&&(e=Z(e,t.params.path));let o=t.querySerializer(t.params.query??{});return o.startsWith("?")&&(o=o.substring(1)),o&&(e+=`?${o}`),e}function M(...r){const t=new Headers;for(const e of r){if(!e||typeof e!="object")continue;const o=e instanceof Headers?e.entries():Object.entries(e);for(const[n,i]of o)if(i===null)t.delete(n);else if(Array.isArray(i))for(const s of i)t.append(n,s);else i!==void 0&&t.set(n,i)}return t}function J(r){return r.endsWith("/")?r.substring(0,r.length-1):r}class Y extends EventTarget{constructor(t,e,o){super(),this.promise=this.track(t,e,o)}async track(t,e,o){const n=typeof e=="object"?e.id:e,i={pollingInterval:2e3,...o};let s=0;for(;;){const l=await t.GET("/v1/jobs/{jobId}",{params:{path:{jobId:n}}});if(l.error){if(s<5&&l.error.error.code==="404.job"){s++,await this.delay(i.pollingInterval);continue}throw l.error}const h=l.data.data,R=L(h);if(this.dispatchEvent(new CustomEvent("progress",{detail:{...R,state:h.state.current}})),ee(h)){if(h.state.current==="error")throw h;return this.dispatchEvent(new CustomEvent("done",{detail:h})),h}await this.delay(i.pollingInterval)}}delay(t=2e3){return new Promise(e=>setTimeout(e,t))}}function ee(r){return["completed","error","expired"].includes(r.state.current)}const z="0001-01-01T00:00:00Z";function L(r){if(!r.tasks||r.tasks.length===0)return{total:0,completed:0,failed:0,percent:100};const t=r.tasks.reduce((e,o)=>{var i,s,l;const n=((i=o.steps)==null?void 0:i.length)||1;if(e.total+=n,o.state.current==="pending")return e;if(!((s=o.steps)!=null&&s.length)){switch(o.state.current){case"completed":e.completed+=1;break;case"error":e.failed+=1}return e}return(l=o.steps)==null||l.forEach(h=>{if(h.completed!==z){e.completed+=1;return}["error","completed"].includes(o.state.current||"")&&h.started!==z&&(e.failed+=1)}),e},{total:0,completed:0,failed:0});return{...t,percent:t.completed/t.total*100}}function te(r,t,e){return new Y(r,t,e)}function re({apiKey:r,baseUrl:t="https://api.cycle.io",hubId:e,fetch:o}){const n=X({baseUrl:t,fetch:o||fetch}),i={async onRequest({request:s}){return s.headers.set("Authorization",`Bearer ${r}`),s.headers.set("X-Hub-Id",e),s}};return n.use(i),n}p.getClient=re,p.getJobProgress=L,p.trackJob=te,p.zeroTimeString=z,Object.defineProperty(p,Symbol.toStringTag,{value:"Module"})}));