@contello/client 2.2.2 → 2.3.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.cjs CHANGED
@@ -1,1182 +1,976 @@
1
- "use strict";
2
- var __create = Object.create;
3
- var __defProp = Object.defineProperty;
4
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
- var __getOwnPropNames = Object.getOwnPropertyNames;
6
- var __getProtoOf = Object.getPrototypeOf;
7
- var __hasOwnProp = Object.prototype.hasOwnProperty;
8
- var __export = (target, all) => {
9
- for (var name in all)
10
- __defProp(target, name, { get: all[name], enumerable: true });
11
- };
12
- var __copyProps = (to, from, except, desc) => {
13
- if (from && typeof from === "object" || typeof from === "function") {
14
- for (let key of __getOwnPropNames(from))
15
- if (!__hasOwnProp.call(to, key) && key !== except)
16
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
- }
18
- return to;
19
- };
20
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
- // If the importer is in node compatibility mode or this is not an ESM
22
- // file that has been converted to a CommonJS file using a Babel-
23
- // compatible transform (i.e. "__esModule" has not been set), then set
24
- // "default" to the CommonJS "module.exports" for node compatibility.
25
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
- mod
27
- ));
28
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
-
30
- // src/index.ts
31
- var index_exports = {};
32
- __export(index_exports, {
33
- ContelloClient: () => ContelloClient,
34
- asyncKeepalive: () => asyncKeepalive,
35
- collectAsync: () => collectAsync,
36
- createAsyncIterableSubject: () => createAsyncIterableSubject,
37
- createContelloClient: () => createContelloClient,
38
- createSourceSubscription: () => createSourceSubscription,
39
- exponentialBackoff: () => exponentialBackoff,
40
- filterAsync: () => filterAsync,
41
- firstAsync: () => firstAsync,
42
- mapAsync: () => mapAsync,
43
- runWithBackoff: () => runWithBackoff
44
- });
45
- module.exports = __toCommonJS(index_exports);
46
-
47
- // src/client.ts
48
- var import_graphql_ws = require("graphql-ws");
49
-
50
- // src/async-iterable-utils.ts
51
- var MAX_BACKOFF_MS = 3e4;
52
- var JITTER_MIN_MS = 300;
53
- var JITTER_MAX_MS = 3e3;
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ let _contello_opentelemetry = require("@contello/opentelemetry");
3
+ let graphql_ws = require("graphql-ws");
4
+ let undici = require("undici");
5
+ //#region src/async-iterable-utils.ts
6
+ const MAX_BACKOFF_MS = 3e4;
7
+ const JITTER_MIN_MS$1 = 300;
8
+ const JITTER_MAX_MS$1 = 3e3;
9
+ /**
10
+ * Returns the first value yielded by `iter`, then disposes the iterator. Throws if the iterable
11
+ * completes without yielding. Equivalent of rxjs's `firstValueFrom` for AsyncIterables.
12
+ */
54
13
  async function firstAsync(iter) {
55
- const it = iter[Symbol.asyncIterator]();
56
- try {
57
- const result = await it.next();
58
- if (result.done) {
59
- throw new Error("firstAsync: async iterable completed without yielding a value");
60
- }
61
- return result.value;
62
- } finally {
63
- await it.return?.();
64
- }
65
- }
14
+ const it = iter[Symbol.asyncIterator]();
15
+ try {
16
+ const result = await it.next();
17
+ if (result.done) throw new Error("firstAsync: async iterable completed without yielding a value");
18
+ return result.value;
19
+ } finally {
20
+ await it.return?.();
21
+ }
22
+ }
23
+ /** Lazy map over an async iterable. Cleanup propagates: breaking the outer iter disposes the inner. */
66
24
  async function* mapAsync(iter, fn) {
67
- for await (const value of iter) {
68
- yield fn(value);
69
- }
25
+ for await (const value of iter) yield fn(value);
70
26
  }
27
+ /** Lazy filter over an async iterable. */
71
28
  async function* filterAsync(iter, predicate) {
72
- for await (const value of iter) {
73
- if (predicate(value)) {
74
- yield value;
75
- }
76
- }
29
+ for await (const value of iter) if (predicate(value)) yield value;
77
30
  }
31
+ /**
32
+ * Concatenates all elements of all arrays yielded by `iter` into a single array. Used to support
33
+ * subscriptions that emit chunks of items before completing.
34
+ */
78
35
  async function collectAsync(iter) {
79
- const out = [];
80
- for await (const chunk of iter) {
81
- out.push(...chunk);
82
- }
83
- return out;
84
- }
36
+ const out = [];
37
+ for await (const chunk of iter) out.push(...chunk);
38
+ return out;
39
+ }
40
+ /**
41
+ * Exponential backoff with jitter. `attempt` starts at 0 → ~1s+jitter, 1 → ~2s+jitter, etc.,
42
+ * capped at 30s. Returns a Promise that resolves after the delay.
43
+ */
85
44
  function exponentialBackoff(attempt) {
86
- const base = Math.min(Math.pow(2, attempt) * 1e3, MAX_BACKOFF_MS);
87
- const jitter = Math.floor(Math.random() * (JITTER_MAX_MS - JITTER_MIN_MS) + JITTER_MIN_MS);
88
- return delay(base + jitter);
45
+ return delay(Math.min(Math.pow(2, attempt) * 1e3, MAX_BACKOFF_MS) + Math.floor(Math.random() * (JITTER_MAX_MS$1 - JITTER_MIN_MS$1) + JITTER_MIN_MS$1));
89
46
  }
90
47
  function delay(ms, signal) {
91
- if (signal?.aborted) {
92
- return Promise.reject(signal.reason);
93
- }
94
- return new Promise((resolve, reject) => {
95
- const timer = setTimeout(() => {
96
- signal?.removeEventListener("abort", onAbort);
97
- resolve();
98
- }, ms);
99
- const onAbort = () => {
100
- clearTimeout(timer);
101
- reject(signal.reason);
102
- };
103
- signal?.addEventListener("abort", onAbort, { once: true });
104
- });
105
- }
48
+ if (signal?.aborted) return Promise.reject(signal.reason);
49
+ return new Promise((resolve, reject) => {
50
+ const timer = setTimeout(() => {
51
+ signal?.removeEventListener("abort", onAbort);
52
+ resolve();
53
+ }, ms);
54
+ const onAbort = () => {
55
+ clearTimeout(timer);
56
+ reject(signal.reason);
57
+ };
58
+ signal?.addEventListener("abort", onAbort, { once: true });
59
+ });
60
+ }
61
+ /**
62
+ * Runs `fn` with exponential-backoff retry on rejection. Returns once `fn` resolves successfully.
63
+ * `signal` aborts both the in-flight `fn` (if it observes the signal) and the backoff wait.
64
+ */
106
65
  async function runWithBackoff(fn, signal) {
107
- let attempt = 0;
108
- for (; ; ) {
109
- if (signal?.aborted) {
110
- throw signal.reason;
111
- }
112
- try {
113
- await fn();
114
- return;
115
- } catch {
116
- await exponentialBackoffWithSignal(attempt, signal);
117
- attempt++;
118
- }
119
- }
66
+ let attempt = 0;
67
+ for (;;) {
68
+ if (signal?.aborted) throw signal.reason;
69
+ try {
70
+ await fn();
71
+ return;
72
+ } catch {
73
+ await exponentialBackoffWithSignal(attempt, signal);
74
+ attempt++;
75
+ }
76
+ }
120
77
  }
121
78
  function exponentialBackoffWithSignal(attempt, signal) {
122
- const base = Math.min(Math.pow(2, attempt) * 1e3, MAX_BACKOFF_MS);
123
- const jitter = Math.floor(Math.random() * (JITTER_MAX_MS - JITTER_MIN_MS) + JITTER_MIN_MS);
124
- return delay(base + jitter, signal);
79
+ return delay(Math.min(Math.pow(2, attempt) * 1e3, MAX_BACKOFF_MS) + Math.floor(Math.random() * (JITTER_MAX_MS$1 - JITTER_MIN_MS$1) + JITTER_MIN_MS$1), signal);
125
80
  }
81
+ /**
82
+ * Long-running stream wrapper: subscribes via `factory()`, yields every value, and on error or
83
+ * unexpected completion re-subscribes with exponential backoff. Stops only when `signal` aborts.
84
+ * Designed for subscriptions that should stay open across reconnects (e.g. the watcher).
85
+ */
126
86
  async function* asyncKeepalive(factory, signal) {
127
- let attempt = 0;
128
- while (!signal?.aborted) {
129
- try {
130
- for await (const value of factory()) {
131
- if (signal?.aborted) {
132
- return;
133
- }
134
- yield value;
135
- attempt = 0;
136
- }
137
- attempt = 0;
138
- } catch (error) {
139
- if (signal?.aborted) {
140
- return;
141
- }
142
- void error;
143
- await exponentialBackoffWithSignal(attempt, signal);
144
- attempt++;
145
- }
146
- }
147
- }
148
-
149
- // src/diagnostics.ts
150
- var import_node_diagnostics_channel = __toESM(require("diagnostics_channel"), 1);
151
- var channels = {
152
- start: "@contello/client:start",
153
- end: "@contello/client:end",
154
- error: "@contello/client:error",
155
- /** subscribe to decorate outgoing GraphQL WebSocket messages (e.g. inject traceparent) */
156
- message: "@contello/client:message"
157
- };
158
- var onStart = import_node_diagnostics_channel.default.channel(channels.start);
159
- var onEnd = import_node_diagnostics_channel.default.channel(channels.end);
160
- var onError = import_node_diagnostics_channel.default.channel(channels.error);
161
- var onMessage = import_node_diagnostics_channel.default.channel(channels.message);
162
- function hasOperationSubscribers() {
163
- return onStart.hasSubscribers || onEnd.hasSubscribers || onError.hasSubscribers;
164
- }
165
- function wrap(name, fn) {
166
- if (!hasOperationSubscribers()) {
167
- return fn();
168
- }
169
- const start = performance.now();
170
- onStart.publish({ name });
171
- let result;
172
- try {
173
- result = fn();
174
- } catch (error) {
175
- onError.publish({ name, error, durationMs: performance.now() - start });
176
- throw error;
177
- }
178
- if (result instanceof Promise) {
179
- return result.then(
180
- (r) => {
181
- onEnd.publish({ name, durationMs: performance.now() - start });
182
- return r;
183
- },
184
- (error) => {
185
- onError.publish({ name, error, durationMs: performance.now() - start });
186
- throw error;
187
- }
188
- );
189
- }
190
- onEnd.publish({ name, durationMs: performance.now() - start });
191
- return result;
192
- }
193
- function decorateMessage(message) {
194
- if (!onMessage.hasSubscribers) {
195
- return message;
196
- }
197
- const msg = { message };
198
- onMessage.publish(msg);
199
- return msg.message;
200
- }
201
-
202
- // src/http.ts
203
- var import_undici = require("undici");
204
- var SAFE_SEGMENT = /^[A-Za-z0-9._-]+$/;
205
- var FORWARDED_PROXY_HEADERS = /* @__PURE__ */ new Set([
206
- "content-type",
207
- "content-length",
208
- "content-range",
209
- "content-encoding",
210
- "accept-ranges",
211
- "cache-control",
212
- "etag",
213
- "last-modified",
214
- "expires",
215
- "age"
87
+ let attempt = 0;
88
+ while (!signal?.aborted) try {
89
+ for await (const value of factory()) {
90
+ if (signal?.aborted) return;
91
+ yield value;
92
+ attempt = 0;
93
+ }
94
+ attempt = 0;
95
+ } catch (error) {
96
+ if (signal?.aborted) return;
97
+ await exponentialBackoffWithSignal(attempt, signal);
98
+ attempt++;
99
+ }
100
+ }
101
+ //#endregion
102
+ //#region src/http.ts
103
+ const SAFE_SEGMENT = /^[A-Za-z0-9._-]+$/;
104
+ const FORWARDED_PROXY_HEADERS = /* @__PURE__ */ new Set([
105
+ "content-type",
106
+ "content-length",
107
+ "content-range",
108
+ "content-encoding",
109
+ "accept-ranges",
110
+ "cache-control",
111
+ "etag",
112
+ "last-modified",
113
+ "expires",
114
+ "age"
216
115
  ]);
217
116
  function assertSafeSegment(segment, kind) {
218
- if (!SAFE_SEGMENT.test(segment) || segment === "." || segment === "..") {
219
- throw new Error(`invalid ${kind}`);
220
- }
117
+ if (!SAFE_SEGMENT.test(segment) || segment === "." || segment === "..") throw new Error(`invalid ${kind}`);
221
118
  }
222
119
  function assertSafeAssetPath(path, kind) {
223
- if (path === "") {
224
- throw new Error(`invalid ${kind}`);
225
- }
226
- for (const segment of path.split("/")) {
227
- assertSafeSegment(segment, kind);
228
- }
120
+ if (path === "") throw new Error(`invalid ${kind}`);
121
+ for (const segment of path.split("/")) assertSafeSegment(segment, kind);
229
122
  }
230
123
  function createHttpAgent(options) {
231
- return new import_undici.Agent({
232
- pipelining: options?.pipelining ?? 10,
233
- allowH2: options?.allowH2 ?? true,
234
- maxConcurrentStreams: options?.maxConcurrentStreams ?? 128,
235
- keepAliveTimeout: options?.keepAliveTimeout ?? 6e4,
236
- autoSelectFamily: true,
237
- autoSelectFamilyAttemptTimeout: 25
238
- });
124
+ return new undici.Agent({
125
+ pipelining: options?.pipelining ?? 10,
126
+ allowH2: options?.allowH2 ?? true,
127
+ maxConcurrentStreams: options?.maxConcurrentStreams ?? 128,
128
+ keepAliveTimeout: options?.keepAliveTimeout ?? 6e4,
129
+ autoSelectFamily: true,
130
+ autoSelectFamilyAttemptTimeout: 25
131
+ });
239
132
  }
240
133
  async function downloadFile(agent, url, token, fileId) {
241
- assertSafeSegment(fileId, "file id");
242
- const response = await (0, import_undici.request)(`${url}/api/v1/assets/files/${fileId}`, {
243
- headers: { token },
244
- dispatcher: agent
245
- });
246
- if (response.statusCode < 200 || response.statusCode >= 300) {
247
- safeDestroyBody(response.body);
248
- throw new Error(`download failed: ${response.statusCode}`);
249
- }
250
- const mimeType = firstHeader(response.headers, "content-type") ?? "application/octet-stream";
251
- const size = Number(firstHeader(response.headers, "content-length") ?? 0);
252
- return {
253
- mimeType,
254
- size,
255
- bytes: async () => new Uint8Array(await response.body.arrayBuffer()),
256
- stream: () => toWebStream(response.body)
257
- };
134
+ assertSafeSegment(fileId, "file id");
135
+ const response = await (0, undici.request)(`${url}/api/v1/assets/files/${fileId}`, {
136
+ headers: { token },
137
+ dispatcher: agent
138
+ });
139
+ if (response.statusCode < 200 || response.statusCode >= 300) {
140
+ safeDestroyBody(response.body);
141
+ throw new Error(`download failed: ${response.statusCode}`);
142
+ }
143
+ return {
144
+ mimeType: firstHeader(response.headers, "content-type") ?? "application/octet-stream",
145
+ size: Number(firstHeader(response.headers, "content-length") ?? 0),
146
+ bytes: async () => new Uint8Array(await response.body.arrayBuffer()),
147
+ stream: () => toWebStream(response.body)
148
+ };
258
149
  }
259
150
  async function proxyHls(agent, url, token, path, signal) {
260
- assertSafeAssetPath(path, "hls path");
261
- const response = await (0, import_undici.request)(`${url}/api/v1/assets/video/hls/${path}`, {
262
- headers: { token },
263
- dispatcher: agent,
264
- signal: signal ?? null
265
- });
266
- return buildProxyResult(response, signal);
151
+ assertSafeAssetPath(path, "hls path");
152
+ return buildProxyResult(await (0, undici.request)(`${url}/api/v1/assets/video/hls/${path}`, {
153
+ headers: { token },
154
+ dispatcher: agent,
155
+ signal: signal ?? null
156
+ }), signal);
267
157
  }
268
158
  function buildProxyResult(response, signal) {
269
- const headers = new Headers();
270
- for (const [key, value] of Object.entries(response.headers)) {
271
- if (!FORWARDED_PROXY_HEADERS.has(key.toLowerCase())) {
272
- continue;
273
- }
274
- if (Array.isArray(value)) {
275
- for (const v of value) headers.append(key, v);
276
- } else if (value !== null && value !== void 0) {
277
- headers.set(key, String(value));
278
- }
279
- }
280
- return {
281
- status: response.statusCode,
282
- headers,
283
- stream: () => toWebStream(response.body, signal)
284
- };
159
+ const headers = new Headers();
160
+ for (const [key, value] of Object.entries(response.headers)) {
161
+ if (!FORWARDED_PROXY_HEADERS.has(key.toLowerCase())) continue;
162
+ if (Array.isArray(value)) for (const v of value) headers.append(key, v);
163
+ else if (value !== null && value !== void 0) headers.set(key, value);
164
+ }
165
+ return {
166
+ status: response.statusCode,
167
+ headers,
168
+ stream: () => toWebStream(response.body, signal)
169
+ };
285
170
  }
286
171
  function firstHeader(headers, key) {
287
- const v = headers[key];
288
- return Array.isArray(v) ? v[0] : v;
172
+ const v = headers[key];
173
+ return Array.isArray(v) ? v[0] : v;
289
174
  }
290
175
  function safeDestroyBody(body) {
291
- try {
292
- body.on("error", () => {
293
- });
294
- body.destroy();
295
- } catch {
296
- }
176
+ try {
177
+ body.on("error", () => {});
178
+ body.destroy();
179
+ } catch {}
297
180
  }
298
181
  function toWebStream(body, signal) {
299
- let closed = false;
300
- const cleanup = () => {
301
- if (!closed) {
302
- closed = true;
303
- signal?.removeEventListener("abort", cleanup);
304
- safeDestroyBody(body);
305
- }
306
- };
307
- return new ReadableStream({
308
- start(controller) {
309
- signal?.addEventListener("abort", cleanup);
310
- body.on("data", (chunk) => {
311
- if (!closed && !signal?.aborted) {
312
- try {
313
- controller.enqueue(chunk);
314
- } catch {
315
- cleanup();
316
- }
317
- }
318
- });
319
- body.on("end", () => {
320
- if (!closed && !signal?.aborted) {
321
- closed = true;
322
- signal?.removeEventListener("abort", cleanup);
323
- try {
324
- controller.close();
325
- } catch {
326
- }
327
- }
328
- });
329
- body.on("error", (err) => {
330
- cleanup();
331
- if (err.name === "AbortError") {
332
- try {
333
- controller.close();
334
- } catch {
335
- }
336
- return;
337
- }
338
- try {
339
- controller.error(err);
340
- } catch {
341
- }
342
- });
343
- },
344
- cancel() {
345
- cleanup();
346
- }
347
- });
348
- }
349
-
350
- // src/ping.ts
351
- var PING_QUERY = `query ContelloPing { contelloPing { response } }`;
182
+ let closed = false;
183
+ const cleanup = () => {
184
+ if (closed) return;
185
+ closed = true;
186
+ signal?.removeEventListener("abort", cleanup);
187
+ safeDestroyBody(body);
188
+ };
189
+ return new ReadableStream({
190
+ start(controller) {
191
+ signal?.addEventListener("abort", cleanup);
192
+ body.on("data", (chunk) => {
193
+ if (closed || signal?.aborted) return;
194
+ try {
195
+ controller.enqueue(chunk);
196
+ } catch {
197
+ cleanup();
198
+ }
199
+ });
200
+ body.on("end", () => {
201
+ if (closed || signal?.aborted) return;
202
+ closed = true;
203
+ signal?.removeEventListener("abort", cleanup);
204
+ try {
205
+ controller.close();
206
+ } catch {}
207
+ });
208
+ body.on("error", (err) => {
209
+ cleanup();
210
+ if (err.name === "AbortError") {
211
+ try {
212
+ controller.close();
213
+ } catch {}
214
+ return;
215
+ }
216
+ try {
217
+ controller.error(err);
218
+ } catch {}
219
+ });
220
+ },
221
+ cancel() {
222
+ cleanup();
223
+ }
224
+ });
225
+ }
226
+ //#endregion
227
+ //#region src/ping.ts
228
+ const PING_QUERY = `query ContelloPing { contelloPing { response } }`;
352
229
  async function ping(execute) {
353
- const data = await execute(PING_QUERY);
354
- if (data.contelloPing.response !== "pong") {
355
- throw new Error(`unexpected ping response: ${data.contelloPing.response}`);
356
- }
230
+ const data = await execute(PING_QUERY);
231
+ if (data.contelloPing.response !== "pong") throw new Error(`unexpected ping response: ${data.contelloPing.response}`);
357
232
  }
358
-
359
- // src/pool.ts
360
- var DEFAULT_CONNECT_TIMEOUT = 1e4;
233
+ //#endregion
234
+ //#region src/pool.ts
235
+ const DEFAULT_CONNECT_TIMEOUT = 1e4;
361
236
  var ConnectionPool = class {
362
- constructor(_createClient, _poolSize, _connectTimeout = DEFAULT_CONNECT_TIMEOUT) {
363
- this._createClient = _createClient;
364
- this._poolSize = _poolSize;
365
- this._connectTimeout = _connectTimeout;
366
- }
367
- _clients = [];
368
- _connected = [];
369
- _currentIndex = 0;
370
- async connect() {
371
- const ready = [];
372
- for (let i = 0; i < this._poolSize; i++) {
373
- const index = i;
374
- const client = this._createClient(`${i + 1}`);
375
- this._clients.push(client);
376
- this._connected.push(false);
377
- client.on("connected", () => {
378
- this._connected[index] = true;
379
- });
380
- client.on("closed", () => {
381
- this._connected[index] = false;
382
- });
383
- ready.push(
384
- new Promise((resolve) => {
385
- let settled = false;
386
- const done = () => {
387
- if (settled) {
388
- return;
389
- }
390
- settled = true;
391
- offConnected();
392
- clearTimeout(timer);
393
- resolve();
394
- };
395
- const offConnected = client.on("connected", done);
396
- const timer = setTimeout(done, this._connectTimeout);
397
- timer.unref?.();
398
- })
399
- );
400
- }
401
- await Promise.all(ready);
402
- }
403
- get() {
404
- if (this._clients.length === 0) {
405
- throw new Error("@contello/client: connection pool is empty \u2014 call client.init() first");
406
- }
407
- for (let i = 0; i < this._clients.length; i++) {
408
- const index = (this._currentIndex + i) % this._clients.length;
409
- if (this._connected[index]) {
410
- this._currentIndex = (index + 1) % this._clients.length;
411
- return this._clients[index];
412
- }
413
- }
414
- const client = this._clients[this._currentIndex];
415
- this._currentIndex = (this._currentIndex + 1) % this._clients.length;
416
- return client;
417
- }
418
- async disconnect() {
419
- const closed = this._clients.map(
420
- (client) => new Promise((resolve) => {
421
- const unsubscribe = client.on("closed", () => {
422
- unsubscribe();
423
- resolve();
424
- });
425
- client.dispose();
426
- })
427
- );
428
- this._clients = [];
429
- this._connected = [];
430
- this._currentIndex = 0;
431
- await Promise.all(closed);
432
- }
237
+ _createClient;
238
+ _poolSize;
239
+ _connectTimeout;
240
+ _clients = [];
241
+ _connected = [];
242
+ _currentIndex = 0;
243
+ constructor(_createClient, _poolSize, _connectTimeout = DEFAULT_CONNECT_TIMEOUT) {
244
+ this._createClient = _createClient;
245
+ this._poolSize = _poolSize;
246
+ this._connectTimeout = _connectTimeout;
247
+ }
248
+ async connect() {
249
+ const ready = [];
250
+ for (let i = 0; i < this._poolSize; i++) {
251
+ const index = i;
252
+ const client = this._createClient(String(i + 1));
253
+ this._clients.push(client);
254
+ this._connected.push(false);
255
+ client.on("connected", () => {
256
+ this._connected[index] = true;
257
+ });
258
+ client.on("closed", () => {
259
+ this._connected[index] = false;
260
+ });
261
+ ready.push(new Promise((resolve) => {
262
+ let settled = false;
263
+ const done = () => {
264
+ if (settled) return;
265
+ settled = true;
266
+ offConnected();
267
+ clearTimeout(timer);
268
+ resolve();
269
+ };
270
+ const offConnected = client.on("connected", done);
271
+ const timer = setTimeout(done, this._connectTimeout);
272
+ timer.unref?.();
273
+ }));
274
+ }
275
+ await Promise.all(ready);
276
+ }
277
+ get() {
278
+ if (this._clients.length === 0) throw new Error("@contello/client: connection pool is empty — call client.init() first");
279
+ for (let i = 0; i < this._clients.length; i++) {
280
+ const index = (this._currentIndex + i) % this._clients.length;
281
+ if (this._connected[index] === true) {
282
+ this._currentIndex = (index + 1) % this._clients.length;
283
+ return this._clients[index];
284
+ }
285
+ }
286
+ const client = this._clients[this._currentIndex];
287
+ this._currentIndex = (this._currentIndex + 1) % this._clients.length;
288
+ return client;
289
+ }
290
+ async disconnect() {
291
+ const closed = this._clients.map((client) => new Promise((resolve) => {
292
+ const unsubscribe = client.on("closed", () => {
293
+ unsubscribe();
294
+ resolve();
295
+ });
296
+ client.dispose();
297
+ }));
298
+ this._clients = [];
299
+ this._connected = [];
300
+ this._currentIndex = 0;
301
+ await Promise.all(closed);
302
+ }
433
303
  };
434
-
435
- // src/scalars.ts
436
- var LOCAL_DATE_TIME_KEYS = ["year", "month", "day", "hour", "minute", "second"];
437
- var LOCAL_DATE_KEYS = ["year", "month", "day"];
438
- var DATE_TIME_REGEX = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})/;
439
- var DATE_REGEX = /^(\d{4})-(\d{2})-(\d{2})/;
304
+ //#endregion
305
+ //#region src/telemetry.ts
306
+ const { wrap } = (0, _contello_opentelemetry.createOperationTelemetry)("@contello/client");
307
+ //#endregion
308
+ //#region src/scalars.ts
309
+ const LOCAL_DATE_TIME_KEYS = [
310
+ "year",
311
+ "month",
312
+ "day",
313
+ "hour",
314
+ "minute",
315
+ "second"
316
+ ];
317
+ const LOCAL_DATE_KEYS = [
318
+ "year",
319
+ "month",
320
+ "day"
321
+ ];
322
+ const DATE_TIME_REGEX = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})/;
323
+ const DATE_REGEX = /^(\d{4})-(\d{2})-(\d{2})/;
440
324
  function pad2(n) {
441
- return n.toString().padStart(2, "0");
325
+ return n.toString().padStart(2, "0");
442
326
  }
443
327
  function pad4(n) {
444
- return n.toString().padStart(4, "0");
328
+ return n.toString().padStart(4, "0");
445
329
  }
446
330
  function hasExactKeys(value, keys) {
447
- const ownKeys = Object.keys(value);
448
- if (ownKeys.length !== keys.length) {
449
- return false;
450
- }
451
- for (const key of keys) {
452
- if (!Object.prototype.hasOwnProperty.call(value, key)) {
453
- return false;
454
- }
455
- }
456
- return true;
331
+ if (Object.keys(value).length !== keys.length) return false;
332
+ for (const key of keys) if (!Object.prototype.hasOwnProperty.call(value, key)) return false;
333
+ return true;
457
334
  }
458
335
  function allNumbers(value, keys) {
459
- for (const key of keys) {
460
- if (typeof value[key] !== "number") {
461
- return false;
462
- }
463
- }
464
- return true;
336
+ for (const key of keys) if (typeof value[key] !== "number") return false;
337
+ return true;
465
338
  }
466
339
  function isLocalDateTime(value) {
467
- return !!value && typeof value === "object" && !Array.isArray(value) && hasExactKeys(value, LOCAL_DATE_TIME_KEYS) && allNumbers(value, LOCAL_DATE_TIME_KEYS);
340
+ return !!value && typeof value === "object" && !Array.isArray(value) && hasExactKeys(value, LOCAL_DATE_TIME_KEYS) && allNumbers(value, LOCAL_DATE_TIME_KEYS);
468
341
  }
469
342
  function isLocalDate(value) {
470
- return !!value && typeof value === "object" && !Array.isArray(value) && hasExactKeys(value, LOCAL_DATE_KEYS) && allNumbers(value, LOCAL_DATE_KEYS);
343
+ return !!value && typeof value === "object" && !Array.isArray(value) && hasExactKeys(value, LOCAL_DATE_KEYS) && allNumbers(value, LOCAL_DATE_KEYS);
471
344
  }
472
345
  function decodeLocalDateTime(value) {
473
- const match = DATE_TIME_REGEX.exec(value);
474
- if (!match) {
475
- throw new Error(`@contello/client: cannot decode LocalDateTime from "${value}"`);
476
- }
477
- return {
478
- year: Number(match[1]),
479
- month: Number(match[2]),
480
- day: Number(match[3]),
481
- hour: Number(match[4]),
482
- minute: Number(match[5]),
483
- second: Number(match[6])
484
- };
346
+ const match = DATE_TIME_REGEX.exec(value);
347
+ if (!match) throw new Error(`@contello/client: cannot decode LocalDateTime from "${value}"`);
348
+ return {
349
+ year: Number(match[1]),
350
+ month: Number(match[2]),
351
+ day: Number(match[3]),
352
+ hour: Number(match[4]),
353
+ minute: Number(match[5]),
354
+ second: Number(match[6])
355
+ };
485
356
  }
486
357
  function decodeLocalDate(value) {
487
- const match = DATE_REGEX.exec(value);
488
- if (!match) {
489
- throw new Error(`@contello/client: cannot decode LocalDate from "${value}"`);
490
- }
491
- return {
492
- year: Number(match[1]),
493
- month: Number(match[2]),
494
- day: Number(match[3])
495
- };
358
+ const match = DATE_REGEX.exec(value);
359
+ if (!match) throw new Error(`@contello/client: cannot decode LocalDate from "${value}"`);
360
+ return {
361
+ year: Number(match[1]),
362
+ month: Number(match[2]),
363
+ day: Number(match[3])
364
+ };
496
365
  }
497
366
  function encodeLocalDateTime(value) {
498
- return `${pad4(value.year)}-${pad2(value.month)}-${pad2(value.day)}T${pad2(value.hour)}:${pad2(value.minute)}:${pad2(value.second)}Z`;
367
+ return `${pad4(value.year)}-${pad2(value.month)}-${pad2(value.day)}T${pad2(value.hour)}:${pad2(value.minute)}:${pad2(value.second)}Z`;
499
368
  }
500
369
  function encodeLocalDate(value) {
501
- return `${pad4(value.year)}-${pad2(value.month)}-${pad2(value.day)}T00:00:00Z`;
502
- }
503
-
504
- // src/transform-variables.ts
370
+ return `${pad4(value.year)}-${pad2(value.month)}-${pad2(value.day)}T00:00:00Z`;
371
+ }
372
+ //#endregion
373
+ //#region src/transform-variables.ts
374
+ /**
375
+ * encodes outgoing variables: LocalDateTime / LocalDate POJOs become wire strings.
376
+ * detection is by shape — generated input types use the struct types, so consumers
377
+ * pass structs in the right places, and stray objects with the same shape would be
378
+ * an extremely unusual coincidence.
379
+ */
505
380
  function transformVariables(value) {
506
- if (value === null || value === void 0) {
507
- return value;
508
- }
509
- if (Array.isArray(value)) {
510
- return value.map((item) => transformVariables(item));
511
- }
512
- if (typeof value !== "object") {
513
- return value;
514
- }
515
- if (isLocalDateTime(value)) {
516
- return encodeLocalDateTime(value);
517
- }
518
- if (isLocalDate(value)) {
519
- return encodeLocalDate(value);
520
- }
521
- const obj = value;
522
- const out = {};
523
- for (const key of Object.keys(obj)) {
524
- out[key] = transformVariables(obj[key]);
525
- }
526
- return out;
527
- }
528
-
529
- // src/rpc.ts
381
+ if (value === null || value === void 0) return value;
382
+ if (Array.isArray(value)) return value.map((item) => transformVariables(item));
383
+ if (typeof value !== "object") return value;
384
+ if (isLocalDateTime(value)) return encodeLocalDateTime(value);
385
+ if (isLocalDate(value)) return encodeLocalDate(value);
386
+ const obj = value;
387
+ const out = {};
388
+ for (const [key, val] of Object.entries(obj)) out[key] = transformVariables(val);
389
+ return out;
390
+ }
391
+ //#endregion
392
+ //#region src/rpc.ts
530
393
  function buildRpc(operations, subscribe) {
531
- const rpc = {};
532
- for (const [name, def] of Object.entries(operations)) {
533
- rpc[name] = def.kind === "subscription" ? (variables) => subscribe(def.document, transformVariables(variables)) : (variables) => wrap(`rpc:${name}`, () => firstAsync(subscribe(def.document, transformVariables(variables))));
534
- }
535
- return rpc;
536
- }
537
-
538
- // src/source-subscription.ts
539
- var cache = /* @__PURE__ */ new WeakMap();
394
+ const rpc = {};
395
+ for (const [name, def] of Object.entries(operations)) rpc[name] = def.kind === "subscription" ? (variables) => subscribe(def.document, transformVariables(variables)) : (variables) => {
396
+ const vars = transformVariables(variables);
397
+ return wrap(`rpc:${name}`, () => firstAsync(subscribe(def.document, vars)), (0, _contello_opentelemetry.graphqlOperationAttributes)(def.document, vars));
398
+ };
399
+ return rpc;
400
+ }
401
+ //#endregion
402
+ //#region src/source-subscription.ts
403
+ const cache = /* @__PURE__ */ new WeakMap();
540
404
  function createSelection(source) {
541
- const spread = `{ ...${source.fragment} }`;
542
- switch (source.__cardinality) {
543
- case "singleton": {
544
- return `subscription { source: ${source.subscription} ${spread} }`;
545
- }
546
- case "entity": {
547
- return `subscription($ids: [ID!]) { source: ${source.subscription}(request: { filter: { ids: $ids } }) ${spread} }`;
548
- }
549
- case "route": {
550
- return `subscription($ids: [ID!], $paths: [String!]) { source: ${source.subscription}(request: { ids: $ids, paths: $paths }) ${spread} }`;
551
- }
552
- case "asset": {
553
- return `subscription($ids: [ID!]) { source: ${source.subscription}(filter: { ids: $ids }) ${spread} }`;
554
- }
555
- case "i18nMessage": {
556
- return `subscription($collection: String!, $ids: [ID!]) { source: ${source.subscription}(collectionReferenceName: $collection, ids: $ids) ${spread} }`;
557
- }
558
- }
405
+ const spread = `{ ...${source.fragment} }`;
406
+ switch (source.__cardinality) {
407
+ case "singleton": return `subscription { source: ${source.subscription} ${spread} }`;
408
+ case "entity": return `subscription($ids: [ID!]) { source: ${source.subscription}(request: { filter: { ids: $ids } }) ${spread} }`;
409
+ case "route": return `subscription($ids: [ID!], $paths: [String!]) { source: ${source.subscription}(request: { ids: $ids, paths: $paths }) ${spread} }`;
410
+ case "asset": return `subscription($ids: [ID!]) { source: ${source.subscription}(filter: { ids: $ids }) ${spread} }`;
411
+ case "i18nMessage": return `subscription($collection: String!, $ids: [ID!]) { source: ${source.subscription}(collectionReferenceName: $collection, ids: $ids) ${spread} }`;
412
+ }
559
413
  }
560
414
  function createSourceSubscription(source) {
561
- const cached = cache.get(source);
562
- if (cached !== void 0) {
563
- return cached;
564
- }
565
- const doc = `${source.document}
566
- ${createSelection(source)}`;
567
- cache.set(source, doc);
568
- return doc;
569
- }
570
-
571
- // src/sources.ts
415
+ const cached = cache.get(source);
416
+ if (cached !== void 0) return cached;
417
+ const doc = `${source.document}\n${createSelection(source)}`;
418
+ cache.set(source, doc);
419
+ return doc;
420
+ }
421
+ //#endregion
422
+ //#region src/sources.ts
572
423
  function createSources(sources, subscribe) {
573
- const out = {};
574
- for (const [name, source] of Object.entries(sources)) {
575
- const def = source;
576
- const doc = createSourceSubscription(def);
577
- switch (def.__cardinality) {
578
- case "singleton": {
579
- out[name] = {
580
- fetch: () => wrap(`source:${name}`, () => firstAsync(mapAsync(subscribe(doc), (r) => r.source)))
581
- };
582
- break;
583
- }
584
- case "entity": {
585
- out[name] = {
586
- fetch: (vars) => wrap(
587
- `source:${name}`,
588
- () => collectAsync(
589
- mapAsync(
590
- subscribe(doc, transformVariables({ ids: vars?.ids })),
591
- (r) => r.source
592
- )
593
- )
594
- )
595
- };
596
- break;
597
- }
598
- case "route": {
599
- out[name] = {
600
- fetch: (vars) => wrap(
601
- `source:${name}`,
602
- () => collectAsync(
603
- mapAsync(
604
- subscribe(doc, transformVariables({ ids: vars?.ids, paths: vars?.paths })),
605
- (r) => r.source
606
- )
607
- )
608
- )
609
- };
610
- break;
611
- }
612
- case "asset": {
613
- out[name] = {
614
- fetch: (vars) => wrap(
615
- `source:${name}`,
616
- () => collectAsync(
617
- mapAsync(
618
- subscribe(doc, transformVariables({ ids: vars?.ids })),
619
- (r) => r.source
620
- )
621
- )
622
- )
623
- };
624
- break;
625
- }
626
- case "i18nMessage": {
627
- out[name] = {
628
- fetch: (vars) => wrap(
629
- `source:${name}`,
630
- () => collectAsync(
631
- mapAsync(
632
- subscribe(
633
- doc,
634
- transformVariables({ collection: vars.collection, ids: vars.ids })
635
- ),
636
- (r) => r.source
637
- )
638
- )
639
- )
640
- };
641
- break;
642
- }
643
- }
644
- }
645
- return out;
646
- }
647
-
648
- // src/transform-response.ts
649
- var FLAT_PREFIX = "_flat_";
650
- var LDT_PREFIX = "_ldt_";
651
- var LD_PREFIX = "_ld_";
652
- var MODEL_SUFFIXES = ["Entity", "Component"];
424
+ const out = {};
425
+ for (const [name, source] of Object.entries(sources)) {
426
+ const def = source;
427
+ const accessor = createSourceAccessor(name, def, createSourceSubscription(def), subscribe);
428
+ if (accessor) out[name] = accessor;
429
+ }
430
+ return out;
431
+ }
432
+ function createSourceAccessor(name, def, doc, subscribe) {
433
+ switch (def.__cardinality) {
434
+ case "singleton": return { fetch: () => wrap(`source:${name}`, () => firstAsync(mapAsync(subscribe(doc), (r) => r.source)), (0, _contello_opentelemetry.graphqlOperationAttributes)(doc)) };
435
+ case "entity": return { fetch: (vars) => {
436
+ const variables = transformVariables({ ids: vars?.ids });
437
+ return wrap(`source:${name}`, () => collectAsync(mapAsync(subscribe(doc, variables), (r) => r.source)), (0, _contello_opentelemetry.graphqlOperationAttributes)(doc, variables));
438
+ } };
439
+ case "route": return { fetch: (vars) => {
440
+ const variables = transformVariables({
441
+ ids: vars?.ids,
442
+ paths: vars?.paths
443
+ });
444
+ return wrap(`source:${name}`, () => collectAsync(mapAsync(subscribe(doc, variables), (r) => r.source)), (0, _contello_opentelemetry.graphqlOperationAttributes)(doc, variables));
445
+ } };
446
+ case "asset": return { fetch: (vars) => {
447
+ const variables = transformVariables({ ids: vars?.ids });
448
+ return wrap(`source:${name}`, () => collectAsync(mapAsync(subscribe(doc, variables), (r) => r.source)), (0, _contello_opentelemetry.graphqlOperationAttributes)(doc, variables));
449
+ } };
450
+ case "i18nMessage": return { fetch: (vars) => {
451
+ const variables = transformVariables({
452
+ collection: vars.collection,
453
+ ids: vars.ids
454
+ });
455
+ return wrap(`source:${name}`, () => collectAsync(mapAsync(subscribe(doc, variables), (r) => r.source)), (0, _contello_opentelemetry.graphqlOperationAttributes)(doc, variables));
456
+ } };
457
+ }
458
+ }
459
+ //#endregion
460
+ //#region src/transform-response.ts
461
+ const FLAT_PREFIX = "_flat_";
462
+ const LDT_PREFIX = "_ldt_";
463
+ const LD_PREFIX = "_ld_";
464
+ const MODEL_SUFFIXES = ["Entity", "Component"];
653
465
  function decodeValue(value, decoder) {
654
- if (value === null || value === void 0) {
655
- return value;
656
- }
657
- if (Array.isArray(value)) {
658
- return value.map((item) => decodeValue(item, decoder));
659
- }
660
- if (typeof value === "string") {
661
- return decoder(value);
662
- }
663
- return value;
466
+ if (value === null || value === void 0) return value;
467
+ if (Array.isArray(value)) return value.map((item) => decodeValue(item, decoder));
468
+ if (typeof value === "string") return decoder(value);
469
+ return value;
664
470
  }
665
471
  function deriveModel(typename) {
666
- for (const suffix of MODEL_SUFFIXES) {
667
- if (typename.endsWith(suffix)) {
668
- const stripped = typename.slice(0, -suffix.length);
669
- return stripped.charAt(0).toLowerCase() + stripped.slice(1);
670
- }
671
- }
672
- return void 0;
673
- }
472
+ for (const suffix of MODEL_SUFFIXES) if (typename.endsWith(suffix)) {
473
+ const stripped = typename.slice(0, -suffix.length);
474
+ return stripped.charAt(0).toLowerCase() + stripped.slice(1);
475
+ }
476
+ }
477
+ /**
478
+ * transforms a GraphQL response in a single depth-first pass:
479
+ * - resolves `_flat_{field}` companions into nested component arrays (refs are
480
+ * matched against the companion map by `_flatId`, at any nesting depth — the
481
+ * companion lists the whole subtree, so one map serves every ref below it)
482
+ * - injects `__model` on objects with entity/component `__typename`
483
+ * - decodes managed scalar aliases (`_ldt_` / `_ld_`) into structured values
484
+ *
485
+ * a `seen` set guards against shared or cyclic references so every object is
486
+ * visited exactly once.
487
+ */
674
488
  function transformResponse(data) {
675
- transformNode(data, void 0, /* @__PURE__ */ new WeakSet());
676
- return data;
489
+ transformNode(data, void 0, /* @__PURE__ */ new WeakSet());
490
+ return data;
677
491
  }
678
492
  function transformNode(value, flatMap, seen) {
679
- if (!value || typeof value !== "object") {
680
- return;
681
- }
682
- if (seen.has(value)) {
683
- return;
684
- }
685
- seen.add(value);
686
- if (Array.isArray(value)) {
687
- for (const item of value) {
688
- transformNode(item, flatMap, seen);
689
- }
690
- return;
691
- }
692
- const obj = value;
693
- const typename = obj["__typename"];
694
- if (typeof typename === "string") {
695
- const model = deriveModel(typename);
696
- if (model) {
697
- obj["__model"] = model;
698
- }
699
- }
700
- let ownMap;
701
- for (const key of Object.keys(obj)) {
702
- if (!key.startsWith(FLAT_PREFIX)) {
703
- continue;
704
- }
705
- const flatArray = obj[key];
706
- delete obj[key];
707
- if (!flatArray) {
708
- continue;
709
- }
710
- if (!ownMap) {
711
- ownMap = flatMap ? new Map(flatMap) : /* @__PURE__ */ new Map();
712
- }
713
- for (const component of flatArray) {
714
- if (component._flatId) {
715
- ownMap.set(component._flatId, component);
716
- }
717
- }
718
- }
719
- const resolveMap = ownMap ?? flatMap;
720
- for (const key of Object.keys(obj)) {
721
- if (key.startsWith(LDT_PREFIX)) {
722
- obj[key.slice(LDT_PREFIX.length)] = decodeValue(obj[key], decodeLocalDateTime);
723
- delete obj[key];
724
- continue;
725
- }
726
- if (key.startsWith(LD_PREFIX)) {
727
- obj[key.slice(LD_PREFIX.length)] = decodeValue(obj[key], decodeLocalDate);
728
- delete obj[key];
729
- continue;
730
- }
731
- const inner = obj[key];
732
- if (resolveMap && Array.isArray(inner) && inner.length > 0 && inner[0]?._flatId !== void 0) {
733
- obj[key] = resolveRefs(inner, resolveMap);
734
- }
735
- transformNode(obj[key], resolveMap, seen);
736
- }
493
+ if (!value || typeof value !== "object") return;
494
+ if (seen.has(value)) return;
495
+ seen.add(value);
496
+ if (Array.isArray(value)) {
497
+ for (const item of value) transformNode(item, flatMap, seen);
498
+ return;
499
+ }
500
+ const obj = value;
501
+ const typename = obj["__typename"];
502
+ if (typeof typename === "string") {
503
+ const model = deriveModel(typename);
504
+ if (model) obj["__model"] = model;
505
+ }
506
+ let ownMap;
507
+ for (const key of Object.keys(obj)) {
508
+ if (!key.startsWith(FLAT_PREFIX)) continue;
509
+ const flatArray = obj[key];
510
+ delete obj[key];
511
+ if (!flatArray) continue;
512
+ if (!ownMap) ownMap = flatMap ? new Map(flatMap) : /* @__PURE__ */ new Map();
513
+ for (const component of flatArray) if (component._flatId) ownMap.set(component._flatId, component);
514
+ }
515
+ const resolveMap = ownMap ?? flatMap;
516
+ for (const key of Object.keys(obj)) {
517
+ if (key.startsWith(LDT_PREFIX)) {
518
+ obj[key.slice(5)] = decodeValue(obj[key], decodeLocalDateTime);
519
+ delete obj[key];
520
+ continue;
521
+ }
522
+ if (key.startsWith(LD_PREFIX)) {
523
+ obj[key.slice(4)] = decodeValue(obj[key], decodeLocalDate);
524
+ delete obj[key];
525
+ continue;
526
+ }
527
+ const inner = obj[key];
528
+ if (resolveMap && Array.isArray(inner) && inner.length > 0 && inner[0]?._flatId !== void 0) obj[key] = resolveRefs(inner, resolveMap);
529
+ transformNode(obj[key], resolveMap, seen);
530
+ }
737
531
  }
738
532
  function resolveRefs(refs, flatMap) {
739
- const resolved = [];
740
- for (const ref of refs) {
741
- if (!ref._flatId) {
742
- continue;
743
- }
744
- const component = flatMap.get(ref._flatId);
745
- if (component) {
746
- resolved.push(component);
747
- }
748
- }
749
- return resolved;
750
- }
751
-
752
- // src/upload.ts
753
- var DEFAULT_CHUNK_SIZE = 4 * 1024 * 1024;
533
+ const resolved = [];
534
+ for (const ref of refs) {
535
+ if (!ref._flatId) continue;
536
+ const component = flatMap.get(ref._flatId);
537
+ if (component) resolved.push(component);
538
+ }
539
+ return resolved;
540
+ }
541
+ //#endregion
542
+ //#region src/upload.ts
543
+ const DEFAULT_CHUNK_SIZE = 4 * 1024 * 1024;
754
544
  function isUint8Array(data) {
755
- return data instanceof Uint8Array;
545
+ return data instanceof Uint8Array;
756
546
  }
757
547
  function upload(url, project, token, data, meta, options) {
758
- const chunkSize = options?.chunkSize ?? DEFAULT_CHUNK_SIZE;
759
- const wsUrl = `${url.replace(/^http/i, "ws")}/api/v1/assets/ws`;
760
- const size = isUint8Array(data) ? data.length : meta.size;
761
- return new Promise((resolve, reject) => {
762
- const ws = new WebSocket(wsUrl, "contello-file-upload-v1");
763
- let done = false;
764
- const cleanup = () => {
765
- options?.abort?.removeEventListener("abort", abortHandler);
766
- };
767
- const abortHandler = () => {
768
- if (!done) {
769
- ws.close();
770
- reject(new Error("upload aborted"));
771
- }
772
- };
773
- options?.abort?.addEventListener("abort", abortHandler);
774
- function sendBuffer(buf) {
775
- let offset = 0;
776
- while (offset < buf.length) {
777
- const chunk = buf.subarray(offset, offset + chunkSize);
778
- ws.send(chunk);
779
- offset += chunk.length;
780
- }
781
- ws.send(JSON.stringify({ type: "done" }));
782
- }
783
- const MAX_BUFFER_SIZE = 8 * 1024 * 1024;
784
- function waitForBufferedDrain() {
785
- return new Promise((resolveDrain, rejectDrain) => {
786
- const check = () => {
787
- if (options?.abort?.aborted) {
788
- rejectDrain(new Error("upload aborted"));
789
- return;
790
- }
791
- if (ws.bufferedAmount <= MAX_BUFFER_SIZE) {
792
- resolveDrain();
793
- return;
794
- }
795
- setTimeout(check, 50);
796
- };
797
- check();
798
- });
799
- }
800
- async function sendStream(stream) {
801
- const reader = stream.getReader();
802
- try {
803
- while (true) {
804
- const { done: streamDone, value } = await reader.read();
805
- if (streamDone) break;
806
- await waitForBufferedDrain();
807
- ws.send(value);
808
- }
809
- ws.send(JSON.stringify({ type: "done" }));
810
- } catch (error) {
811
- reject(error);
812
- ws.close();
813
- }
814
- }
815
- ws.addEventListener("open", () => {
816
- const initFrame = {
817
- type: "init",
818
- metadata: { ...meta, ...size === void 0 ? {} : { size }, projectRef: project },
819
- token
820
- };
821
- ws.send(JSON.stringify(initFrame));
822
- });
823
- ws.addEventListener("message", (event) => {
824
- const message = JSON.parse(String(event.data));
825
- if (message.type === "ack") {
826
- if (isUint8Array(data)) {
827
- sendBuffer(data);
828
- } else {
829
- sendStream(data);
830
- }
831
- return;
832
- }
833
- if (message.type === "done") {
834
- done = true;
835
- cleanup();
836
- ws.close();
837
- resolve(message.id);
838
- }
839
- });
840
- ws.addEventListener("error", () => {
841
- cleanup();
842
- reject(new Error("upload websocket error"));
843
- });
844
- ws.addEventListener("close", () => {
845
- cleanup();
846
- if (!done) {
847
- reject(new Error("connection closed before upload completed"));
848
- }
849
- });
850
- });
851
- }
852
-
853
- // src/utils.ts
854
- var MAX_DELAY_MS = 3e4;
855
- var JITTER_MIN_MS2 = 300;
856
- var JITTER_MAX_MS2 = 3e3;
548
+ const chunkSize = options?.chunkSize ?? DEFAULT_CHUNK_SIZE;
549
+ const wsUrl = `${url.replace(/^http/i, "ws")}/api/v1/assets/ws`;
550
+ const size = isUint8Array(data) ? data.length : meta.size;
551
+ return new Promise((resolve, reject) => {
552
+ const ws = new WebSocket(wsUrl, "contello-file-upload-v1");
553
+ let done = false;
554
+ const cleanup = () => {
555
+ options?.abort?.removeEventListener("abort", abortHandler);
556
+ };
557
+ const abortHandler = () => {
558
+ if (done) return;
559
+ ws.close();
560
+ reject(/* @__PURE__ */ new Error("upload aborted"));
561
+ };
562
+ options?.abort?.addEventListener("abort", abortHandler);
563
+ function sendBuffer(buf) {
564
+ let offset = 0;
565
+ while (offset < buf.length) {
566
+ const chunk = buf.subarray(offset, offset + chunkSize);
567
+ ws.send(chunk);
568
+ offset += chunk.length;
569
+ }
570
+ ws.send(JSON.stringify({ type: "done" }));
571
+ }
572
+ const MAX_BUFFER_SIZE = 8 * 1024 * 1024;
573
+ function waitForBufferedDrain() {
574
+ return new Promise((resolveDrain, rejectDrain) => {
575
+ const check = () => {
576
+ if (options?.abort?.aborted) {
577
+ rejectDrain(/* @__PURE__ */ new Error("upload aborted"));
578
+ return;
579
+ }
580
+ if (ws.bufferedAmount <= MAX_BUFFER_SIZE) {
581
+ resolveDrain();
582
+ return;
583
+ }
584
+ setTimeout(check, 50);
585
+ };
586
+ check();
587
+ });
588
+ }
589
+ async function sendStream(stream) {
590
+ const reader = stream.getReader();
591
+ try {
592
+ while (true) {
593
+ const { done: streamDone, value } = await reader.read();
594
+ if (streamDone) break;
595
+ await waitForBufferedDrain();
596
+ ws.send(value);
597
+ }
598
+ ws.send(JSON.stringify({ type: "done" }));
599
+ } catch (error) {
600
+ reject(error);
601
+ ws.close();
602
+ }
603
+ }
604
+ ws.addEventListener("open", () => {
605
+ const initFrame = {
606
+ type: "init",
607
+ metadata: {
608
+ ...meta,
609
+ ...size !== void 0 && { size },
610
+ projectRef: project
611
+ },
612
+ token
613
+ };
614
+ ws.send(JSON.stringify(initFrame));
615
+ });
616
+ ws.addEventListener("message", (event) => {
617
+ const message = JSON.parse(String(event.data));
618
+ if (message.type === "ack") {
619
+ if (isUint8Array(data)) sendBuffer(data);
620
+ else sendStream(data);
621
+ return;
622
+ }
623
+ if (message.type === "done") {
624
+ done = true;
625
+ cleanup();
626
+ ws.close();
627
+ resolve(message.id);
628
+ }
629
+ });
630
+ ws.addEventListener("error", () => {
631
+ cleanup();
632
+ reject(/* @__PURE__ */ new Error("upload websocket error"));
633
+ });
634
+ ws.addEventListener("close", () => {
635
+ cleanup();
636
+ if (!done) reject(/* @__PURE__ */ new Error("connection closed before upload completed"));
637
+ });
638
+ });
639
+ }
640
+ //#endregion
641
+ //#region src/utils.ts
642
+ const MAX_DELAY_MS = 3e4;
643
+ const JITTER_MIN_MS = 300;
644
+ const JITTER_MAX_MS = 3e3;
857
645
  function wsRetryWait(retries) {
858
- const delay2 = Math.min(Math.pow(2, retries) * 1e3, MAX_DELAY_MS) + Math.floor(Math.random() * (JITTER_MAX_MS2 - JITTER_MIN_MS2) + JITTER_MIN_MS2);
859
- return new Promise((resolve) => setTimeout(resolve, delay2));
646
+ const delay = Math.min(Math.pow(2, retries) * 1e3, MAX_DELAY_MS) + Math.floor(Math.random() * (JITTER_MAX_MS - JITTER_MIN_MS) + JITTER_MIN_MS);
647
+ return new Promise((resolve) => setTimeout(resolve, delay));
860
648
  }
861
-
862
- // src/client.ts
649
+ //#endregion
650
+ //#region src/client.ts
863
651
  var ContelloClient = class {
864
- _pool;
865
- _rpc;
866
- _sources;
867
- _url;
868
- _project;
869
- _token;
870
- _agent;
871
- constructor(options) {
872
- const { url, project, token, schema, connections = 1, connectionEvents } = options;
873
- this._url = url;
874
- this._project = project;
875
- this._token = token;
876
- this._agent = createHttpAgent(options.http);
877
- const websocketUrl = `${url}/graphql/projects/${project}`.replace(/^http/i, "ws");
878
- let state = "disconnected";
879
- let connectedCount = 0;
880
- const onConnectionUp = () => {
881
- connectedCount++;
882
- if (connectedCount === connections && state !== "connected") {
883
- state = "connected";
884
- options.onConnected?.();
885
- }
886
- };
887
- const onConnectionDown = () => {
888
- if (connectedCount > 0) {
889
- connectedCount--;
890
- }
891
- if (state === "connected") {
892
- state = "reconnecting";
893
- options.onReconnecting?.();
894
- }
895
- };
896
- this._pool = new ConnectionPool((id) => {
897
- const context = Object.freeze({ connectionId: id, websocketUrl });
898
- return (0, import_graphql_ws.createClient)({
899
- url: websocketUrl,
900
- connectionParams: { token },
901
- lazy: false,
902
- keepAlive: 3e4,
903
- retryAttempts: Infinity,
904
- retryWait: wsRetryWait,
905
- shouldRetry: () => true,
906
- jsonMessageReplacer: (key, value) => {
907
- if (!key) {
908
- return decorateMessage(value);
909
- }
910
- return value;
911
- },
912
- ...options.onError ? { onNonLazyError: (e) => options.onError(e) } : {},
913
- on: {
914
- connected: () => {
915
- onConnectionUp();
916
- connectionEvents?.onConnected?.(context);
917
- },
918
- connecting: () => {
919
- connectionEvents?.onConnecting?.(context);
920
- },
921
- closed: () => {
922
- onConnectionDown();
923
- connectionEvents?.onClosed?.(context);
924
- },
925
- ...options.onError || connectionEvents?.onError ? {
926
- error: (e) => {
927
- options.onError?.(e);
928
- connectionEvents?.onError?.(context, e);
929
- }
930
- } : {}
931
- }
932
- });
933
- }, connections);
934
- this._rpc = schema?.operations ? buildRpc(schema.operations, (q, v) => this.subscribe(q, v)) : void 0;
935
- this._sources = schema?.sources ? createSources(schema.sources, (q, v) => this.subscribe(q, v)) : void 0;
936
- }
937
- get rpc() {
938
- if (!this._rpc) {
939
- throw new Error("@contello/client: .rpc accessed without a schema containing operations");
940
- }
941
- return this._rpc;
942
- }
943
- get sources() {
944
- if (!this._sources) {
945
- throw new Error("@contello/client: .sources accessed without a schema containing sources");
946
- }
947
- return this._sources;
948
- }
949
- async init() {
950
- await this._pool.connect();
951
- }
952
- async destroy() {
953
- await this._pool.disconnect();
954
- await this._agent.close();
955
- }
956
- async ping() {
957
- return ping((query) => firstAsync(this.subscribe(query)));
958
- }
959
- /**
960
- * Open a subscription on the websocket. Each `[Symbol.asyncIterator]()` call (the implicit one
961
- * from `for await`, or via `rxjs.from(this)`) starts a fresh server subscription and tears it
962
- * down when the iterator is returned (`break`, error, or explicit stop).
963
- */
964
- subscribe(query, variables) {
965
- const pool = this._pool;
966
- return {
967
- [Symbol.asyncIterator]() {
968
- const wsClient = pool.get();
969
- const queue = [];
970
- let pending;
971
- let done = false;
972
- let error;
973
- const unsubscribe = wsClient.subscribe(
974
- { query, variables },
975
- {
976
- next(msg) {
977
- const value = transformResponse(msg.data);
978
- if (value === void 0 || value === null) {
979
- return;
980
- }
981
- if (pending) {
982
- const p = pending;
983
- pending = void 0;
984
- p.resolve({ value, done: false });
985
- } else {
986
- queue.push(value);
987
- }
988
- },
989
- error(err) {
990
- done = true;
991
- error = err;
992
- if (pending) {
993
- const p = pending;
994
- pending = void 0;
995
- p.reject(err);
996
- }
997
- },
998
- complete() {
999
- done = true;
1000
- if (pending) {
1001
- const p = pending;
1002
- pending = void 0;
1003
- p.resolve({ value: void 0, done: true });
1004
- }
1005
- }
1006
- }
1007
- );
1008
- return {
1009
- next() {
1010
- if (queue.length > 0) {
1011
- return Promise.resolve({ value: queue.shift(), done: false });
1012
- }
1013
- if (error !== void 0) {
1014
- return Promise.reject(error);
1015
- }
1016
- if (done) {
1017
- return Promise.resolve({ value: void 0, done: true });
1018
- }
1019
- return new Promise((resolve, reject) => {
1020
- pending = { resolve, reject };
1021
- });
1022
- },
1023
- return() {
1024
- unsubscribe();
1025
- return Promise.resolve({ value: void 0, done: true });
1026
- },
1027
- throw(err) {
1028
- unsubscribe();
1029
- return Promise.reject(err);
1030
- }
1031
- };
1032
- }
1033
- };
1034
- }
1035
- download(fileId) {
1036
- return wrap("@contello/client:download", () => downloadFile(this._agent, this._url, this._token, fileId));
1037
- }
1038
- proxyHls(path, signal) {
1039
- return wrap("@contello/client:proxyHls", () => proxyHls(this._agent, this._url, this._token, path, signal));
1040
- }
1041
- upload(data, meta, options) {
1042
- return wrap(
1043
- "@contello/client:upload",
1044
- () => upload(this._url, this._project, this._token, data, meta, options)
1045
- );
1046
- }
1047
- execute(query, variables) {
1048
- return wrap("@contello/client:execute", () => firstAsync(this.subscribe(query, variables)));
1049
- }
652
+ _pool;
653
+ _rpc;
654
+ _sources;
655
+ _url;
656
+ _project;
657
+ _token;
658
+ _agent;
659
+ constructor(options) {
660
+ const { url, project, token, schema, connections = 1, connectionEvents } = options;
661
+ this._url = url;
662
+ this._project = project;
663
+ this._token = token;
664
+ this._agent = createHttpAgent(options.http);
665
+ const websocketUrl = `${url}/graphql/projects/${project}`.replace(/^http/i, "ws");
666
+ let state = "disconnected";
667
+ let connectedCount = 0;
668
+ const onConnectionUp = () => {
669
+ connectedCount++;
670
+ if (connectedCount === connections && state !== "connected") {
671
+ state = "connected";
672
+ options.onConnected?.();
673
+ }
674
+ };
675
+ const onConnectionDown = () => {
676
+ if (connectedCount > 0) connectedCount--;
677
+ if (state === "connected") {
678
+ state = "reconnecting";
679
+ options.onReconnecting?.();
680
+ }
681
+ };
682
+ this._pool = new ConnectionPool((id) => {
683
+ const context = Object.freeze({
684
+ connectionId: id,
685
+ websocketUrl
686
+ });
687
+ return (0, graphql_ws.createClient)({
688
+ url: websocketUrl,
689
+ connectionParams: { token },
690
+ lazy: false,
691
+ keepAlive: 3e4,
692
+ retryAttempts: Infinity,
693
+ retryWait: wsRetryWait,
694
+ shouldRetry: () => true,
695
+ jsonMessageReplacer: (key, value) => {
696
+ if (!key) return (0, _contello_opentelemetry.injectTraceContext)(value);
697
+ return value;
698
+ },
699
+ ...options.onError && { onNonLazyError: (e) => options.onError(e) },
700
+ on: {
701
+ connected: () => {
702
+ onConnectionUp();
703
+ connectionEvents?.onConnected?.(context);
704
+ },
705
+ connecting: () => {
706
+ connectionEvents?.onConnecting?.(context);
707
+ },
708
+ closed: () => {
709
+ onConnectionDown();
710
+ connectionEvents?.onClosed?.(context);
711
+ },
712
+ ...(options.onError || connectionEvents?.onError) && { error: (e) => {
713
+ options.onError?.(e);
714
+ connectionEvents?.onError?.(context, e);
715
+ } }
716
+ }
717
+ });
718
+ }, connections);
719
+ this._rpc = schema?.operations ? buildRpc(schema.operations, (q, v) => this.subscribe(q, v)) : void 0;
720
+ this._sources = schema?.sources ? createSources(schema.sources, (q, v) => this.subscribe(q, v)) : void 0;
721
+ }
722
+ get rpc() {
723
+ if (!this._rpc) throw new Error("@contello/client: .rpc accessed without a schema containing operations");
724
+ return this._rpc;
725
+ }
726
+ get sources() {
727
+ if (!this._sources) throw new Error("@contello/client: .sources accessed without a schema containing sources");
728
+ return this._sources;
729
+ }
730
+ async init() {
731
+ await this._pool.connect();
732
+ }
733
+ async destroy() {
734
+ await this._pool.disconnect();
735
+ await this._agent.close();
736
+ }
737
+ async ping() {
738
+ return ping((query) => firstAsync(this.subscribe(query)));
739
+ }
740
+ /**
741
+ * Open a subscription on the websocket. Each `[Symbol.asyncIterator]()` call (the implicit one
742
+ * from `for await`, or via `rxjs.from(this)`) starts a fresh server subscription and tears it
743
+ * down when the iterator is returned (`break`, error, or explicit stop).
744
+ */
745
+ subscribe(query, variables) {
746
+ const pool = this._pool;
747
+ return { [Symbol.asyncIterator]() {
748
+ const wsClient = pool.get();
749
+ const queue = [];
750
+ let pending;
751
+ let done = false;
752
+ let error;
753
+ const unsubscribe = wsClient.subscribe({
754
+ query,
755
+ variables
756
+ }, {
757
+ next(msg) {
758
+ const value = transformResponse(msg.data);
759
+ if (value === void 0 || value === null) return;
760
+ if (pending) {
761
+ const p = pending;
762
+ pending = void 0;
763
+ p.resolve({
764
+ value,
765
+ done: false
766
+ });
767
+ } else queue.push(value);
768
+ },
769
+ error(err) {
770
+ done = true;
771
+ error = err;
772
+ if (pending) {
773
+ const p = pending;
774
+ pending = void 0;
775
+ p.reject(err);
776
+ }
777
+ },
778
+ complete() {
779
+ done = true;
780
+ if (pending) {
781
+ const p = pending;
782
+ pending = void 0;
783
+ p.resolve({
784
+ value: void 0,
785
+ done: true
786
+ });
787
+ }
788
+ }
789
+ });
790
+ return {
791
+ next() {
792
+ if (queue.length > 0) return Promise.resolve({
793
+ value: queue.shift(),
794
+ done: false
795
+ });
796
+ if (error !== void 0) return Promise.reject(error);
797
+ if (done) return Promise.resolve({
798
+ value: void 0,
799
+ done: true
800
+ });
801
+ return new Promise((resolve, reject) => {
802
+ pending = {
803
+ resolve,
804
+ reject
805
+ };
806
+ });
807
+ },
808
+ return() {
809
+ unsubscribe();
810
+ return Promise.resolve({
811
+ value: void 0,
812
+ done: true
813
+ });
814
+ },
815
+ throw(err) {
816
+ unsubscribe();
817
+ return Promise.reject(err);
818
+ }
819
+ };
820
+ } };
821
+ }
822
+ download(fileId) {
823
+ return wrap("@contello/client:download", () => downloadFile(this._agent, this._url, this._token, fileId));
824
+ }
825
+ proxyHls(path, signal) {
826
+ return wrap("@contello/client:proxyHls", () => proxyHls(this._agent, this._url, this._token, path, signal));
827
+ }
828
+ upload(data, meta, options) {
829
+ return wrap("@contello/client:upload", () => upload(this._url, this._project, this._token, data, meta, options));
830
+ }
831
+ execute(query, variables) {
832
+ return wrap("@contello/client:execute", () => firstAsync(this.subscribe(query, variables)), (0, _contello_opentelemetry.graphqlOperationAttributes)(query, variables));
833
+ }
1050
834
  };
1051
835
  function createContelloClient(options) {
1052
- return new ContelloClient(options);
836
+ return new ContelloClient(options);
1053
837
  }
1054
-
1055
- // src/async-iterable-subject.ts
838
+ //#endregion
839
+ //#region src/async-iterable-subject.ts
1056
840
  function createAsyncIterableSubject() {
1057
- const consumers = /* @__PURE__ */ new Set();
1058
- let status = { state: "open" };
1059
- const next = (value) => {
1060
- if (status.state !== "open") {
1061
- return;
1062
- }
1063
- for (const consumer of consumers) {
1064
- if (consumer.kind === "listener") {
1065
- consumer.next?.(value);
1066
- } else if (consumer.pending) {
1067
- const p = consumer.pending;
1068
- consumer.pending = void 0;
1069
- p.resolve({ value, done: false });
1070
- } else {
1071
- consumer.queue.push(value);
1072
- }
1073
- }
1074
- };
1075
- const error = (err) => {
1076
- if (status.state !== "open") {
1077
- return;
1078
- }
1079
- status = { state: "errored", err };
1080
- for (const consumer of consumers) {
1081
- if (consumer.kind === "listener") {
1082
- consumer.error?.(err);
1083
- } else if (consumer.pending) {
1084
- const p = consumer.pending;
1085
- consumer.pending = void 0;
1086
- p.reject(err);
1087
- }
1088
- }
1089
- consumers.clear();
1090
- };
1091
- const complete = () => {
1092
- if (status.state !== "open") {
1093
- return;
1094
- }
1095
- status = { state: "completed" };
1096
- for (const consumer of consumers) {
1097
- if (consumer.kind === "listener") {
1098
- consumer.complete?.();
1099
- } else if (consumer.pending) {
1100
- const p = consumer.pending;
1101
- consumer.pending = void 0;
1102
- p.resolve({ value: void 0, done: true });
1103
- }
1104
- }
1105
- consumers.clear();
1106
- };
1107
- const subscribe = (observerOrNext) => {
1108
- if (status.state !== "open") {
1109
- return () => {
1110
- };
1111
- }
1112
- const observer = typeof observerOrNext === "function" ? { next: observerOrNext } : observerOrNext;
1113
- const consumer = { kind: "listener", ...observer };
1114
- consumers.add(consumer);
1115
- return () => {
1116
- consumers.delete(consumer);
1117
- };
1118
- };
1119
- const iterable = {
1120
- [Symbol.asyncIterator]() {
1121
- if (status.state === "errored") {
1122
- const err = status.err;
1123
- return {
1124
- next: () => Promise.reject(err),
1125
- return: () => Promise.resolve({ value: void 0, done: true })
1126
- };
1127
- }
1128
- if (status.state === "completed") {
1129
- return {
1130
- next: () => Promise.resolve({ value: void 0, done: true }),
1131
- return: () => Promise.resolve({ value: void 0, done: true })
1132
- };
1133
- }
1134
- const consumer = { kind: "iterator", queue: [] };
1135
- consumers.add(consumer);
1136
- return {
1137
- next() {
1138
- if (consumer.queue.length > 0) {
1139
- return Promise.resolve({ value: consumer.queue.shift(), done: false });
1140
- }
1141
- if (status.state === "errored") {
1142
- return Promise.reject(status.err);
1143
- }
1144
- if (status.state === "completed") {
1145
- return Promise.resolve({ value: void 0, done: true });
1146
- }
1147
- return new Promise((resolve, reject) => {
1148
- consumer.pending = { resolve, reject };
1149
- });
1150
- },
1151
- return() {
1152
- consumers.delete(consumer);
1153
- if (consumer.pending) {
1154
- const p = consumer.pending;
1155
- consumer.pending = void 0;
1156
- p.resolve({ value: void 0, done: true });
1157
- }
1158
- return Promise.resolve({ value: void 0, done: true });
1159
- },
1160
- throw(err) {
1161
- consumers.delete(consumer);
1162
- return Promise.reject(err);
1163
- }
1164
- };
1165
- }
1166
- };
1167
- return Object.assign(iterable, { next, error, complete, subscribe });
1168
- }
1169
- // Annotate the CommonJS export names for ESM import in node:
1170
- 0 && (module.exports = {
1171
- ContelloClient,
1172
- asyncKeepalive,
1173
- collectAsync,
1174
- createAsyncIterableSubject,
1175
- createContelloClient,
1176
- createSourceSubscription,
1177
- exponentialBackoff,
1178
- filterAsync,
1179
- firstAsync,
1180
- mapAsync,
1181
- runWithBackoff
1182
- });
841
+ const consumers = /* @__PURE__ */ new Set();
842
+ let status = { state: "open" };
843
+ const next = (value) => {
844
+ if (status.state !== "open") return;
845
+ for (const consumer of consumers) if (consumer.kind === "listener") consumer.next?.(value);
846
+ else if (consumer.pending) {
847
+ const p = consumer.pending;
848
+ consumer.pending = void 0;
849
+ p.resolve({
850
+ value,
851
+ done: false
852
+ });
853
+ } else consumer.queue.push(value);
854
+ };
855
+ const error = (err) => {
856
+ if (status.state !== "open") return;
857
+ status = {
858
+ state: "errored",
859
+ err
860
+ };
861
+ for (const consumer of consumers) if (consumer.kind === "listener") consumer.error?.(err);
862
+ else if (consumer.pending) {
863
+ const p = consumer.pending;
864
+ consumer.pending = void 0;
865
+ p.reject(err);
866
+ }
867
+ consumers.clear();
868
+ };
869
+ const complete = () => {
870
+ if (status.state !== "open") return;
871
+ status = { state: "completed" };
872
+ for (const consumer of consumers) if (consumer.kind === "listener") consumer.complete?.();
873
+ else if (consumer.pending) {
874
+ const p = consumer.pending;
875
+ consumer.pending = void 0;
876
+ p.resolve({
877
+ value: void 0,
878
+ done: true
879
+ });
880
+ }
881
+ consumers.clear();
882
+ };
883
+ const subscribe = (observerOrNext) => {
884
+ if (status.state !== "open") return () => {};
885
+ const consumer = {
886
+ kind: "listener",
887
+ ...typeof observerOrNext === "function" ? { next: observerOrNext } : observerOrNext
888
+ };
889
+ consumers.add(consumer);
890
+ return () => {
891
+ consumers.delete(consumer);
892
+ };
893
+ };
894
+ return Object.assign({ [Symbol.asyncIterator]() {
895
+ if (status.state === "errored") {
896
+ const err = status.err;
897
+ return {
898
+ next: () => Promise.reject(err),
899
+ return: () => Promise.resolve({
900
+ value: void 0,
901
+ done: true
902
+ })
903
+ };
904
+ }
905
+ if (status.state === "completed") return {
906
+ next: () => Promise.resolve({
907
+ value: void 0,
908
+ done: true
909
+ }),
910
+ return: () => Promise.resolve({
911
+ value: void 0,
912
+ done: true
913
+ })
914
+ };
915
+ const consumer = {
916
+ kind: "iterator",
917
+ queue: []
918
+ };
919
+ consumers.add(consumer);
920
+ return {
921
+ next() {
922
+ if (consumer.queue.length > 0) return Promise.resolve({
923
+ value: consumer.queue.shift(),
924
+ done: false
925
+ });
926
+ if (status.state === "errored") return Promise.reject(status.err);
927
+ if (status.state === "completed") return Promise.resolve({
928
+ value: void 0,
929
+ done: true
930
+ });
931
+ return new Promise((resolve, reject) => {
932
+ consumer.pending = {
933
+ resolve,
934
+ reject
935
+ };
936
+ });
937
+ },
938
+ return() {
939
+ consumers.delete(consumer);
940
+ if (consumer.pending) {
941
+ const p = consumer.pending;
942
+ consumer.pending = void 0;
943
+ p.resolve({
944
+ value: void 0,
945
+ done: true
946
+ });
947
+ }
948
+ return Promise.resolve({
949
+ value: void 0,
950
+ done: true
951
+ });
952
+ },
953
+ throw(err) {
954
+ consumers.delete(consumer);
955
+ return Promise.reject(err);
956
+ }
957
+ };
958
+ } }, {
959
+ next,
960
+ error,
961
+ complete,
962
+ subscribe
963
+ });
964
+ }
965
+ //#endregion
966
+ exports.ContelloClient = ContelloClient;
967
+ exports.asyncKeepalive = asyncKeepalive;
968
+ exports.collectAsync = collectAsync;
969
+ exports.createAsyncIterableSubject = createAsyncIterableSubject;
970
+ exports.createContelloClient = createContelloClient;
971
+ exports.createSourceSubscription = createSourceSubscription;
972
+ exports.exponentialBackoff = exponentialBackoff;
973
+ exports.filterAsync = filterAsync;
974
+ exports.firstAsync = firstAsync;
975
+ exports.mapAsync = mapAsync;
976
+ exports.runWithBackoff = runWithBackoff;