@gscdump/sdk 0.37.7 → 0.38.1

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.
@@ -0,0 +1,1375 @@
1
+ import { GSCDUMP_REALTIME_ACK_POLICY, GSCDUMP_REALTIME_CLOSE_CODES, GSCDUMP_REALTIME_CONNECTION_POLICY, GSCDUMP_REALTIME_LIMITS, GSCDUMP_REALTIME_PING, GSCDUMP_REALTIME_PONG, GSCDUMP_REALTIME_SUBPROTOCOL, REALTIME_V1_EVENT_NAMES, REALTIME_V1_RESOURCE_TYPES, buildHttpOperationPath, createGscdumpV1Protocol } from "@gscdump/contracts/v1";
2
+ var GscdumpV1Error = class extends Error {
3
+ tag = "GscdumpV1Error";
4
+ code;
5
+ status;
6
+ requestId;
7
+ retryable;
8
+ details;
9
+ cause;
10
+ constructor(options) {
11
+ super(options.message);
12
+ this.name = "GscdumpV1Error";
13
+ this.code = options.code;
14
+ this.status = options.status;
15
+ this.requestId = options.requestId;
16
+ this.retryable = options.retryable;
17
+ this.details = options.details;
18
+ this.cause = options.cause;
19
+ }
20
+ };
21
+ function isGscdumpV1Error(error) {
22
+ return error instanceof GscdumpV1Error;
23
+ }
24
+ const DEFAULT_API_ROOT = "https://gscdump.com/api";
25
+ const API_PREFIX_RE = /^\/api(?=\/)/;
26
+ const TRAILING_SLASH_RE = /\/+$/;
27
+ const LEADING_SLASH_RE = /^\/+/;
28
+ function validationDetails(cause) {
29
+ if (typeof cause === "object" && cause !== null && "issues" in cause) return { issues: cause.issues };
30
+ return {};
31
+ }
32
+ function requestValidationError(operationId, location, cause) {
33
+ return new GscdumpV1Error({
34
+ code: "request_validation",
35
+ message: `${operationId}: invalid request ${location}`,
36
+ retryable: false,
37
+ details: {
38
+ location,
39
+ ...validationDetails(cause)
40
+ },
41
+ cause
42
+ });
43
+ }
44
+ function responseValidationError(operationId, status, requestId, cause) {
45
+ return new GscdumpV1Error({
46
+ code: "response_validation",
47
+ message: `${operationId}: response ${status} did not match the v1 contract`,
48
+ status,
49
+ requestId,
50
+ retryable: false,
51
+ details: validationDetails(cause),
52
+ cause
53
+ });
54
+ }
55
+ function clampInteger(value, fallback, min, max) {
56
+ if (value === void 0) return fallback;
57
+ if (!Number.isFinite(value)) throw new TypeError("Retry configuration values must be finite numbers.");
58
+ return Math.min(max, Math.max(min, Math.trunc(value)));
59
+ }
60
+ function resolveRetryOptions(options) {
61
+ const baseDelayMs = clampInteger(options?.baseDelayMs, 250, 0, 6e4);
62
+ const maxDelayMs = clampInteger(options?.maxDelayMs, 2e3, baseDelayMs, 3e5);
63
+ return {
64
+ maxAttempts: clampInteger(options?.maxAttempts, 3, 1, 5),
65
+ baseDelayMs,
66
+ maxDelayMs
67
+ };
68
+ }
69
+ function resolveApiUrl(apiRoot, contractPath) {
70
+ const relative = contractPath.replace(API_PREFIX_RE, "").replace(LEADING_SLASH_RE, "");
71
+ return `${apiRoot.replace(TRAILING_SLASH_RE, "")}/${relative}`;
72
+ }
73
+ function appendQueryValue(search, key, value) {
74
+ if (value === void 0) return;
75
+ if (Array.isArray(value)) {
76
+ for (const item of value) appendQueryValue(search, key, item);
77
+ return;
78
+ }
79
+ if (value === null || typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
80
+ search.append(key, value === null ? "null" : String(value));
81
+ return;
82
+ }
83
+ search.append(key, JSON.stringify(value));
84
+ }
85
+ function appendQuery(url, query) {
86
+ if (query === void 0 || query === null) return url;
87
+ if (typeof query !== "object" || Array.isArray(query)) throw new TypeError("A query schema must produce an object.");
88
+ const search = new URLSearchParams();
89
+ for (const key of Object.keys(query).sort()) appendQueryValue(search, key, query[key]);
90
+ const serialized = search.toString();
91
+ return serialized ? `${url}?${serialized}` : url;
92
+ }
93
+ function assertAbsentLocation(operationId, location, value) {
94
+ if (value !== void 0) throw requestValidationError(operationId, location, /* @__PURE__ */ new TypeError(`${location} is not accepted by this operation.`));
95
+ }
96
+ function parseLocation(operation, location, value) {
97
+ const schema = operation.request[location];
98
+ if (schema === null) {
99
+ assertAbsentLocation(operation.id, location, value);
100
+ return;
101
+ }
102
+ try {
103
+ return schema.parse(location === "headers" && value === void 0 ? {} : value);
104
+ } catch (cause) {
105
+ throw requestValidationError(operation.id, location, cause);
106
+ }
107
+ }
108
+ function prepareRequest(surface, operation, input, options) {
109
+ let path;
110
+ if (operation.request.params === null) {
111
+ assertAbsentLocation(operation.id, "params", input.params);
112
+ path = buildHttpOperationPath(surface, operation);
113
+ } else try {
114
+ path = buildHttpOperationPath(surface, operation, input.params);
115
+ } catch (cause) {
116
+ throw requestValidationError(operation.id, "params", cause);
117
+ }
118
+ const inputHeaders = input.headers;
119
+ const headerRequestId = inputHeaders?.["x-request-id"];
120
+ if (options.requestId && headerRequestId && options.requestId !== headerRequestId) throw requestValidationError(operation.id, "headers", /* @__PURE__ */ new TypeError("requestId conflicts with headers.x-request-id."));
121
+ const requestHeaders = options.requestId ? {
122
+ ...inputHeaders ?? {},
123
+ "x-request-id": options.requestId
124
+ } : input.headers;
125
+ return {
126
+ path,
127
+ query: parseLocation(operation, "query", input.query),
128
+ headers: parseLocation(operation, "headers", requestHeaders),
129
+ body: parseLocation(operation, "body", input.body)
130
+ };
131
+ }
132
+ async function resolveCredential(resolver) {
133
+ let credential;
134
+ try {
135
+ credential = typeof resolver === "function" ? await resolver() : resolver;
136
+ } catch (cause) {
137
+ throw new GscdumpV1Error({
138
+ code: "credential_resolution",
139
+ message: "Could not resolve the v1 Bearer credential.",
140
+ retryable: false,
141
+ details: {},
142
+ cause
143
+ });
144
+ }
145
+ if (typeof credential !== "string" || !credential.trim()) throw new GscdumpV1Error({
146
+ code: "credential_resolution",
147
+ message: "The v1 Bearer credential cannot be empty.",
148
+ retryable: false,
149
+ details: {}
150
+ });
151
+ return credential;
152
+ }
153
+ async function resolveBaseHeaders(resolver) {
154
+ return typeof resolver === "function" ? await resolver() : resolver;
155
+ }
156
+ async function buildRequestHeaders(options, operation, prepared, executeOptions) {
157
+ try {
158
+ const headers = new Headers(await resolveBaseHeaders(options.headers));
159
+ for (const [key, value] of Object.entries(prepared.headers)) if (value !== void 0) headers.set(key, String(value));
160
+ headers.delete("x-api-key");
161
+ headers.set("accept", "application/json");
162
+ headers.set("authorization", `Bearer ${await resolveCredential(options.credential)}`);
163
+ if (executeOptions.idempotencyKey) headers.set("idempotency-key", executeOptions.idempotencyKey);
164
+ if (prepared.body !== void 0) headers.set("content-type", "application/json");
165
+ return headers;
166
+ } catch (cause) {
167
+ if (cause instanceof GscdumpV1Error) throw cause;
168
+ throw requestValidationError(operation.id, "headers", cause);
169
+ }
170
+ }
171
+ function isAbortError(error, signal) {
172
+ return signal?.aborted === true || typeof error === "object" && error !== null && "name" in error && error.name === "AbortError";
173
+ }
174
+ function abortedRequestError(operation, executeOptions, cause = executeOptions.signal?.reason) {
175
+ return new GscdumpV1Error({
176
+ code: "aborted",
177
+ message: `${operation.id}: request aborted`,
178
+ requestId: executeOptions.requestId,
179
+ retryable: false,
180
+ details: {},
181
+ cause
182
+ });
183
+ }
184
+ async function waitForRetry(ms, operation, executeOptions) {
185
+ try {
186
+ await sleep(ms, executeOptions.signal);
187
+ } catch (cause) {
188
+ if (isAbortError(cause, executeOptions.signal)) throw abortedRequestError(operation, executeOptions, cause);
189
+ throw cause;
190
+ }
191
+ }
192
+ function awaitWithAbort(promise, operation, executeOptions) {
193
+ const signal = executeOptions.signal;
194
+ if (!signal) return promise;
195
+ if (signal.aborted) return Promise.reject(abortedRequestError(operation, executeOptions));
196
+ return new Promise((resolve, reject) => {
197
+ function onAbort() {
198
+ reject(abortedRequestError(operation, executeOptions));
199
+ }
200
+ signal.addEventListener("abort", onAbort, { once: true });
201
+ promise.then((value) => {
202
+ signal.removeEventListener("abort", onAbort);
203
+ resolve(value);
204
+ }, (cause) => {
205
+ signal.removeEventListener("abort", onAbort);
206
+ reject(cause);
207
+ });
208
+ });
209
+ }
210
+ function parseRetryAfter(value, now) {
211
+ if (value === null) return void 0;
212
+ const seconds = Number(value);
213
+ if (Number.isFinite(seconds) && seconds >= 0) return Math.ceil(seconds * 1e3);
214
+ const date = Date.parse(value);
215
+ if (Number.isNaN(date)) return void 0;
216
+ return Math.max(0, date - now);
217
+ }
218
+ function retryDelay(attempt, retryAfter, options) {
219
+ const exponential = Math.min(options.maxDelayMs, options.baseDelayMs * 2 ** Math.max(0, attempt - 1));
220
+ return Math.max(exponential, parseRetryAfter(retryAfter, Date.now()) ?? 0);
221
+ }
222
+ function sleep(ms, signal) {
223
+ if (signal?.aborted) return Promise.reject(signal.reason ?? new DOMException("The operation was aborted.", "AbortError"));
224
+ return new Promise((resolve, reject) => {
225
+ const handle = setTimeout(() => {
226
+ signal?.removeEventListener("abort", onAbort);
227
+ resolve();
228
+ }, ms);
229
+ function onAbort() {
230
+ clearTimeout(handle);
231
+ reject(signal?.reason ?? new DOMException("The operation was aborted.", "AbortError"));
232
+ }
233
+ signal?.addEventListener("abort", onAbort, { once: true });
234
+ });
235
+ }
236
+ async function readJson(response) {
237
+ const text = await response.text();
238
+ if (!text) return null;
239
+ return JSON.parse(text);
240
+ }
241
+ function requestIdFrom(response) {
242
+ return response.headers.get("x-request-id") ?? void 0;
243
+ }
244
+ function operationLookup(protocol) {
245
+ const operations = /* @__PURE__ */ new Map();
246
+ for (const surface of Object.values(protocol.surfaces)) for (const operation of Object.values(surface.operations)) operations.set(operation.id, {
247
+ operation,
248
+ surface
249
+ });
250
+ return operations;
251
+ }
252
+ function createGscdumpV1Client(options) {
253
+ const protocol = createGscdumpV1Protocol();
254
+ const operations = operationLookup(protocol);
255
+ const retryOptions = resolveRetryOptions(options.retry);
256
+ const apiRoot = options.apiRoot ?? DEFAULT_API_ROOT;
257
+ const fetchImpl = options.fetch ?? globalThis.fetch;
258
+ if (typeof fetchImpl !== "function") throw new TypeError("createGscdumpV1Client requires a fetch implementation in this runtime.");
259
+ async function execute(operationId, input, executeOptions = {}) {
260
+ const entry = operations.get(operationId);
261
+ if (!entry) throw new GscdumpV1Error({
262
+ code: "request_validation",
263
+ message: `Unknown gscdump v1 operation: ${operationId}`,
264
+ retryable: false,
265
+ details: { operationId }
266
+ });
267
+ const { operation, surface } = entry;
268
+ if (typeof input !== "object" || input === null || Array.isArray(input)) throw requestValidationError(operation.id, "input", /* @__PURE__ */ new TypeError("input must be an object."));
269
+ const prepared = prepareRequest(surface, operation, input, executeOptions);
270
+ let url;
271
+ try {
272
+ url = appendQuery(resolveApiUrl(apiRoot, prepared.path), prepared.query);
273
+ } catch (cause) {
274
+ throw requestValidationError(operation.id, "query", cause);
275
+ }
276
+ const canRetry = operation.semantics.retry === "idempotent";
277
+ for (let attempt = 1; attempt <= retryOptions.maxAttempts; attempt++) {
278
+ if (executeOptions.signal?.aborted) throw abortedRequestError(operation, executeOptions);
279
+ const headers = await awaitWithAbort(buildRequestHeaders(options, operation, prepared, executeOptions), operation, executeOptions);
280
+ if (executeOptions.signal?.aborted) throw abortedRequestError(operation, executeOptions);
281
+ let response;
282
+ try {
283
+ response = await fetchImpl(url, {
284
+ method: operation.method,
285
+ headers,
286
+ body: prepared.body === void 0 ? void 0 : JSON.stringify(prepared.body),
287
+ signal: executeOptions.signal
288
+ });
289
+ } catch (cause) {
290
+ if (isAbortError(cause, executeOptions.signal)) throw abortedRequestError(operation, executeOptions, cause);
291
+ if (canRetry && attempt < retryOptions.maxAttempts) {
292
+ await waitForRetry(retryDelay(attempt, null, retryOptions), operation, executeOptions);
293
+ continue;
294
+ }
295
+ throw new GscdumpV1Error({
296
+ code: "network_error",
297
+ message: `${operation.id}: network request failed`,
298
+ requestId: executeOptions.requestId,
299
+ retryable: canRetry,
300
+ details: { attempts: attempt },
301
+ cause
302
+ });
303
+ }
304
+ const requestId = requestIdFrom(response) ?? executeOptions.requestId;
305
+ let payload;
306
+ try {
307
+ payload = await readJson(response);
308
+ } catch (cause) {
309
+ if (isAbortError(cause, executeOptions.signal)) throw abortedRequestError(operation, executeOptions, cause);
310
+ throw responseValidationError(operation.id, response.status, requestId, cause);
311
+ }
312
+ if (executeOptions.signal?.aborted) throw abortedRequestError(operation, executeOptions);
313
+ const responseContract = operation.responses[response.status];
314
+ if (responseContract) try {
315
+ return responseContract.client.parse(payload);
316
+ } catch (cause) {
317
+ throw responseValidationError(operation.id, response.status, requestId, cause);
318
+ }
319
+ if (response.ok) throw new GscdumpV1Error({
320
+ code: "protocol_error",
321
+ message: `${operation.id}: undeclared success status ${response.status}`,
322
+ status: response.status,
323
+ requestId,
324
+ retryable: false,
325
+ details: { status: response.status }
326
+ });
327
+ let envelope;
328
+ try {
329
+ envelope = protocol.schemas.errorEnvelope.client.parse(payload);
330
+ } catch (cause) {
331
+ throw responseValidationError(operation.id, response.status, requestId, cause);
332
+ }
333
+ if (!operation.errors.includes(envelope.error.code)) throw new GscdumpV1Error({
334
+ code: "protocol_error",
335
+ message: `${operation.id}: undeclared error code ${envelope.error.code}`,
336
+ status: response.status,
337
+ requestId: envelope.error.requestId,
338
+ retryable: false,
339
+ details: { code: envelope.error.code }
340
+ });
341
+ const apiError = new GscdumpV1Error({
342
+ code: envelope.error.code,
343
+ message: envelope.error.message,
344
+ status: response.status,
345
+ requestId: envelope.error.requestId,
346
+ retryable: envelope.error.retryable,
347
+ details: envelope.error.details ?? {}
348
+ });
349
+ if (canRetry && apiError.retryable && attempt < retryOptions.maxAttempts) {
350
+ await waitForRetry(retryDelay(attempt, response.headers.get("retry-after"), retryOptions), operation, executeOptions);
351
+ continue;
352
+ }
353
+ throw apiError;
354
+ }
355
+ throw new GscdumpV1Error({
356
+ code: "network_error",
357
+ message: `${operationId}: retry budget exhausted`,
358
+ retryable: false,
359
+ details: {}
360
+ });
361
+ }
362
+ return {
363
+ execute,
364
+ getUserLifecycle: (input, executeOptions) => execute("partner.users.lifecycle.get", input, executeOptions),
365
+ queryAnalyticsRows: (input, executeOptions) => execute("analytics.rows.query", input, executeOptions),
366
+ getRealtimeStreamHead: (input = {}, executeOptions) => execute("realtime.stream.head.get", input, executeOptions),
367
+ createRealtimeTicket: (input, executeOptions) => execute("realtime.tickets.create", input, executeOptions)
368
+ };
369
+ }
370
+ const GSCDUMP_REALTIME_V1_SDK_VERSION = "0.37.7";
371
+ var GscdumpRealtimeV1Error = class extends Error {
372
+ tag = "GscdumpRealtimeV1Error";
373
+ code;
374
+ retryable;
375
+ terminal;
376
+ details;
377
+ cause;
378
+ constructor(options) {
379
+ super(options.message);
380
+ this.name = "GscdumpRealtimeV1Error";
381
+ this.code = options.code;
382
+ this.retryable = options.retryable;
383
+ this.terminal = options.terminal;
384
+ this.details = options.details ?? {};
385
+ this.cause = options.cause;
386
+ }
387
+ };
388
+ var StaleEpochError = class extends Error {
389
+ constructor() {
390
+ super("The realtime connection epoch is no longer active.");
391
+ this.name = "StaleEpochError";
392
+ }
393
+ };
394
+ function createMemoryCursorStore() {
395
+ let value = null;
396
+ return {
397
+ load: () => value,
398
+ save: (cursor) => {
399
+ value = { ...cursor };
400
+ }
401
+ };
402
+ }
403
+ function defaultRuntime() {
404
+ return {
405
+ createSocket(url, protocols) {
406
+ if (typeof globalThis.WebSocket !== "function") throw new GscdumpRealtimeV1Error({
407
+ code: "runtime_unavailable",
408
+ message: "This runtime does not provide WebSocket; inject a realtime runtime port.",
409
+ retryable: false,
410
+ terminal: true
411
+ });
412
+ return new globalThis.WebSocket(url, [...protocols]);
413
+ },
414
+ setTimeout: (handler, ms) => globalThis.setTimeout(handler, ms),
415
+ clearTimeout: (handle) => globalThis.clearTimeout(handle),
416
+ random: () => Math.random(),
417
+ now: () => Date.now()
418
+ };
419
+ }
420
+ function utf8Size(value) {
421
+ return new TextEncoder().encode(value).byteLength;
422
+ }
423
+ async function messageText(raw) {
424
+ if (typeof raw === "string") return raw;
425
+ if (raw instanceof ArrayBuffer) return new TextDecoder().decode(raw);
426
+ if (ArrayBuffer.isView(raw)) return new TextDecoder().decode(new Uint8Array(raw.buffer, raw.byteOffset, raw.byteLength));
427
+ if (typeof Blob !== "undefined" && raw instanceof Blob) return raw.text();
428
+ throw new TypeError("Realtime frames must be text or UTF-8 binary data.");
429
+ }
430
+ function compareSequence(left, right) {
431
+ const a = BigInt(left);
432
+ const b = BigInt(right);
433
+ return a < b ? -1 : a > b ? 1 : 0;
434
+ }
435
+ function nextSequence(sequence) {
436
+ return (BigInt(sequence) + 1n).toString();
437
+ }
438
+ function laterCursor(left, right) {
439
+ return compareSequence(left.sequence, right.sequence) >= 0 ? left : right;
440
+ }
441
+ function sameCursor(left, right) {
442
+ return left?.streamId === right?.streamId && left?.sequence === right?.sequence;
443
+ }
444
+ function parseErrorDetails(cause) {
445
+ if (typeof cause === "object" && cause !== null && "issues" in cause) return { issues: cause.issues };
446
+ return {};
447
+ }
448
+ function safeRandom(random) {
449
+ const value = random();
450
+ return Number.isFinite(value) ? Math.min(1, Math.max(0, value)) : .5;
451
+ }
452
+ function createGscdumpRealtimeV1Client(options) {
453
+ const protocol = createGscdumpV1Protocol();
454
+ const runtime = options.runtime ?? defaultRuntime();
455
+ const cursorStore = options.cursorStore ?? createMemoryCursorStore();
456
+ const sdkVersion = options.sdkVersion ?? "0.37.7";
457
+ if (!sdkVersion) throw new TypeError("sdkVersion cannot be empty.");
458
+ let running = false;
459
+ let epoch = 0;
460
+ let reconnectTimer;
461
+ let heartbeatTimer;
462
+ let rotationTimer;
463
+ let current = null;
464
+ let immediateExpiredTicketRetry = true;
465
+ let cursor = null;
466
+ let streamId = null;
467
+ let head = null;
468
+ let attempt = 0;
469
+ let transport = "idle";
470
+ let freshness = "unknown";
471
+ let lastError = null;
472
+ const eventFailures = /* @__PURE__ */ new Map();
473
+ const appliedEventIds = /* @__PURE__ */ new Set();
474
+ const appliedEventOrder = [];
475
+ function getSnapshot() {
476
+ return {
477
+ transport,
478
+ freshness,
479
+ attempt,
480
+ streamId,
481
+ cursor: cursor ? { ...cursor } : null,
482
+ head: head ? { ...head } : null,
483
+ error: lastError
484
+ };
485
+ }
486
+ function observe(observation) {
487
+ if (!options.onObservation) return;
488
+ try {
489
+ Promise.resolve(options.onObservation(observation)).catch(() => {});
490
+ } catch {}
491
+ }
492
+ function emitState() {
493
+ observe({
494
+ type: "state",
495
+ state: getSnapshot()
496
+ });
497
+ }
498
+ function setState(nextTransport, nextFreshness = freshness) {
499
+ transport = nextTransport;
500
+ freshness = nextFreshness;
501
+ emitState();
502
+ }
503
+ function reportError(error) {
504
+ lastError = error;
505
+ observe({
506
+ type: "error",
507
+ error,
508
+ state: getSnapshot()
509
+ });
510
+ emitState();
511
+ }
512
+ function clearTimer(handle) {
513
+ if (handle !== void 0) runtime.clearTimeout(handle);
514
+ }
515
+ function clearConnectionTimers() {
516
+ clearTimer(heartbeatTimer);
517
+ clearTimer(rotationTimer);
518
+ heartbeatTimer = void 0;
519
+ rotationTimer = void 0;
520
+ }
521
+ function ensureEpoch(context) {
522
+ if (!running || current !== context || context.closed || context.epoch !== epoch) throw new StaleEpochError();
523
+ }
524
+ function closeSocket(context, code, reason) {
525
+ if (context.closed) return;
526
+ context.closed = true;
527
+ if (current === context) {
528
+ current = null;
529
+ epoch++;
530
+ }
531
+ clearConnectionTimers();
532
+ try {
533
+ context.socket.close(code, reason);
534
+ } catch {}
535
+ }
536
+ function reconnectBackoff() {
537
+ const exponent = Math.max(0, attempt - 1);
538
+ const cap = Math.min(GSCDUMP_REALTIME_CONNECTION_POLICY.reconnectMaxDelayMs, GSCDUMP_REALTIME_CONNECTION_POLICY.reconnectBaseDelayMs * 2 ** exponent);
539
+ return cap / 2 + safeRandom(runtime.random) * cap / 2;
540
+ }
541
+ function scheduleReconnect(context, reason, minimumDelayMs = 0, immediate = false) {
542
+ if (!running) return;
543
+ if (context) closeSocket(context, GSCDUMP_REALTIME_CLOSE_CODES.internalError, reason);
544
+ clearTimer(reconnectTimer);
545
+ attempt++;
546
+ const delay = immediate ? minimumDelayMs : Math.max(minimumDelayMs, reconnectBackoff());
547
+ setState("waiting", freshness === "unknown" || freshness === "degraded" ? freshness : "stale");
548
+ reconnectTimer = runtime.setTimeout(() => {
549
+ reconnectTimer = void 0;
550
+ beginAttempt();
551
+ }, delay);
552
+ }
553
+ function terminal(error, context = current) {
554
+ running = false;
555
+ clearTimer(reconnectTimer);
556
+ reconnectTimer = void 0;
557
+ if (context) closeSocket(context, GSCDUMP_REALTIME_CLOSE_CODES.normal, "terminal");
558
+ freshness = "degraded";
559
+ transport = "terminal";
560
+ reportError(error);
561
+ }
562
+ function assertStream(value, context, label) {
563
+ if (value.streamId !== context.ticket.head.streamId) throw new GscdumpRealtimeV1Error({
564
+ code: "protocol_error",
565
+ message: `${label} did not match the ticket's exact stream.`,
566
+ retryable: false,
567
+ terminal: true,
568
+ details: {
569
+ expected: context.ticket.head.streamId,
570
+ received: value.streamId
571
+ }
572
+ });
573
+ }
574
+ function sendJson(context, value) {
575
+ ensureEpoch(context);
576
+ const serialized = JSON.stringify(value);
577
+ if (utf8Size(serialized) > GSCDUMP_REALTIME_LIMITS.clientFrameMaxBytes) throw new GscdumpRealtimeV1Error({
578
+ code: "protocol_error",
579
+ message: "The generated client frame exceeded the v1 size limit.",
580
+ retryable: false,
581
+ terminal: true
582
+ });
583
+ try {
584
+ context.socket.send(serialized);
585
+ } catch (cause) {
586
+ throw new GscdumpRealtimeV1Error({
587
+ code: "socket_error",
588
+ message: "Could not send a realtime client frame.",
589
+ retryable: true,
590
+ terminal: false,
591
+ cause
592
+ });
593
+ }
594
+ }
595
+ function sendAck(context, appliedCursor) {
596
+ sendJson(context, protocol.schemas.ackFrame.parse({
597
+ type: "ack",
598
+ cursor: appliedCursor
599
+ }));
600
+ }
601
+ function eventDedupeKey(stream, id) {
602
+ return `${stream}:${id}`;
603
+ }
604
+ function rememberEvent(stream, id) {
605
+ const key = eventDedupeKey(stream, id);
606
+ if (appliedEventIds.has(key)) return;
607
+ appliedEventIds.add(key);
608
+ appliedEventOrder.push(key);
609
+ if (appliedEventOrder.length > 1e4) {
610
+ const oldest = appliedEventOrder.shift();
611
+ if (oldest) appliedEventIds.delete(oldest);
612
+ }
613
+ }
614
+ function eventFailureKey(event) {
615
+ return `${event.cursor?.streamId ?? "ephemeral"}:${event.id}:${event.cursor?.sequence ?? "ephemeral"}`;
616
+ }
617
+ function eventForRequiredEffect(event) {
618
+ return REALTIME_V1_EVENT_NAMES.includes(event.name) && event.eventVersion === 1 ? event : {
619
+ ...event,
620
+ data: null
621
+ };
622
+ }
623
+ function eventAdvisories(event) {
624
+ if (!REALTIME_V1_EVENT_NAMES.includes(event.name)) observe({
625
+ type: "advisory",
626
+ code: "unknown_event",
627
+ event
628
+ });
629
+ else if (event.eventVersion !== 1) observe({
630
+ type: "advisory",
631
+ code: "unsupported_event_version",
632
+ event
633
+ });
634
+ if (event.changes.some((change) => !REALTIME_V1_RESOURCE_TYPES.includes(change.type))) observe({
635
+ type: "advisory",
636
+ code: "unknown_resource",
637
+ event
638
+ });
639
+ }
640
+ async function saveCursor(context, nextCursor) {
641
+ ensureEpoch(context);
642
+ await cursorStore.save(nextCursor);
643
+ ensureEpoch(context);
644
+ }
645
+ async function performResync(context, request) {
646
+ ensureEpoch(context);
647
+ setState("handshaking", "resyncing");
648
+ try {
649
+ await options.resync(request);
650
+ ensureEpoch(context);
651
+ } catch (cause) {
652
+ if (cause instanceof StaleEpochError || !running || current !== context || context.closed) return;
653
+ terminal(new GscdumpRealtimeV1Error({
654
+ code: "resync_failed",
655
+ message: `Realtime resync failed (${request.reason}).`,
656
+ retryable: false,
657
+ terminal: true,
658
+ details: {
659
+ reason: request.reason,
660
+ resumeAfter: request.resumeAfter
661
+ },
662
+ cause
663
+ }), context);
664
+ return;
665
+ }
666
+ try {
667
+ await saveCursor(context, request.resumeAfter);
668
+ } catch (cause) {
669
+ if (cause instanceof StaleEpochError || !running || current !== context || context.closed) return;
670
+ terminal(new GscdumpRealtimeV1Error({
671
+ code: "cursor_store_failed",
672
+ message: "Realtime resync completed, but its resume cursor could not be persisted.",
673
+ retryable: false,
674
+ terminal: true,
675
+ details: { resumeAfter: request.resumeAfter },
676
+ cause
677
+ }), context);
678
+ return;
679
+ }
680
+ cursor = { ...request.resumeAfter };
681
+ eventFailures.clear();
682
+ emitState();
683
+ scheduleReconnect(context, "resync-complete", 0, true);
684
+ }
685
+ async function handleEventFailure(context, event, code, cause) {
686
+ if (cause instanceof StaleEpochError) return;
687
+ ensureEpoch(context);
688
+ const key = eventFailureKey(event);
689
+ const failures = (eventFailures.get(key) ?? 0) + 1;
690
+ eventFailures.set(key, failures);
691
+ const error = new GscdumpRealtimeV1Error({
692
+ code,
693
+ message: code === "effect_failed" ? `The required effect rejected for durable event ${event.id}.` : `The cursor store rejected durable event ${event.id}.`,
694
+ retryable: failures < GSCDUMP_REALTIME_ACK_POLICY.effectRetryBeforeUnsafeResync,
695
+ terminal: false,
696
+ details: {
697
+ eventId: event.id,
698
+ sequence: event.cursor?.sequence,
699
+ failures
700
+ },
701
+ cause
702
+ });
703
+ freshness = "degraded";
704
+ reportError(error);
705
+ if (failures < GSCDUMP_REALTIME_ACK_POLICY.effectRetryBeforeUnsafeResync) {
706
+ scheduleReconnect(context, code);
707
+ return;
708
+ }
709
+ const eventCursor = event.cursor;
710
+ if (!eventCursor) return;
711
+ const resumeAfter = context.head ? laterCursor(context.head, eventCursor) : eventCursor;
712
+ await performResync(context, {
713
+ reason: "effect_application_failed",
714
+ source: "client",
715
+ streamId: eventCursor.streamId,
716
+ previousCursor: cursor,
717
+ resumeAfter,
718
+ failedEvent: event,
719
+ cause
720
+ });
721
+ }
722
+ async function applyDurableEvent(context, event) {
723
+ ensureEpoch(context);
724
+ assertStream(event.cursor, context, "event cursor");
725
+ if (context.replayThrough && compareSequence(event.cursor.sequence, context.replayThrough.sequence) > 0) throw new GscdumpRealtimeV1Error({
726
+ code: "protocol_error",
727
+ message: "A live event arrived before the declared replay completed.",
728
+ retryable: false,
729
+ terminal: true
730
+ });
731
+ if (!context.replaying && (!context.head || compareSequence(event.cursor.sequence, context.head.sequence) > 0)) {
732
+ context.head = { ...event.cursor };
733
+ head = { ...event.cursor };
734
+ }
735
+ if (!cursor) {
736
+ await performResync(context, {
737
+ reason: "initial_cursor_missing",
738
+ source: "client",
739
+ streamId: event.cursor.streamId,
740
+ previousCursor: null,
741
+ resumeAfter: context.head ? laterCursor(context.head, event.cursor) : event.cursor
742
+ });
743
+ return;
744
+ }
745
+ assertStream(cursor, context, "stored cursor");
746
+ if (compareSequence(event.cursor.sequence, cursor.sequence) <= 0) {
747
+ sendAck(context, cursor);
748
+ return;
749
+ }
750
+ if (event.cursor.sequence !== nextSequence(cursor.sequence)) {
751
+ const resumeAfter = context.head ? laterCursor(context.head, event.cursor) : event.cursor;
752
+ await performResync(context, {
753
+ reason: "sequence_gap",
754
+ source: "client",
755
+ streamId: event.cursor.streamId,
756
+ previousCursor: cursor,
757
+ resumeAfter
758
+ });
759
+ return;
760
+ }
761
+ setState(context.replaying ? "replaying" : "live", "applying");
762
+ const effectEvent = eventForRequiredEffect(event);
763
+ if (!appliedEventIds.has(eventDedupeKey(event.cursor.streamId, event.id))) try {
764
+ await options.applyEvent(effectEvent);
765
+ ensureEpoch(context);
766
+ } catch (cause) {
767
+ await handleEventFailure(context, event, "effect_failed", cause);
768
+ return;
769
+ }
770
+ try {
771
+ await saveCursor(context, event.cursor);
772
+ } catch (cause) {
773
+ await handleEventFailure(context, event, "cursor_store_failed", cause);
774
+ return;
775
+ }
776
+ cursor = { ...event.cursor };
777
+ rememberEvent(event.cursor.streamId, event.id);
778
+ eventFailures.delete(eventFailureKey(event));
779
+ sendAck(context, cursor);
780
+ freshness = context.replaying ? "stale" : "fresh";
781
+ transport = context.replaying ? "replaying" : "live";
782
+ emitState();
783
+ eventAdvisories(effectEvent);
784
+ observe({
785
+ type: "event",
786
+ event: effectEvent,
787
+ cursor: { ...cursor }
788
+ });
789
+ }
790
+ function scheduleHeartbeat(context) {
791
+ clearTimer(heartbeatTimer);
792
+ heartbeatTimer = runtime.setTimeout(() => {
793
+ heartbeatTimer = void 0;
794
+ if (!running || current !== context || context.closed) return;
795
+ const staleFor = runtime.now() - context.lastPongAt;
796
+ if (staleFor >= GSCDUMP_REALTIME_CONNECTION_POLICY.staleAfterMs) {
797
+ const error = new GscdumpRealtimeV1Error({
798
+ code: "heartbeat_stale",
799
+ message: "Realtime heartbeat became stale.",
800
+ retryable: true,
801
+ terminal: false,
802
+ details: { staleFor }
803
+ });
804
+ freshness = "stale";
805
+ reportError(error);
806
+ scheduleReconnect(context, "heartbeat-stale");
807
+ return;
808
+ }
809
+ try {
810
+ context.socket.send(GSCDUMP_REALTIME_PING);
811
+ } catch (cause) {
812
+ reportError(new GscdumpRealtimeV1Error({
813
+ code: "socket_error",
814
+ message: "Could not send the realtime heartbeat.",
815
+ retryable: true,
816
+ terminal: false,
817
+ cause
818
+ }));
819
+ scheduleReconnect(context, "heartbeat-send");
820
+ return;
821
+ }
822
+ scheduleHeartbeat(context);
823
+ }, GSCDUMP_REALTIME_CONNECTION_POLICY.heartbeatIntervalMs);
824
+ }
825
+ function scheduleRotation(context, expiresAt) {
826
+ clearTimer(rotationTimer);
827
+ const delay = Math.max(0, Date.parse(expiresAt) - runtime.now() - GSCDUMP_REALTIME_CONNECTION_POLICY.connectionRefreshBeforeExpiryMs);
828
+ rotationTimer = runtime.setTimeout(() => {
829
+ rotationTimer = void 0;
830
+ if (running && current === context && !context.closed) scheduleReconnect(context, "connection-expiry-rotation", 0, true);
831
+ }, delay);
832
+ }
833
+ async function handleReady(context, frame) {
834
+ ensureEpoch(context);
835
+ if (context.ready) throw new GscdumpRealtimeV1Error({
836
+ code: "protocol_error",
837
+ message: "The server sent more than one ready frame.",
838
+ retryable: false,
839
+ terminal: true
840
+ });
841
+ assertStream(frame, context, "ready frame");
842
+ assertStream(frame.head, context, "ready head");
843
+ assertStream(frame.replayFloor, context, "ready replay floor");
844
+ if (compareSequence(frame.head.sequence, context.ticket.head.sequence) < 0) throw new GscdumpRealtimeV1Error({
845
+ code: "protocol_error",
846
+ message: "The ready head regressed behind the ticket head.",
847
+ retryable: false,
848
+ terminal: true,
849
+ details: {
850
+ ticketHead: context.ticket.head,
851
+ readyHead: frame.head
852
+ }
853
+ });
854
+ const expiresAt = Date.parse(frame.expiresAt);
855
+ if (!Number.isFinite(expiresAt) || expiresAt <= runtime.now() || expiresAt - runtime.now() > context.ticket.maxConnectionSeconds * 1e3) throw new GscdumpRealtimeV1Error({
856
+ code: "protocol_error",
857
+ message: "The ready frame carried an invalid signed connection expiry.",
858
+ retryable: false,
859
+ terminal: true,
860
+ details: { expiresAt: frame.expiresAt }
861
+ });
862
+ context.ready = true;
863
+ context.head = { ...frame.head };
864
+ context.lastPongAt = runtime.now();
865
+ head = { ...frame.head };
866
+ streamId = frame.streamId;
867
+ attempt = 0;
868
+ lastError = null;
869
+ scheduleHeartbeat(context);
870
+ scheduleRotation(context, frame.expiresAt);
871
+ if (!cursor) {
872
+ await performResync(context, {
873
+ reason: "initial_cursor_missing",
874
+ source: "client",
875
+ streamId: frame.streamId,
876
+ previousCursor: null,
877
+ resumeAfter: frame.head
878
+ });
879
+ return;
880
+ }
881
+ if (cursor.streamId !== frame.streamId) {
882
+ await performResync(context, {
883
+ reason: "stream_mismatch",
884
+ source: "client",
885
+ streamId: frame.streamId,
886
+ previousCursor: cursor,
887
+ resumeAfter: frame.head
888
+ });
889
+ return;
890
+ }
891
+ if (compareSequence(cursor.sequence, frame.head.sequence) > 0) {
892
+ await performResync(context, {
893
+ reason: "sequence_gap",
894
+ source: "client",
895
+ streamId: frame.streamId,
896
+ previousCursor: cursor,
897
+ resumeAfter: frame.head
898
+ });
899
+ return;
900
+ }
901
+ if (compareSequence(cursor.sequence, frame.replayFloor.sequence) < 0) {
902
+ await performResync(context, {
903
+ reason: "cursor_expired",
904
+ source: "client",
905
+ streamId: frame.streamId,
906
+ previousCursor: cursor,
907
+ resumeAfter: frame.head
908
+ });
909
+ return;
910
+ }
911
+ if (sameCursor(cursor, frame.head)) {
912
+ context.replaying = false;
913
+ setState("live", "fresh");
914
+ } else {
915
+ context.replaying = true;
916
+ setState("replaying", "stale");
917
+ }
918
+ }
919
+ async function processFrame(context, frame) {
920
+ ensureEpoch(context);
921
+ if (frame.type === "ready") {
922
+ await handleReady(context, frame);
923
+ return;
924
+ }
925
+ if (frame.type === "error") {
926
+ const retryable = !(frame.error.code === "invalid_frame" || frame.error.code === "protocol_mismatch" || frame.error.code === "policy_violation") && frame.error.retryable;
927
+ const error = new GscdumpRealtimeV1Error({
928
+ code: frame.error.code === "internal_error" || frame.error.code === "overloaded" ? "socket_error" : "protocol_error",
929
+ message: frame.error.message,
930
+ retryable,
931
+ terminal: !retryable,
932
+ details: {
933
+ serverCode: frame.error.code,
934
+ retryAfter: frame.error.retryAfter
935
+ }
936
+ });
937
+ reportError(error);
938
+ if (retryable) {
939
+ context.retryAfterMs = frame.error.retryAfter === void 0 ? void 0 : frame.error.retryAfter * 1e3;
940
+ scheduleReconnect(context, "server-error", context.retryAfterMs);
941
+ } else terminal(error, context);
942
+ return;
943
+ }
944
+ if (!context.ready) throw new GscdumpRealtimeV1Error({
945
+ code: "protocol_error",
946
+ message: `The server sent ${frame.type} before ready.`,
947
+ retryable: false,
948
+ terminal: true
949
+ });
950
+ if (frame.type === "replay.begin") {
951
+ assertStream(frame.through, context, "replay through cursor");
952
+ if (frame.after) assertStream(frame.after, context, "replay after cursor");
953
+ if (context.replayThrough) throw new GscdumpRealtimeV1Error({
954
+ code: "protocol_error",
955
+ message: "The server sent a nested replay.begin frame.",
956
+ retryable: false,
957
+ terminal: true
958
+ });
959
+ if (!sameCursor(frame.after, cursor)) {
960
+ await performResync(context, {
961
+ reason: "sequence_gap",
962
+ source: "client",
963
+ streamId: context.ticket.head.streamId,
964
+ previousCursor: cursor,
965
+ resumeAfter: frame.through
966
+ });
967
+ return;
968
+ }
969
+ if (!context.head || !sameCursor(frame.through, context.head)) throw new GscdumpRealtimeV1Error({
970
+ code: "protocol_error",
971
+ message: "The replay boundary did not match the ready head.",
972
+ retryable: false,
973
+ terminal: true
974
+ });
975
+ context.replaying = true;
976
+ context.replayThrough = { ...frame.through };
977
+ setState("replaying", "stale");
978
+ return;
979
+ }
980
+ if (frame.type === "replay.end") {
981
+ assertStream(frame.through, context, "replay end cursor");
982
+ if (!context.replaying || !context.replayThrough || !sameCursor(context.replayThrough, frame.through) || !sameCursor(cursor, frame.through)) {
983
+ await performResync(context, {
984
+ reason: "sequence_gap",
985
+ source: "client",
986
+ streamId: frame.through.streamId,
987
+ previousCursor: cursor,
988
+ resumeAfter: context.head ? laterCursor(context.head, frame.through) : frame.through
989
+ });
990
+ return;
991
+ }
992
+ context.replaying = false;
993
+ context.replayThrough = null;
994
+ setState("live", "fresh");
995
+ return;
996
+ }
997
+ if (frame.type === "resync.required") {
998
+ assertStream(frame.scope, context, "resync scope");
999
+ assertStream(frame.resumeAfter, context, "resync cursor");
1000
+ const minimumSequence = context.head && cursor ? laterCursor(context.head, cursor).sequence : context.head?.sequence ?? cursor?.sequence;
1001
+ if (minimumSequence !== void 0 && compareSequence(frame.resumeAfter.sequence, minimumSequence) < 0) throw new GscdumpRealtimeV1Error({
1002
+ code: "protocol_error",
1003
+ message: "The resync cursor regressed behind observed stream state.",
1004
+ retryable: false,
1005
+ terminal: true,
1006
+ details: {
1007
+ minimumSequence,
1008
+ resumeAfter: frame.resumeAfter
1009
+ }
1010
+ });
1011
+ await performResync(context, {
1012
+ reason: frame.reason,
1013
+ source: "server",
1014
+ streamId: frame.scope.streamId,
1015
+ previousCursor: cursor,
1016
+ resumeAfter: frame.resumeAfter
1017
+ });
1018
+ return;
1019
+ }
1020
+ if (frame.type === "batch") {
1021
+ if (context.replaying && !context.replayThrough) throw new GscdumpRealtimeV1Error({
1022
+ code: "protocol_error",
1023
+ message: "A replay batch arrived before replay.begin.",
1024
+ retryable: false,
1025
+ terminal: true
1026
+ });
1027
+ for (const event of frame.events) {
1028
+ ensureEpoch(context);
1029
+ await applyDurableEvent(context, event);
1030
+ }
1031
+ return;
1032
+ }
1033
+ if (frame.type === "event") {
1034
+ if (frame.delivery === "ephemeral") {
1035
+ const observedEvent = eventForRequiredEffect(frame);
1036
+ eventAdvisories(observedEvent);
1037
+ observe({
1038
+ type: "event",
1039
+ event: observedEvent,
1040
+ cursor: cursor ? { ...cursor } : null
1041
+ });
1042
+ return;
1043
+ }
1044
+ if (context.replaying && !context.replayThrough) throw new GscdumpRealtimeV1Error({
1045
+ code: "protocol_error",
1046
+ message: "A durable replay event arrived before replay.begin.",
1047
+ retryable: false,
1048
+ terminal: true
1049
+ });
1050
+ await applyDurableEvent(context, frame);
1051
+ }
1052
+ }
1053
+ async function processRawMessage(context, raw) {
1054
+ ensureEpoch(context);
1055
+ const text = await messageText(raw);
1056
+ ensureEpoch(context);
1057
+ if (text === GSCDUMP_REALTIME_PONG) {
1058
+ context.lastPongAt = runtime.now();
1059
+ return;
1060
+ }
1061
+ if (utf8Size(text) > GSCDUMP_REALTIME_LIMITS.outboundFrameMaxBytes) throw new GscdumpRealtimeV1Error({
1062
+ code: "protocol_error",
1063
+ message: "A server frame exceeded the v1 outbound frame limit.",
1064
+ retryable: false,
1065
+ terminal: true
1066
+ });
1067
+ let rawFrame;
1068
+ try {
1069
+ rawFrame = JSON.parse(text);
1070
+ } catch (cause) {
1071
+ throw new GscdumpRealtimeV1Error({
1072
+ code: "protocol_error",
1073
+ message: "The server sent malformed realtime JSON.",
1074
+ retryable: false,
1075
+ terminal: true,
1076
+ cause
1077
+ });
1078
+ }
1079
+ const parsed = protocol.schemas.serverFrame.safeParse(rawFrame);
1080
+ if (!parsed.success) throw new GscdumpRealtimeV1Error({
1081
+ code: "protocol_error",
1082
+ message: "The server frame did not match the v1 protocol.",
1083
+ retryable: false,
1084
+ terminal: true,
1085
+ details: parseErrorDetails(parsed.error),
1086
+ cause: parsed.error
1087
+ });
1088
+ if (parsed.data.type === "event") {
1089
+ const eventLimit = parsed.data.delivery === "durable" ? GSCDUMP_REALTIME_LIMITS.durableEventMaxBytes : GSCDUMP_REALTIME_LIMITS.ephemeralEventMaxBytes;
1090
+ if (utf8Size(text) > eventLimit) throw new GscdumpRealtimeV1Error({
1091
+ code: "protocol_error",
1092
+ message: `A ${parsed.data.delivery} event exceeded its v1 size limit.`,
1093
+ retryable: false,
1094
+ terminal: true
1095
+ });
1096
+ }
1097
+ if (parsed.data.type === "batch") {
1098
+ for (const event of parsed.data.events) if (utf8Size(JSON.stringify(event)) > GSCDUMP_REALTIME_LIMITS.durableEventMaxBytes) throw new GscdumpRealtimeV1Error({
1099
+ code: "protocol_error",
1100
+ message: "A durable event inside a batch exceeded its v1 size limit.",
1101
+ retryable: false,
1102
+ terminal: true
1103
+ });
1104
+ }
1105
+ await processFrame(context, parsed.data);
1106
+ }
1107
+ function handleFrameQueueError(context, cause) {
1108
+ if (cause instanceof StaleEpochError || !running || current !== context) return;
1109
+ const error = cause instanceof GscdumpRealtimeV1Error ? cause : new GscdumpRealtimeV1Error({
1110
+ code: "protocol_error",
1111
+ message: "Realtime frame processing failed.",
1112
+ retryable: false,
1113
+ terminal: true,
1114
+ cause
1115
+ });
1116
+ if (error.terminal) {
1117
+ terminal(error, context);
1118
+ return;
1119
+ }
1120
+ reportError(error);
1121
+ scheduleReconnect(context, error.code);
1122
+ }
1123
+ async function loadCursor(ticket) {
1124
+ let stored;
1125
+ try {
1126
+ stored = await cursorStore.load();
1127
+ } catch (cause) {
1128
+ throw new GscdumpRealtimeV1Error({
1129
+ code: "cursor_store_failed",
1130
+ message: "Could not load the realtime cursor.",
1131
+ retryable: false,
1132
+ terminal: true,
1133
+ cause
1134
+ });
1135
+ }
1136
+ if (stored === null) return null;
1137
+ const parsed = protocol.schemas.cursor.safeParse(stored);
1138
+ if (!parsed.success) {
1139
+ reportError(new GscdumpRealtimeV1Error({
1140
+ code: "cursor_store_failed",
1141
+ message: "The stored realtime cursor was invalid; a full resync is required.",
1142
+ retryable: true,
1143
+ terminal: false,
1144
+ details: parseErrorDetails(parsed.error),
1145
+ cause: parsed.error
1146
+ }));
1147
+ return null;
1148
+ }
1149
+ if (parsed.data.streamId !== ticket.head.streamId) return null;
1150
+ return parsed.data;
1151
+ }
1152
+ async function provideFreshTicket() {
1153
+ let raw;
1154
+ try {
1155
+ raw = await options.ticketProvider();
1156
+ } catch (cause) {
1157
+ throw new GscdumpRealtimeV1Error({
1158
+ code: "ticket_provider_failed",
1159
+ message: "The realtime ticket provider rejected.",
1160
+ retryable: true,
1161
+ terminal: false,
1162
+ cause
1163
+ });
1164
+ }
1165
+ const parsed = protocol.schemas.ticketResponse.client.safeParse(raw);
1166
+ if (!parsed.success) throw new GscdumpRealtimeV1Error({
1167
+ code: "ticket_invalid",
1168
+ message: "The realtime ticket response did not match the v1 contract.",
1169
+ retryable: false,
1170
+ terminal: true,
1171
+ details: parseErrorDetails(parsed.error),
1172
+ cause: parsed.error
1173
+ });
1174
+ if (Date.parse(parsed.data.data.expiresAt) <= runtime.now()) throw new GscdumpRealtimeV1Error({
1175
+ code: "ticket_invalid",
1176
+ message: "The realtime ticket had already expired locally.",
1177
+ retryable: true,
1178
+ terminal: false,
1179
+ details: { localExpiry: true }
1180
+ });
1181
+ return parsed.data.data;
1182
+ }
1183
+ async function beginAttempt() {
1184
+ if (!running) return;
1185
+ const attemptEpoch = ++epoch;
1186
+ setState("ticketing", freshness === "fresh" ? "stale" : freshness);
1187
+ let ticket;
1188
+ try {
1189
+ ticket = await provideFreshTicket();
1190
+ } catch (cause) {
1191
+ if (!running || epoch !== attemptEpoch) return;
1192
+ const error = cause instanceof GscdumpRealtimeV1Error ? cause : new GscdumpRealtimeV1Error({
1193
+ code: "ticket_provider_failed",
1194
+ message: "Could not obtain a realtime ticket.",
1195
+ retryable: true,
1196
+ terminal: false,
1197
+ cause
1198
+ });
1199
+ if (error.code === "ticket_invalid" && error.details.localExpiry === true && immediateExpiredTicketRetry) {
1200
+ immediateExpiredTicketRetry = false;
1201
+ beginAttempt();
1202
+ return;
1203
+ }
1204
+ reportError(error);
1205
+ if (error.terminal) terminal(error, null);
1206
+ else scheduleReconnect(null, error.code);
1207
+ return;
1208
+ }
1209
+ immediateExpiredTicketRetry = true;
1210
+ if (!running || epoch !== attemptEpoch) return;
1211
+ try {
1212
+ cursor = await loadCursor(ticket);
1213
+ } catch (cause) {
1214
+ if (!running || epoch !== attemptEpoch) return;
1215
+ terminal(cause, null);
1216
+ return;
1217
+ }
1218
+ if (!running || epoch !== attemptEpoch) return;
1219
+ streamId = ticket.head.streamId;
1220
+ head = { ...ticket.head };
1221
+ emitState();
1222
+ let socket;
1223
+ try {
1224
+ socket = runtime.createSocket(ticket.socketUrl, [ticket.protocol, ticket.ticket]);
1225
+ } catch (cause) {
1226
+ terminal(cause instanceof GscdumpRealtimeV1Error ? cause : new GscdumpRealtimeV1Error({
1227
+ code: "runtime_unavailable",
1228
+ message: "Could not create the realtime WebSocket.",
1229
+ retryable: false,
1230
+ terminal: true,
1231
+ cause
1232
+ }), null);
1233
+ return;
1234
+ }
1235
+ const context = {
1236
+ epoch: attemptEpoch,
1237
+ socket,
1238
+ ticket,
1239
+ accepted: false,
1240
+ ready: false,
1241
+ closed: false,
1242
+ replaying: false,
1243
+ replayThrough: null,
1244
+ lastPongAt: runtime.now(),
1245
+ head: null,
1246
+ retryAfterMs: void 0,
1247
+ frameQueue: Promise.resolve()
1248
+ };
1249
+ current = context;
1250
+ setState("connecting", freshness);
1251
+ socket.onopen = () => {
1252
+ if (!running || current !== context || context.closed) return;
1253
+ context.accepted = true;
1254
+ if (socket.protocol !== GSCDUMP_REALTIME_SUBPROTOCOL) {
1255
+ terminal(new GscdumpRealtimeV1Error({
1256
+ code: "protocol_error",
1257
+ message: "The WebSocket did not select gscdump.v1.",
1258
+ retryable: false,
1259
+ terminal: true,
1260
+ details: { selectedProtocol: socket.protocol }
1261
+ }), context);
1262
+ return;
1263
+ }
1264
+ setState("handshaking", cursor ? "stale" : "unknown");
1265
+ try {
1266
+ const hello = protocol.schemas.helloFrame.parse({
1267
+ type: "hello",
1268
+ protocolVersion: protocol.constants.realtimeProtocolVersion,
1269
+ sdkVersion,
1270
+ resume: cursor
1271
+ });
1272
+ sendJson(context, hello);
1273
+ } catch (cause) {
1274
+ handleFrameQueueError(context, cause);
1275
+ }
1276
+ };
1277
+ socket.onmessage = (event) => {
1278
+ if (!running || current !== context || context.closed) return;
1279
+ const work = context.frameQueue.then(() => processRawMessage(context, event.data));
1280
+ context.frameQueue = work.catch((cause) => {
1281
+ handleFrameQueueError(context, cause);
1282
+ });
1283
+ };
1284
+ socket.onerror = (cause) => {
1285
+ if (!running || current !== context || context.closed) return;
1286
+ const error = new GscdumpRealtimeV1Error({
1287
+ code: context.accepted ? "socket_error" : "upgrade_rejected",
1288
+ message: context.accepted ? "The accepted realtime socket emitted an opaque error." : "The realtime WebSocket upgrade was rejected or failed opaquely.",
1289
+ retryable: true,
1290
+ terminal: false,
1291
+ cause
1292
+ });
1293
+ reportError(error);
1294
+ scheduleReconnect(context, error.code);
1295
+ };
1296
+ socket.onclose = (event) => {
1297
+ if (context.closed || current !== context) return;
1298
+ current = null;
1299
+ epoch++;
1300
+ clearConnectionTimers();
1301
+ const code = event.code ?? 1006;
1302
+ if (!running) return;
1303
+ if (!context.accepted) {
1304
+ reportError(new GscdumpRealtimeV1Error({
1305
+ code: "upgrade_rejected",
1306
+ message: "The realtime WebSocket upgrade failed opaquely.",
1307
+ retryable: true,
1308
+ terminal: false,
1309
+ details: { closeCode: code }
1310
+ }));
1311
+ scheduleReconnect(null, "upgrade-rejected");
1312
+ return;
1313
+ }
1314
+ if (code === GSCDUMP_REALTIME_CLOSE_CODES.normal) {
1315
+ running = false;
1316
+ setState("stopped", "unknown");
1317
+ return;
1318
+ }
1319
+ if (code === GSCDUMP_REALTIME_CLOSE_CODES.protocolError || code === GSCDUMP_REALTIME_CLOSE_CODES.policyViolation) {
1320
+ terminal(new GscdumpRealtimeV1Error({
1321
+ code: "protocol_error",
1322
+ message: `The realtime server closed with terminal code ${code}.`,
1323
+ retryable: false,
1324
+ terminal: true,
1325
+ details: {
1326
+ closeCode: code,
1327
+ reason: event.reason
1328
+ }
1329
+ }), null);
1330
+ return;
1331
+ }
1332
+ if (code === GSCDUMP_REALTIME_CLOSE_CODES.maximumLifetime) {
1333
+ scheduleReconnect(null, "maximum-lifetime", 0, true);
1334
+ return;
1335
+ }
1336
+ if (code === 1006 || code === GSCDUMP_REALTIME_CLOSE_CODES.internalError || code === GSCDUMP_REALTIME_CLOSE_CODES.serviceRestart || code === GSCDUMP_REALTIME_CLOSE_CODES.overloadedOrAckLag) {
1337
+ scheduleReconnect(null, `close-${code}`, context.retryAfterMs);
1338
+ return;
1339
+ }
1340
+ terminal(new GscdumpRealtimeV1Error({
1341
+ code: "protocol_error",
1342
+ message: `The realtime server used an unsupported close code ${code}.`,
1343
+ retryable: false,
1344
+ terminal: true,
1345
+ details: {
1346
+ closeCode: code,
1347
+ reason: event.reason
1348
+ }
1349
+ }), null);
1350
+ };
1351
+ }
1352
+ async function start() {
1353
+ if (running) return;
1354
+ running = true;
1355
+ attempt = 0;
1356
+ lastError = null;
1357
+ immediateExpiredTicketRetry = true;
1358
+ freshness = cursor ? "stale" : "unknown";
1359
+ await beginAttempt();
1360
+ }
1361
+ function stop() {
1362
+ running = false;
1363
+ clearTimer(reconnectTimer);
1364
+ reconnectTimer = void 0;
1365
+ if (current) closeSocket(current, GSCDUMP_REALTIME_CLOSE_CODES.normal, "manual");
1366
+ else epoch++;
1367
+ setState("stopped", "unknown");
1368
+ }
1369
+ return {
1370
+ start,
1371
+ stop,
1372
+ getSnapshot
1373
+ };
1374
+ }
1375
+ export { GSCDUMP_REALTIME_V1_SDK_VERSION, GscdumpRealtimeV1Error, GscdumpV1Error, createGscdumpRealtimeV1Client, createGscdumpV1Client, isGscdumpV1Error };