@layers/amba-web 4.0.4 → 4.0.6
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.d.ts +783 -16
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1514 -22
- package/dist/index.js.map +1 -1
- package/dist-rn/index.d.ts +783 -16
- package/dist-rn/index.js +1514 -22
- package/package.json +2 -2
package/dist/index.js
CHANGED
|
@@ -39,11 +39,89 @@ function encodeJson(value) {
|
|
|
39
39
|
return JSON.stringify(value);
|
|
40
40
|
}
|
|
41
41
|
|
|
42
|
+
//#endregion
|
|
43
|
+
//#region src/ai-images.ts
|
|
44
|
+
/**
|
|
45
|
+
* Normalize an image input into a content block, applying the SAME validity
|
|
46
|
+
* rule the backend's gateway + the MCP tool use: trim `url`/`data`, treat a
|
|
47
|
+
* blank/whitespace-only value as absent, and return `null` when NEITHER a real
|
|
48
|
+
* url nor real data survives. A `null` block is dropped by the caller so we
|
|
49
|
+
* never emit an empty image — keeping the SDK, MCP, and gateway in agreement.
|
|
50
|
+
*/
|
|
51
|
+
function normalizeImageBlock(img) {
|
|
52
|
+
const url = typeof img.url === "string" && img.url.trim().length > 0 ? img.url.trim() : void 0;
|
|
53
|
+
const data = typeof img.data === "string" && img.data.trim().length > 0 ? img.data.trim() : void 0;
|
|
54
|
+
if (!url && !data) return null;
|
|
55
|
+
const block = { type: "image" };
|
|
56
|
+
if (url !== void 0) block.url = url;
|
|
57
|
+
if (data !== void 0) block.data = data;
|
|
58
|
+
if (img.mime !== void 0) block.mime = img.mime;
|
|
59
|
+
return block;
|
|
60
|
+
}
|
|
61
|
+
/**
|
|
62
|
+
* Expand a request's convenience `images` into content blocks on `messages`.
|
|
63
|
+
* Returns the SAME object reference when there's nothing to expand, or a new
|
|
64
|
+
* request (with `images` removed) when images were attached.
|
|
65
|
+
*/
|
|
66
|
+
function expandAiImages(request) {
|
|
67
|
+
const images = request.images;
|
|
68
|
+
if (!images || images.length === 0) return request;
|
|
69
|
+
const imageBlocks = images.map(normalizeImageBlock).filter((b) => b !== null);
|
|
70
|
+
const { images: _images,...rest } = request;
|
|
71
|
+
if (imageBlocks.length === 0) return rest;
|
|
72
|
+
const messages = (rest.messages ?? []).map((m) => ({ ...m }));
|
|
73
|
+
let lastUserIdx = -1;
|
|
74
|
+
for (let i = messages.length - 1; i >= 0; i--) if (messages[i].role === "user") {
|
|
75
|
+
lastUserIdx = i;
|
|
76
|
+
break;
|
|
77
|
+
}
|
|
78
|
+
if (lastUserIdx === -1) {
|
|
79
|
+
const variableBlocks = rest.variables && Object.keys(rest.variables).length > 0 ? [{
|
|
80
|
+
type: "text",
|
|
81
|
+
text: JSON.stringify(rest.variables)
|
|
82
|
+
}] : [];
|
|
83
|
+
messages.push({
|
|
84
|
+
role: "user",
|
|
85
|
+
content: [...variableBlocks, ...imageBlocks]
|
|
86
|
+
});
|
|
87
|
+
} else {
|
|
88
|
+
const existing = messages[lastUserIdx].content;
|
|
89
|
+
let leadingBlocks;
|
|
90
|
+
if (typeof existing === "string") leadingBlocks = [{
|
|
91
|
+
type: "text",
|
|
92
|
+
text: existing
|
|
93
|
+
}];
|
|
94
|
+
else if (Array.isArray(existing)) leadingBlocks = existing;
|
|
95
|
+
else if (existing === null || existing === void 0) leadingBlocks = [];
|
|
96
|
+
else leadingBlocks = [{
|
|
97
|
+
type: "text",
|
|
98
|
+
text: JSON.stringify(existing)
|
|
99
|
+
}];
|
|
100
|
+
messages[lastUserIdx] = {
|
|
101
|
+
...messages[lastUserIdx],
|
|
102
|
+
content: [...leadingBlocks, ...imageBlocks]
|
|
103
|
+
};
|
|
104
|
+
}
|
|
105
|
+
return {
|
|
106
|
+
...rest,
|
|
107
|
+
messages
|
|
108
|
+
};
|
|
109
|
+
}
|
|
110
|
+
|
|
42
111
|
//#endregion
|
|
43
112
|
//#region src/error.ts
|
|
44
113
|
var AmbaApiError = class extends Error {
|
|
45
114
|
code;
|
|
46
115
|
details;
|
|
116
|
+
/**
|
|
117
|
+
* Server-side request / trace id (the `X-Amba-Request-Id` response
|
|
118
|
+
* header, falling back to the `request_id` field in the standard error
|
|
119
|
+
* envelope). Present on errors thrown by `Amba.functions.invoke()` so a
|
|
120
|
+
* failed run can be correlated with server logs
|
|
121
|
+
* (`functions logs --request-id <traceId>`). `undefined` when the failure
|
|
122
|
+
* happened before a response was received (e.g. a transport error).
|
|
123
|
+
*/
|
|
124
|
+
traceId;
|
|
47
125
|
constructor(code, message, details) {
|
|
48
126
|
super(message);
|
|
49
127
|
this.name = "AmbaApiError";
|
|
@@ -53,14 +131,13 @@ var AmbaApiError = class extends Error {
|
|
|
53
131
|
}
|
|
54
132
|
};
|
|
55
133
|
/**
|
|
56
|
-
* Best-effort: pull a stable error code out of
|
|
57
|
-
*
|
|
58
|
-
*
|
|
134
|
+
* Best-effort: pull a stable error code out of an `AmbaError` display
|
|
135
|
+
* string. Used by `toAmbaApiError` when the underlying thrown value is a
|
|
136
|
+
* generic `Error` produced by the SDK core.
|
|
59
137
|
*
|
|
60
|
-
* Keep in sync with
|
|
61
|
-
*
|
|
62
|
-
*
|
|
63
|
-
* just a quality-of-life regression.
|
|
138
|
+
* Keep in sync with the SDK core's `AmbaError` format strings — but the
|
|
139
|
+
* parser falls back to UNKNOWN_ERROR for any pattern it doesn't recognize,
|
|
140
|
+
* so a stale match list isn't a footgun, just a quality-of-life regression.
|
|
64
141
|
*/
|
|
65
142
|
function codeFromMessage(message) {
|
|
66
143
|
if (message.startsWith("Unauthorized")) return "UNAUTHORIZED";
|
|
@@ -103,6 +180,18 @@ function toAmbaApiError(err) {
|
|
|
103
180
|
//#region src/realtime.ts
|
|
104
181
|
const INITIAL_BACKOFF_MS = 500;
|
|
105
182
|
const MAX_BACKOFF_MS = 15e3;
|
|
183
|
+
const DEFAULT_API_URL$1 = "https://api.amba.dev";
|
|
184
|
+
const DEFAULT_REALTIME_URL = "https://realtime.amba.host";
|
|
185
|
+
/**
|
|
186
|
+
* Resolve the base URL for live-update connections. Long-lived streams are
|
|
187
|
+
* served from a dedicated realtime host (no request-duration ceiling), so
|
|
188
|
+
* when the SDK points at the default production API the stream connects
|
|
189
|
+
* there instead. Any custom `apiUrl` (dev, staging, self-hosted, proxy)
|
|
190
|
+
* keeps live updates on that same origin — override semantics unchanged.
|
|
191
|
+
*/
|
|
192
|
+
function resolveRealtimeBaseUrl(baseUrl) {
|
|
193
|
+
return baseUrl.replace(/\/+$/, "") === DEFAULT_API_URL$1 ? DEFAULT_REALTIME_URL : baseUrl;
|
|
194
|
+
}
|
|
106
195
|
/**
|
|
107
196
|
* Builder returned by `Amba.collection(name)`. Chain `.where(...)` to
|
|
108
197
|
* narrow, then `.subscribe(cb)` to start streaming.
|
|
@@ -126,7 +215,7 @@ var CollectionSubscription = class {
|
|
|
126
215
|
if (!this.ctx.authHeaders()) throw new Error("Amba.collection().subscribe() requires an authenticated session — call Amba.auth.signIn*/verify* first.");
|
|
127
216
|
const qs = Object.keys(this.filters).length > 0 ? `?where=${encodeURIComponent(JSON.stringify(this.filters))}` : "";
|
|
128
217
|
return openStream({
|
|
129
|
-
url: `${this.ctx.baseUrl}/v1/client/realtime/collections/${encodeURIComponent(this.name)}${qs}`,
|
|
218
|
+
url: `${resolveRealtimeBaseUrl(this.ctx.baseUrl)}/v1/client/realtime/collections/${encodeURIComponent(this.name)}${qs}`,
|
|
130
219
|
authHeaders: this.ctx.authHeaders,
|
|
131
220
|
onChange: cb,
|
|
132
221
|
options
|
|
@@ -247,13 +336,985 @@ var ConversationSubscription = class {
|
|
|
247
336
|
subscribe(cb, options = {}) {
|
|
248
337
|
if (!this.ctx.authHeaders()) throw new Error("Amba.messaging.conversation().subscribe() requires an authenticated session — call Amba.auth.signIn*/verify* first.");
|
|
249
338
|
return openStream({
|
|
250
|
-
url: `${this.ctx.baseUrl}/v1/client/realtime/conversations/${encodeURIComponent(this.conversationId)}`,
|
|
339
|
+
url: `${resolveRealtimeBaseUrl(this.ctx.baseUrl)}/v1/client/realtime/conversations/${encodeURIComponent(this.conversationId)}`,
|
|
340
|
+
authHeaders: this.ctx.authHeaders,
|
|
341
|
+
onChange: cb,
|
|
342
|
+
options
|
|
343
|
+
});
|
|
344
|
+
}
|
|
345
|
+
};
|
|
346
|
+
/**
|
|
347
|
+
* Builder returned by `Amba.gamification`. Call `.subscribe(cb)` to receive the
|
|
348
|
+
* signed-in user's xp / level / achievement / streak changes live instead of
|
|
349
|
+
* polling.
|
|
350
|
+
*
|
|
351
|
+
* const unsub = Amba.gamification.subscribe((change) => {
|
|
352
|
+
* // change.kind: "xp" | "level" | "achievement" | "streak"
|
|
353
|
+
* // change.data: the new state
|
|
354
|
+
* });
|
|
355
|
+
* unsub(); // stop listening
|
|
356
|
+
*
|
|
357
|
+
* Delivery is scoped to the signed-in user — you only ever receive your own
|
|
358
|
+
* gamification changes, never another user's. Reconnects with the same
|
|
359
|
+
* exponential backoff as collection subscriptions.
|
|
360
|
+
*/
|
|
361
|
+
var GamificationSubscription = class {
|
|
362
|
+
constructor(ctx) {
|
|
363
|
+
this.ctx = ctx;
|
|
364
|
+
}
|
|
365
|
+
subscribe(cb, options = {}) {
|
|
366
|
+
if (!this.ctx.authHeaders()) throw new Error("Amba.gamification.subscribe() requires an authenticated session — call Amba.auth.signIn*/verify* first.");
|
|
367
|
+
return openGamificationStream({
|
|
368
|
+
url: `${resolveRealtimeBaseUrl(this.ctx.baseUrl)}/v1/client/realtime/gamification`,
|
|
251
369
|
authHeaders: this.ctx.authHeaders,
|
|
252
370
|
onChange: cb,
|
|
253
371
|
options
|
|
254
372
|
});
|
|
255
373
|
}
|
|
256
374
|
};
|
|
375
|
+
/**
|
|
376
|
+
* Open a streamed GET to the gamification realtime endpoint. Identical
|
|
377
|
+
* transport + backoff/reconnect to {@link openStream}; only the frame payload
|
|
378
|
+
* shape differs (gamification carries `kind`, not `op`/`row`), so it gets its
|
|
379
|
+
* own thin consumer rather than overloading the row-change parser.
|
|
380
|
+
*/
|
|
381
|
+
function openGamificationStream(args) {
|
|
382
|
+
let stopped = false;
|
|
383
|
+
let controller = null;
|
|
384
|
+
let backoff = INITIAL_BACKOFF_MS;
|
|
385
|
+
const run = async () => {
|
|
386
|
+
while (!stopped) {
|
|
387
|
+
controller = new AbortController();
|
|
388
|
+
try {
|
|
389
|
+
const headers = args.authHeaders();
|
|
390
|
+
if (!headers) throw new Error("no active session");
|
|
391
|
+
const resp = await fetch(args.url, {
|
|
392
|
+
method: "GET",
|
|
393
|
+
headers: {
|
|
394
|
+
...headers,
|
|
395
|
+
Accept: "text/event-stream"
|
|
396
|
+
},
|
|
397
|
+
signal: controller.signal
|
|
398
|
+
});
|
|
399
|
+
if (!resp.ok || !resp.body) throw new Error(`realtime connect failed: HTTP ${resp.status}`);
|
|
400
|
+
await consumeGamification(resp.body, args, () => {
|
|
401
|
+
backoff = INITIAL_BACKOFF_MS;
|
|
402
|
+
args.options.onOpen?.();
|
|
403
|
+
});
|
|
404
|
+
} catch (err) {
|
|
405
|
+
if (stopped) break;
|
|
406
|
+
args.options.onError?.(err);
|
|
407
|
+
}
|
|
408
|
+
if (stopped) break;
|
|
409
|
+
await delay(backoff);
|
|
410
|
+
backoff = Math.min(backoff * 2, MAX_BACKOFF_MS);
|
|
411
|
+
}
|
|
412
|
+
};
|
|
413
|
+
run();
|
|
414
|
+
return () => {
|
|
415
|
+
stopped = true;
|
|
416
|
+
controller?.abort();
|
|
417
|
+
};
|
|
418
|
+
}
|
|
419
|
+
async function consumeGamification(body, args, onFirstFrame) {
|
|
420
|
+
const reader = body.getReader();
|
|
421
|
+
const decoder = new TextDecoder();
|
|
422
|
+
let buffer = "";
|
|
423
|
+
let sawFrame = false;
|
|
424
|
+
for (;;) {
|
|
425
|
+
const { done, value } = await reader.read();
|
|
426
|
+
if (done) return;
|
|
427
|
+
buffer += decoder.decode(value, { stream: true });
|
|
428
|
+
let idx;
|
|
429
|
+
while ((idx = buffer.indexOf("\n\n")) !== -1) {
|
|
430
|
+
const frame = buffer.slice(0, idx);
|
|
431
|
+
buffer = buffer.slice(idx + 2);
|
|
432
|
+
if (!sawFrame) {
|
|
433
|
+
sawFrame = true;
|
|
434
|
+
onFirstFrame();
|
|
435
|
+
}
|
|
436
|
+
dispatchGamificationFrame(frame, args.onChange);
|
|
437
|
+
}
|
|
438
|
+
}
|
|
439
|
+
}
|
|
440
|
+
function dispatchGamificationFrame(frame, onChange) {
|
|
441
|
+
let event = "";
|
|
442
|
+
const dataLines = [];
|
|
443
|
+
for (const line of frame.split("\n")) {
|
|
444
|
+
if (line.startsWith(":")) continue;
|
|
445
|
+
if (line.startsWith("event:")) event = line.slice(6).trim();
|
|
446
|
+
else if (line.startsWith("data:")) dataLines.push(line.slice(5).trim());
|
|
447
|
+
}
|
|
448
|
+
if (event !== "change") return;
|
|
449
|
+
try {
|
|
450
|
+
const payload = JSON.parse(dataLines.join("\n"));
|
|
451
|
+
onChange({
|
|
452
|
+
kind: payload.kind,
|
|
453
|
+
data: payload.data,
|
|
454
|
+
truncated: payload.truncated
|
|
455
|
+
});
|
|
456
|
+
} catch {}
|
|
457
|
+
}
|
|
458
|
+
|
|
459
|
+
//#endregion
|
|
460
|
+
//#region src/ai-stream.ts
|
|
461
|
+
function newUsageAccumulator() {
|
|
462
|
+
return {
|
|
463
|
+
input_tokens: 0,
|
|
464
|
+
output_tokens: 0,
|
|
465
|
+
cache_creation_input_tokens: 0,
|
|
466
|
+
cache_read_input_tokens: 0
|
|
467
|
+
};
|
|
468
|
+
}
|
|
469
|
+
function toAiUsage(acc) {
|
|
470
|
+
return {
|
|
471
|
+
input_tokens: acc.input_tokens,
|
|
472
|
+
output_tokens: acc.output_tokens,
|
|
473
|
+
cache_creation_input_tokens: acc.cache_creation_input_tokens,
|
|
474
|
+
cache_read_input_tokens: acc.cache_read_input_tokens
|
|
475
|
+
};
|
|
476
|
+
}
|
|
477
|
+
/** Read a numeric field defensively (vendors occasionally send null). */
|
|
478
|
+
function num(v) {
|
|
479
|
+
return typeof v === "number" && Number.isFinite(v) ? v : 0;
|
|
480
|
+
}
|
|
481
|
+
/**
|
|
482
|
+
* Merge a vendor `usage`-shaped object into the accumulator. Handles both
|
|
483
|
+
* Anthropic (`input_tokens` / `output_tokens` / `cache_*`) and OpenAI
|
|
484
|
+
* (`prompt_tokens` / `completion_tokens`) field names, taking the max so a
|
|
485
|
+
* later frame that re-reports a counter doesn't shrink it.
|
|
486
|
+
*/
|
|
487
|
+
function mergeUsage(acc, usage) {
|
|
488
|
+
const input = usage["input_tokens"] ?? usage["prompt_tokens"];
|
|
489
|
+
const output = usage["output_tokens"] ?? usage["completion_tokens"];
|
|
490
|
+
if (input !== void 0) acc.input_tokens = Math.max(acc.input_tokens, num(input));
|
|
491
|
+
if (output !== void 0) acc.output_tokens = Math.max(acc.output_tokens, num(output));
|
|
492
|
+
if (usage["cache_creation_input_tokens"] !== void 0) acc.cache_creation_input_tokens = Math.max(acc.cache_creation_input_tokens, num(usage["cache_creation_input_tokens"]));
|
|
493
|
+
if (usage["cache_read_input_tokens"] !== void 0) acc.cache_read_input_tokens = Math.max(acc.cache_read_input_tokens, num(usage["cache_read_input_tokens"]));
|
|
494
|
+
}
|
|
495
|
+
/**
|
|
496
|
+
* Parse one SSE frame (everything between blank lines) and return the text
|
|
497
|
+
* delta it carries, if any. Side-effect: folds any usage / model / stop
|
|
498
|
+
* metadata into `acc`. Returns `null` for keepalive comments, the `[DONE]`
|
|
499
|
+
* sentinel, and frames with no text (e.g. Anthropic's `message_start`).
|
|
500
|
+
*
|
|
501
|
+
* Tolerant by design — a malformed `data:` payload is skipped rather than
|
|
502
|
+
* tearing down the stream.
|
|
503
|
+
*/
|
|
504
|
+
function parseAiSseFrame(frame, acc) {
|
|
505
|
+
const dataLines = [];
|
|
506
|
+
for (const line of frame.split(/\r\n|\r|\n/)) {
|
|
507
|
+
if (line.startsWith(":")) continue;
|
|
508
|
+
if (line.startsWith("data:")) dataLines.push(line.slice(5).trimStart());
|
|
509
|
+
}
|
|
510
|
+
if (dataLines.length === 0) return null;
|
|
511
|
+
const data = dataLines.join("\n").trim();
|
|
512
|
+
if (data === "" || data === "[DONE]") return null;
|
|
513
|
+
let payload;
|
|
514
|
+
try {
|
|
515
|
+
payload = JSON.parse(data);
|
|
516
|
+
} catch {
|
|
517
|
+
return null;
|
|
518
|
+
}
|
|
519
|
+
const type = typeof payload["type"] === "string" ? payload["type"] : "";
|
|
520
|
+
if (type === "content_block_delta") {
|
|
521
|
+
const text = payload["delta"]?.["text"];
|
|
522
|
+
return typeof text === "string" ? text : null;
|
|
523
|
+
}
|
|
524
|
+
if (type === "message_start") {
|
|
525
|
+
const message = payload["message"];
|
|
526
|
+
const usage = message?.["usage"];
|
|
527
|
+
if (usage && typeof usage === "object") mergeUsage(acc, usage);
|
|
528
|
+
if (typeof message?.["model"] === "string") acc.model = message["model"];
|
|
529
|
+
return null;
|
|
530
|
+
}
|
|
531
|
+
if (type === "message_delta") {
|
|
532
|
+
const usage = payload["usage"];
|
|
533
|
+
if (usage && typeof usage === "object") mergeUsage(acc, usage);
|
|
534
|
+
const delta = payload["delta"];
|
|
535
|
+
if (typeof delta?.["stop_reason"] === "string") acc.stopReason = delta["stop_reason"];
|
|
536
|
+
return null;
|
|
537
|
+
}
|
|
538
|
+
if (type === "message_stop") return null;
|
|
539
|
+
if (Array.isArray(payload["choices"])) {
|
|
540
|
+
const choices = payload["choices"];
|
|
541
|
+
if (typeof payload["model"] === "string") acc.model = payload["model"];
|
|
542
|
+
const usage = payload["usage"];
|
|
543
|
+
if (usage && typeof usage === "object") mergeUsage(acc, usage);
|
|
544
|
+
const first = choices[0];
|
|
545
|
+
if (first) {
|
|
546
|
+
const finish = first["finish_reason"];
|
|
547
|
+
if (typeof finish === "string") acc.stopReason = finish;
|
|
548
|
+
const content = first["delta"]?.["content"];
|
|
549
|
+
if (typeof content === "string" && content.length > 0) return content;
|
|
550
|
+
}
|
|
551
|
+
return null;
|
|
552
|
+
}
|
|
553
|
+
return null;
|
|
554
|
+
}
|
|
555
|
+
/**
|
|
556
|
+
* SSE event-frame delimiter: a blank line. The spec permits any line ending
|
|
557
|
+
* (`\r\n`, `\n`, `\r`), so a blank line is two consecutive line breaks in any
|
|
558
|
+
* combination — `\r\n\r\n`, `\n\n`, or `\r\r`. Some servers / proxies emit
|
|
559
|
+
* CRLF, so splitting on `\n\n` alone would never frame those streams.
|
|
560
|
+
*/
|
|
561
|
+
const SSE_FRAME_DELIMITER = /\r\n\r\n|\n\n|\r\r/;
|
|
562
|
+
/**
|
|
563
|
+
* Pull the next complete SSE frame off the front of `buffer`, returning the
|
|
564
|
+
* frame text (without the trailing blank-line delimiter) and the remaining
|
|
565
|
+
* buffer, or `null` when no complete frame is present yet.
|
|
566
|
+
*
|
|
567
|
+
* Only *complete* delimiters match: a buffer ending mid-delimiter (e.g.
|
|
568
|
+
* `…\r\n\r`, awaiting the final `\n`) leaves the partial bytes buffered for the
|
|
569
|
+
* next read rather than framing prematurely.
|
|
570
|
+
*/
|
|
571
|
+
function splitNextSseFrame(buffer) {
|
|
572
|
+
const m = SSE_FRAME_DELIMITER.exec(buffer);
|
|
573
|
+
if (!m) return null;
|
|
574
|
+
return {
|
|
575
|
+
frame: buffer.slice(0, m.index),
|
|
576
|
+
rest: buffer.slice(m.index + m[0].length)
|
|
577
|
+
};
|
|
578
|
+
}
|
|
579
|
+
/**
|
|
580
|
+
* Open the streaming route and yield vendor-neutral events. Throws an
|
|
581
|
+
* `AmbaApiError` on a transport failure or a non-2xx response (the error body
|
|
582
|
+
* is read and surfaced just like the buffered path).
|
|
583
|
+
*
|
|
584
|
+
* The generator yields zero or more `{type:'delta'}` events followed by
|
|
585
|
+
* exactly one terminal `{type:'done'}` when the stream completes cleanly.
|
|
586
|
+
*/
|
|
587
|
+
async function* invokeAiStream(args) {
|
|
588
|
+
let resp;
|
|
589
|
+
try {
|
|
590
|
+
resp = await fetch(args.url, {
|
|
591
|
+
method: "POST",
|
|
592
|
+
headers: args.headers,
|
|
593
|
+
body: args.body
|
|
594
|
+
});
|
|
595
|
+
} catch (err) {
|
|
596
|
+
throw new AmbaApiError("NETWORK_ERROR", `AI stream network error: ${String(err)}`);
|
|
597
|
+
}
|
|
598
|
+
if (!resp.ok) {
|
|
599
|
+
const text = await resp.text().catch(() => "");
|
|
600
|
+
let parsed = void 0;
|
|
601
|
+
if (text.length > 0) try {
|
|
602
|
+
parsed = JSON.parse(text);
|
|
603
|
+
} catch {
|
|
604
|
+
parsed = text;
|
|
605
|
+
}
|
|
606
|
+
const envelope = parsed && typeof parsed === "object" ? parsed : void 0;
|
|
607
|
+
throw new AmbaApiError(typeof envelope?.error?.code === "string" ? envelope.error.code : `HTTP_${resp.status}`, typeof envelope?.error?.message === "string" ? envelope.error.message : typeof parsed === "string" && parsed.length > 0 ? parsed : `AI stream failed with status ${resp.status}`, parsed);
|
|
608
|
+
}
|
|
609
|
+
if (!resp.body) throw new AmbaApiError("NETWORK_ERROR", "AI stream response had no readable body (the environment does not expose a streaming fetch body).");
|
|
610
|
+
const reader = resp.body.getReader();
|
|
611
|
+
const decoder = new TextDecoder();
|
|
612
|
+
const acc = newUsageAccumulator();
|
|
613
|
+
let buffer = "";
|
|
614
|
+
try {
|
|
615
|
+
for (;;) {
|
|
616
|
+
const { done, value } = await reader.read();
|
|
617
|
+
if (value) buffer += decoder.decode(value, { stream: true });
|
|
618
|
+
if (done) buffer += decoder.decode();
|
|
619
|
+
let split;
|
|
620
|
+
while ((split = splitNextSseFrame(buffer)) !== null) {
|
|
621
|
+
buffer = split.rest;
|
|
622
|
+
const text = parseAiSseFrame(split.frame, acc);
|
|
623
|
+
if (text !== null && text.length > 0) {
|
|
624
|
+
args.onChunk?.(text);
|
|
625
|
+
yield {
|
|
626
|
+
type: "delta",
|
|
627
|
+
text
|
|
628
|
+
};
|
|
629
|
+
}
|
|
630
|
+
}
|
|
631
|
+
if (done) {
|
|
632
|
+
const tail = buffer.trim();
|
|
633
|
+
if (tail.length > 0) {
|
|
634
|
+
const text = parseAiSseFrame(tail, acc);
|
|
635
|
+
if (text !== null && text.length > 0) {
|
|
636
|
+
args.onChunk?.(text);
|
|
637
|
+
yield {
|
|
638
|
+
type: "delta",
|
|
639
|
+
text
|
|
640
|
+
};
|
|
641
|
+
}
|
|
642
|
+
}
|
|
643
|
+
break;
|
|
644
|
+
}
|
|
645
|
+
}
|
|
646
|
+
} finally {
|
|
647
|
+
try {
|
|
648
|
+
reader.releaseLock();
|
|
649
|
+
} catch {}
|
|
650
|
+
}
|
|
651
|
+
yield {
|
|
652
|
+
type: "done",
|
|
653
|
+
usage: toAiUsage(acc),
|
|
654
|
+
model: acc.model,
|
|
655
|
+
stopReason: acc.stopReason ?? null
|
|
656
|
+
};
|
|
657
|
+
}
|
|
658
|
+
|
|
659
|
+
//#endregion
|
|
660
|
+
//#region src/resilience.ts
|
|
661
|
+
/**
|
|
662
|
+
* Best-effort online probe. In a browser/RN runtime `navigator.onLine`
|
|
663
|
+
* exists; under Node / SSR it doesn't, so we treat "unknown" as online
|
|
664
|
+
* (the executor's own error handling then decides).
|
|
665
|
+
*/
|
|
666
|
+
function isOnline() {
|
|
667
|
+
const nav = typeof navigator !== "undefined" ? navigator : void 0;
|
|
668
|
+
if (nav && typeof nav.onLine === "boolean") return nav.onLine;
|
|
669
|
+
return true;
|
|
670
|
+
}
|
|
671
|
+
/**
|
|
672
|
+
* Error codes the server raised deterministically — replaying them would fail
|
|
673
|
+
* identically, so they're NEVER queued even when the device reports offline.
|
|
674
|
+
* (A request can fail validation/auth/etc. while `navigator.onLine` is briefly
|
|
675
|
+
* false; we must not buffer-and-retry those forever.)
|
|
676
|
+
*/
|
|
677
|
+
const DETERMINISTIC_ERROR_CODES = new Set([
|
|
678
|
+
"VALIDATION_ERROR",
|
|
679
|
+
"INVALID_ARGUMENT",
|
|
680
|
+
"INVALID_INPUT",
|
|
681
|
+
"UNAUTHORIZED",
|
|
682
|
+
"FORBIDDEN",
|
|
683
|
+
"NOT_FOUND",
|
|
684
|
+
"CONFLICT",
|
|
685
|
+
"CONSENT_NOT_GRANTED",
|
|
686
|
+
"NOT_INITIALIZED"
|
|
687
|
+
]);
|
|
688
|
+
/**
|
|
689
|
+
* Is this a deterministic server rejection — a coded error the server would
|
|
690
|
+
* raise identically on every replay (bad input, auth, not-found, conflict)? A
|
|
691
|
+
* queued op that fails this way is poison: retrying it forever would wedge the
|
|
692
|
+
* queue, so the flush DROPS it. Everything else (transport failures, 5xx
|
|
693
|
+
* `HTTP_ERROR`, `RATE_LIMITED`, `CIRCUIT_OPEN`, anything uncoded) is treated as
|
|
694
|
+
* transient and RETAINED for a later attempt — favoring retain over data loss.
|
|
695
|
+
*/
|
|
696
|
+
function isDeterministicError(err) {
|
|
697
|
+
const code = err?.code;
|
|
698
|
+
return typeof code === "string" && DETERMINISTIC_ERROR_CODES.has(code);
|
|
699
|
+
}
|
|
700
|
+
/**
|
|
701
|
+
* Heuristic: does a thrown value look like a transient offline / transport
|
|
702
|
+
* failure (vs a deterministic 4xx the server would reject again)? Used at
|
|
703
|
+
* ENQUEUE time to decide whether a failed write is worth buffering — a
|
|
704
|
+
* `VALIDATION_ERROR` will fail identically on replay, so it throws instead.
|
|
705
|
+
*
|
|
706
|
+
* A deterministic server error is excluded even when the device reports
|
|
707
|
+
* offline: the request clearly reached the server (it got a coded response),
|
|
708
|
+
* so retrying it on reconnect is pointless and would wedge the queue.
|
|
709
|
+
*
|
|
710
|
+
* NOTE: this is intentionally stricter than {@link isDeterministicError}'s
|
|
711
|
+
* inverse — at enqueue time we only buffer GENUINE connectivity failures (a
|
|
712
|
+
* non-offline 5xx/429 surfaces to the caller immediately rather than silently
|
|
713
|
+
* queueing). The flush drop-decision uses {@link isDeterministicError} so a
|
|
714
|
+
* transient 5xx/429 encountered DURING replay is retained, not dropped.
|
|
715
|
+
*/
|
|
716
|
+
function isOfflineError(err) {
|
|
717
|
+
const code = err?.code;
|
|
718
|
+
if (typeof code === "string" && DETERMINISTIC_ERROR_CODES.has(code)) return false;
|
|
719
|
+
if (code === "NETWORK_ERROR") return true;
|
|
720
|
+
const msg = err?.message;
|
|
721
|
+
if (typeof msg === "string" && /network (error|request failed)|failed to fetch|fetch failed|load failed/i.test(msg)) return true;
|
|
722
|
+
return !isOnline();
|
|
723
|
+
}
|
|
724
|
+
/** Generate a stable idempotency key for a queued op. */
|
|
725
|
+
function newIdempotencyKey() {
|
|
726
|
+
const c = typeof globalThis !== "undefined" ? globalThis.crypto : void 0;
|
|
727
|
+
if (c && typeof c.randomUUID === "function") return `amba_obx_${c.randomUUID()}`;
|
|
728
|
+
return `amba_obx_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 12)}`;
|
|
729
|
+
}
|
|
730
|
+
/**
|
|
731
|
+
* Durable, ordered, idempotent offline outbox. Opt-in via `Amba.offline`.
|
|
732
|
+
* Single in-flight flush is enforced so concurrent reconnect signals don't
|
|
733
|
+
* double-replay.
|
|
734
|
+
*/
|
|
735
|
+
var OfflineQueue = class {
|
|
736
|
+
store;
|
|
737
|
+
executor;
|
|
738
|
+
storageKey;
|
|
739
|
+
/**
|
|
740
|
+
* Notified when a queued op is dropped because its replay failed
|
|
741
|
+
* deterministically (a poisoned op the server will always reject). Lets the
|
|
742
|
+
* SDK surface the loss (debug log) instead of silently discarding.
|
|
743
|
+
*/
|
|
744
|
+
onDropped;
|
|
745
|
+
flushing = null;
|
|
746
|
+
/**
|
|
747
|
+
* Serializes every read-modify-write of the persisted outbox. Each mutation
|
|
748
|
+
* chains onto the previous one's promise, so concurrent `enqueue`s — and an
|
|
749
|
+
* `enqueue` racing the per-op removal inside `flush` — can never read a stale
|
|
750
|
+
* snapshot and clobber each other's writes (the lost-update bug). All
|
|
751
|
+
* storage mutations funnel through `mutate()`; only `pendingCount`/`pending`
|
|
752
|
+
* read without taking the lock (a stale-by-one read is harmless).
|
|
753
|
+
*/
|
|
754
|
+
tail = Promise.resolve();
|
|
755
|
+
/** Detach function for the auto-flush `online` listener, if installed. */
|
|
756
|
+
detachOnline = null;
|
|
757
|
+
/**
|
|
758
|
+
* Set once `dispose()` is called (on teardown / reconfigure). A disposed
|
|
759
|
+
* queue refuses to mutate the persisted outbox, so an orphaned in-flight
|
|
760
|
+
* flush — or any late call against the old instance — can never race the new
|
|
761
|
+
* queue by reading/writing the same storage after it's been replaced.
|
|
762
|
+
*/
|
|
763
|
+
disposed = false;
|
|
764
|
+
constructor(opts) {
|
|
765
|
+
this.store = opts.store;
|
|
766
|
+
this.executor = opts.executor;
|
|
767
|
+
this.storageKey = opts.storageKey ?? "offline_outbox";
|
|
768
|
+
this.onDropped = opts.onDropped;
|
|
769
|
+
}
|
|
770
|
+
/**
|
|
771
|
+
* Run `fn` exclusively against the persisted outbox: it chains after every
|
|
772
|
+
* prior mutation and the next one waits for it. `fn` receives the current
|
|
773
|
+
* ops and returns the next ops to persist plus its own result.
|
|
774
|
+
*/
|
|
775
|
+
mutate(fn, opts) {
|
|
776
|
+
const run = this.tail.then(async () => {
|
|
777
|
+
if (this.disposed && opts?.rejectIfDisposed) throw new Error("amba offline queue was disposed (SDK reconfigured)");
|
|
778
|
+
const { next, result } = await fn(await this.load());
|
|
779
|
+
await this.save(next);
|
|
780
|
+
return result;
|
|
781
|
+
});
|
|
782
|
+
this.tail = run.catch(() => void 0);
|
|
783
|
+
return run;
|
|
784
|
+
}
|
|
785
|
+
async load() {
|
|
786
|
+
const raw = await this.store.get(this.storageKey);
|
|
787
|
+
if (!raw) return [];
|
|
788
|
+
try {
|
|
789
|
+
const parsed = JSON.parse(raw);
|
|
790
|
+
return Array.isArray(parsed) ? parsed : [];
|
|
791
|
+
} catch {
|
|
792
|
+
return [];
|
|
793
|
+
}
|
|
794
|
+
}
|
|
795
|
+
async save(ops) {
|
|
796
|
+
if (this.disposed) return;
|
|
797
|
+
if (ops.length === 0) {
|
|
798
|
+
await this.store.delete(this.storageKey);
|
|
799
|
+
return;
|
|
800
|
+
}
|
|
801
|
+
await this.store.set(this.storageKey, JSON.stringify(ops));
|
|
802
|
+
}
|
|
803
|
+
/**
|
|
804
|
+
* Permanently retire this queue. Detaches the auto-flush listener and marks
|
|
805
|
+
* it disposed so it can no longer mutate the persisted outbox. Returns once
|
|
806
|
+
* any in-flight flush + pending mutation chain has settled, so a caller (e.g.
|
|
807
|
+
* `configure()` teardown) can safely create a replacement queue knowing the
|
|
808
|
+
* old one will never touch storage again. Idempotent.
|
|
809
|
+
*/
|
|
810
|
+
async dispose() {
|
|
811
|
+
this.disposed = true;
|
|
812
|
+
if (this.detachOnline) {
|
|
813
|
+
this.detachOnline();
|
|
814
|
+
this.detachOnline = null;
|
|
815
|
+
}
|
|
816
|
+
try {
|
|
817
|
+
await this.flushing;
|
|
818
|
+
} catch {}
|
|
819
|
+
await this.tail.catch(() => void 0);
|
|
820
|
+
}
|
|
821
|
+
/** Whether this queue has been disposed. */
|
|
822
|
+
get isDisposed() {
|
|
823
|
+
return this.disposed;
|
|
824
|
+
}
|
|
825
|
+
/** Append an op to the durable outbox. Returns the persisted op. */
|
|
826
|
+
async enqueue(op) {
|
|
827
|
+
if (this.disposed) throw new Error("amba offline queue was disposed (SDK reconfigured)");
|
|
828
|
+
const full = {
|
|
829
|
+
...op,
|
|
830
|
+
idempotencyKey: op.idempotencyKey ?? newIdempotencyKey(),
|
|
831
|
+
enqueuedAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
832
|
+
};
|
|
833
|
+
return this.mutate((ops) => ({
|
|
834
|
+
next: [...ops, full],
|
|
835
|
+
result: full
|
|
836
|
+
}), { rejectIfDisposed: true });
|
|
837
|
+
}
|
|
838
|
+
/** Number of ops awaiting replay. */
|
|
839
|
+
async pendingCount() {
|
|
840
|
+
return (await this.load()).length;
|
|
841
|
+
}
|
|
842
|
+
/** Snapshot the pending ops (a copy — mutating it does not affect the queue). */
|
|
843
|
+
async pending() {
|
|
844
|
+
return [...await this.load()];
|
|
845
|
+
}
|
|
846
|
+
/** Drop every queued op without replaying. */
|
|
847
|
+
async clear() {
|
|
848
|
+
await this.mutate(() => ({
|
|
849
|
+
next: [],
|
|
850
|
+
result: void 0
|
|
851
|
+
}));
|
|
852
|
+
}
|
|
853
|
+
/**
|
|
854
|
+
* Replay the outbox in FIFO order. Each op is removed only after it
|
|
855
|
+
* succeeds; the first failure stops the flush and retains the remainder
|
|
856
|
+
* (so order is preserved and nothing is dropped mid-batch). Concurrent
|
|
857
|
+
* calls share one in-flight flush.
|
|
858
|
+
*/
|
|
859
|
+
async flush() {
|
|
860
|
+
if (this.disposed) return {
|
|
861
|
+
flushed: 0,
|
|
862
|
+
dropped: 0,
|
|
863
|
+
remaining: 0
|
|
864
|
+
};
|
|
865
|
+
if (this.flushing) return this.flushing;
|
|
866
|
+
this.flushing = this.runFlush().finally(() => {
|
|
867
|
+
this.flushing = null;
|
|
868
|
+
});
|
|
869
|
+
return this.flushing;
|
|
870
|
+
}
|
|
871
|
+
async runFlush() {
|
|
872
|
+
let flushed = 0;
|
|
873
|
+
let dropped = 0;
|
|
874
|
+
for (;;) {
|
|
875
|
+
if (this.disposed) break;
|
|
876
|
+
const head = (await this.load())[0];
|
|
877
|
+
if (!head) break;
|
|
878
|
+
let replayError = void 0;
|
|
879
|
+
let ok = false;
|
|
880
|
+
try {
|
|
881
|
+
await this.executor(head);
|
|
882
|
+
ok = true;
|
|
883
|
+
} catch (err) {
|
|
884
|
+
replayError = err;
|
|
885
|
+
}
|
|
886
|
+
if (!ok && !isDeterministicError(replayError)) {
|
|
887
|
+
await this.mutate((ops) => {
|
|
888
|
+
return {
|
|
889
|
+
next: ops.some((o) => o.idempotencyKey === head.idempotencyKey) ? ops : [head, ...ops],
|
|
890
|
+
result: void 0
|
|
891
|
+
};
|
|
892
|
+
});
|
|
893
|
+
break;
|
|
894
|
+
}
|
|
895
|
+
if (!await this.mutate((ops) => {
|
|
896
|
+
const idx = ops.findIndex((o) => o.idempotencyKey === head.idempotencyKey);
|
|
897
|
+
if (idx === -1) return {
|
|
898
|
+
next: ops,
|
|
899
|
+
result: false
|
|
900
|
+
};
|
|
901
|
+
return {
|
|
902
|
+
next: ops.slice(0, idx).concat(ops.slice(idx + 1)),
|
|
903
|
+
result: true
|
|
904
|
+
};
|
|
905
|
+
})) break;
|
|
906
|
+
if (ok) flushed += 1;
|
|
907
|
+
else {
|
|
908
|
+
dropped += 1;
|
|
909
|
+
try {
|
|
910
|
+
this.onDropped?.(head, replayError);
|
|
911
|
+
} catch {}
|
|
912
|
+
}
|
|
913
|
+
}
|
|
914
|
+
const remaining = (await this.load()).length;
|
|
915
|
+
return {
|
|
916
|
+
flushed,
|
|
917
|
+
dropped,
|
|
918
|
+
remaining
|
|
919
|
+
};
|
|
920
|
+
}
|
|
921
|
+
/**
|
|
922
|
+
* Install an auto-flush listener on the runtime's `online` event so the
|
|
923
|
+
* queue drains the moment connectivity returns. Idempotent — a second
|
|
924
|
+
* call is a no-op. Returns a detach function.
|
|
925
|
+
*/
|
|
926
|
+
startAutoFlush() {
|
|
927
|
+
if (this.detachOnline) return this.detachOnline;
|
|
928
|
+
const target = typeof globalThis !== "undefined" && typeof globalThis.addEventListener === "function" ? globalThis : null;
|
|
929
|
+
if (!target) {
|
|
930
|
+
this.detachOnline = () => {};
|
|
931
|
+
return this.detachOnline;
|
|
932
|
+
}
|
|
933
|
+
const handler = () => {
|
|
934
|
+
this.flush();
|
|
935
|
+
};
|
|
936
|
+
target.addEventListener("online", handler);
|
|
937
|
+
this.detachOnline = () => {
|
|
938
|
+
target.removeEventListener("online", handler);
|
|
939
|
+
this.detachOnline = null;
|
|
940
|
+
};
|
|
941
|
+
return this.detachOnline;
|
|
942
|
+
}
|
|
943
|
+
};
|
|
944
|
+
/**
|
|
945
|
+
* Apply a local change immediately, fire the real mutation, and roll the
|
|
946
|
+
* local change back if the mutation fails. Framework-agnostic: `apply` and
|
|
947
|
+
* `rollback` operate on whatever local view you hand them (a React state
|
|
948
|
+
* setter, a store, an in-memory cache).
|
|
949
|
+
*
|
|
950
|
+
* Resolves with the mutation's result on success. On failure it invokes
|
|
951
|
+
* `rollback` (with the value `apply` returned, so you can restore a captured
|
|
952
|
+
* snapshot) and rethrows the original error.
|
|
953
|
+
*
|
|
954
|
+
* @example
|
|
955
|
+
* await withOptimistic({
|
|
956
|
+
* apply: () => { const prev = todos; setTodos([...todos, draft]); return prev; },
|
|
957
|
+
* mutate: () => Amba.collections.insert("todos", draft),
|
|
958
|
+
* rollback: (prev) => setTodos(prev),
|
|
959
|
+
* });
|
|
960
|
+
*/
|
|
961
|
+
async function withOptimistic(spec) {
|
|
962
|
+
const applied = spec.apply();
|
|
963
|
+
try {
|
|
964
|
+
return await spec.mutate();
|
|
965
|
+
} catch (err) {
|
|
966
|
+
try {
|
|
967
|
+
spec.rollback(applied);
|
|
968
|
+
} catch {}
|
|
969
|
+
throw err;
|
|
970
|
+
}
|
|
971
|
+
}
|
|
972
|
+
|
|
973
|
+
//#endregion
|
|
974
|
+
//#region src/push-rotation.ts
|
|
975
|
+
/**
|
|
976
|
+
* Subscribe to browser push-subscription rotation. On a
|
|
977
|
+
* `pushsubscriptionchange`, the new subscription endpoint is forwarded to
|
|
978
|
+
* `reRegister` (which the SDK points at its idempotent token-upsert).
|
|
979
|
+
*
|
|
980
|
+
* Returns an unsubscribe function. No-ops (returning a no-op detacher) when
|
|
981
|
+
* the runtime has no service-worker / push support — e.g. SSR or a browser
|
|
982
|
+
* without Web Push — so callers can invoke it unconditionally.
|
|
983
|
+
*/
|
|
984
|
+
/**
|
|
985
|
+
* Are we executing inside a ServiceWorkerGlobalScope? `pushsubscriptionchange`
|
|
986
|
+
* ONLY fires there — on a normal page `self === window`, where the event never
|
|
987
|
+
* fires, so attaching a listener silently does nothing. We detect the scope by
|
|
988
|
+
* the `ServiceWorkerGlobalScope` constructor when present, falling back to the
|
|
989
|
+
* SW-only `self.registration.pushManager` shape (a window has no `registration`
|
|
990
|
+
* on its global).
|
|
991
|
+
*/
|
|
992
|
+
function inServiceWorkerScope(g) {
|
|
993
|
+
if (typeof g !== "object" || g === null) return false;
|
|
994
|
+
const swCtor = globalThis.ServiceWorkerGlobalScope;
|
|
995
|
+
if (typeof swCtor === "function" && g instanceof swCtor) return true;
|
|
996
|
+
const reg = g.registration;
|
|
997
|
+
return !!reg && typeof reg.pushManager === "object" && reg.pushManager !== null;
|
|
998
|
+
}
|
|
999
|
+
let pageScopeWarned = false;
|
|
1000
|
+
function enableWebPushAutoRotation(reRegister) {
|
|
1001
|
+
const g = typeof self !== "undefined" ? self : void 0;
|
|
1002
|
+
if (!g || !inServiceWorkerScope(g)) {
|
|
1003
|
+
if (!pageScopeWarned && typeof console !== "undefined") {
|
|
1004
|
+
pageScopeWarned = true;
|
|
1005
|
+
console.warn("[amba] push.enableAutoRotation() must run inside your service worker — `pushsubscriptionchange` doesn't fire on a page/window. Call it from your amba service worker. No-op here.");
|
|
1006
|
+
}
|
|
1007
|
+
return () => {};
|
|
1008
|
+
}
|
|
1009
|
+
const sw = g;
|
|
1010
|
+
if (typeof sw.addEventListener !== "function") return () => {};
|
|
1011
|
+
const onChange = (event) => {
|
|
1012
|
+
(async () => {
|
|
1013
|
+
try {
|
|
1014
|
+
const ev = event;
|
|
1015
|
+
let endpoint = ev?.newSubscription?.endpoint;
|
|
1016
|
+
if (!endpoint && sw.registration?.pushManager?.getSubscription) endpoint = (await sw.registration.pushManager.getSubscription())?.endpoint ?? void 0;
|
|
1017
|
+
if (!endpoint) return;
|
|
1018
|
+
const work = reRegister(endpoint, "web");
|
|
1019
|
+
if (typeof ev?.waitUntil === "function") ev.waitUntil(work);
|
|
1020
|
+
await work;
|
|
1021
|
+
} catch (err) {
|
|
1022
|
+
if (typeof console !== "undefined") console.error("[amba] push auto-rotation re-register failed", err);
|
|
1023
|
+
}
|
|
1024
|
+
})();
|
|
1025
|
+
};
|
|
1026
|
+
sw.addEventListener("pushsubscriptionchange", onChange);
|
|
1027
|
+
return () => {
|
|
1028
|
+
sw.removeEventListener?.("pushsubscriptionchange", onChange);
|
|
1029
|
+
};
|
|
1030
|
+
}
|
|
1031
|
+
|
|
1032
|
+
//#endregion
|
|
1033
|
+
//#region src/local-notifications.ts
|
|
1034
|
+
/**
|
|
1035
|
+
* Browsers store a `setTimeout` delay in a signed 32-bit int. A delay
|
|
1036
|
+
* larger than `2^31 - 1` ms (~24.8 days) overflows and is clamped — most
|
|
1037
|
+
* browsers fire (often immediately) rather than wait. So a far-future
|
|
1038
|
+
* local notification scheduled via the in-page timer fallback would fire
|
|
1039
|
+
* at the wrong time. We chunk long delays: arm a timer for at most
|
|
1040
|
+
* `MAX_TIMEOUT_MS`, and on wake re-arm for the remainder until due.
|
|
1041
|
+
*/
|
|
1042
|
+
const MAX_TIMEOUT_MS = 2147483647;
|
|
1043
|
+
const pendingTimers = /* @__PURE__ */ new Map();
|
|
1044
|
+
function hasNotificationApi() {
|
|
1045
|
+
return typeof globalThis !== "undefined" && typeof globalThis.Notification === "function";
|
|
1046
|
+
}
|
|
1047
|
+
function timestampTriggerCtor() {
|
|
1048
|
+
const ctor = globalThis.TimestampTrigger;
|
|
1049
|
+
return typeof ctor === "function" ? ctor : void 0;
|
|
1050
|
+
}
|
|
1051
|
+
function genId() {
|
|
1052
|
+
const c = globalThis.crypto;
|
|
1053
|
+
if (c?.randomUUID) return c.randomUUID();
|
|
1054
|
+
return `amba_local_${Date.now()}_${Math.random().toString(36).slice(2)}`;
|
|
1055
|
+
}
|
|
1056
|
+
/**
|
|
1057
|
+
* Per-INSTANCE token. The stable `__ambaLocalId` survives a reschedule of the
|
|
1058
|
+
* same id; this token does not — every individual `scheduleLocal` call mints a
|
|
1059
|
+
* fresh one. It lets `listScheduledLocal` distinguish a NEW pending schedule
|
|
1060
|
+
* for an id from an OLD already-fired-but-still-visible notification of the
|
|
1061
|
+
* SAME id (which the Service Worker reports under `getNotifications()`),
|
|
1062
|
+
* instead of conflating the two by id and hiding the pending one. (Round-5.)
|
|
1063
|
+
*/
|
|
1064
|
+
function genInstanceToken() {
|
|
1065
|
+
return `${Date.now()}_${Math.random().toString(36).slice(2)}`;
|
|
1066
|
+
}
|
|
1067
|
+
/**
|
|
1068
|
+
* Resolve the id a schedule will be filed under. A caller may omit `id`
|
|
1069
|
+
* (we mint one) but must not pass a BLANK/whitespace id: `cancelLocal`
|
|
1070
|
+
* rejects blank ids, so returning one in the handle would make the
|
|
1071
|
+
* notification uncancellable. We reject blank at schedule time so every
|
|
1072
|
+
* returned handle id round-trips through `cancelLocal`. Shared by both
|
|
1073
|
+
* SDK platforms (web + react-native) for identical validation.
|
|
1074
|
+
*/
|
|
1075
|
+
function normalizeScheduleId(rawId) {
|
|
1076
|
+
if (rawId === void 0) return genId();
|
|
1077
|
+
if (typeof rawId !== "string" || rawId.trim() === "") throw new AmbaApiError("INVALID_ARGUMENT", "Amba.notifications.scheduleLocal: id, when provided, must be a non-empty string");
|
|
1078
|
+
return rawId;
|
|
1079
|
+
}
|
|
1080
|
+
function parseTrigger(input) {
|
|
1081
|
+
const trigger = input.trigger;
|
|
1082
|
+
if (!trigger || typeof trigger !== "object") throw new AmbaApiError("INVALID_ARGUMENT", "Amba.notifications.scheduleLocal: trigger must be { at: Date } or { inSeconds: number }");
|
|
1083
|
+
if ("at" in trigger) {
|
|
1084
|
+
const ms = (trigger.at instanceof Date ? trigger.at : new Date(trigger.at)).getTime();
|
|
1085
|
+
if (Number.isNaN(ms)) throw new AmbaApiError("INVALID_ARGUMENT", "Amba.notifications.scheduleLocal: trigger.at must be a valid Date");
|
|
1086
|
+
return {
|
|
1087
|
+
kind: "absolute",
|
|
1088
|
+
at: ms
|
|
1089
|
+
};
|
|
1090
|
+
}
|
|
1091
|
+
if ("inSeconds" in trigger) {
|
|
1092
|
+
if (!Number.isFinite(trigger.inSeconds) || trigger.inSeconds < 0) throw new AmbaApiError("INVALID_ARGUMENT", "Amba.notifications.scheduleLocal: trigger.inSeconds must be a non-negative number");
|
|
1093
|
+
return {
|
|
1094
|
+
kind: "relative",
|
|
1095
|
+
seconds: trigger.inSeconds
|
|
1096
|
+
};
|
|
1097
|
+
}
|
|
1098
|
+
throw new AmbaApiError("INVALID_ARGUMENT", "Amba.notifications.scheduleLocal: trigger must be { at: Date } or { inSeconds: number }");
|
|
1099
|
+
}
|
|
1100
|
+
/**
|
|
1101
|
+
* Resolve a parsed trigger to an absolute fire time (ms epoch). For a
|
|
1102
|
+
* relative trigger this is `now + seconds` — call it ONLY after permission
|
|
1103
|
+
* has resolved so `inSeconds` counts from when scheduling actually completes.
|
|
1104
|
+
*/
|
|
1105
|
+
function computeFireAt(parsed) {
|
|
1106
|
+
return parsed.kind === "absolute" ? parsed.at : Date.now() + parsed.seconds * 1e3;
|
|
1107
|
+
}
|
|
1108
|
+
function validateContent(input) {
|
|
1109
|
+
if (!input || typeof input.title !== "string" || input.title.trim() === "") throw new AmbaApiError("INVALID_ARGUMENT", "Amba.notifications.scheduleLocal: title is required");
|
|
1110
|
+
if (typeof input.body !== "string") throw new AmbaApiError("INVALID_ARGUMENT", "Amba.notifications.scheduleLocal: body must be a string");
|
|
1111
|
+
}
|
|
1112
|
+
async function ensurePermission() {
|
|
1113
|
+
const N = globalThis.Notification;
|
|
1114
|
+
let permission = N.permission;
|
|
1115
|
+
if (permission === "default") permission = await N.requestPermission();
|
|
1116
|
+
if (permission !== "granted") throw new AmbaApiError("LOCAL_NOTIFICATIONS_PERMISSION_DENIED", "user denied notification permission — local notifications cannot be shown");
|
|
1117
|
+
}
|
|
1118
|
+
/**
|
|
1119
|
+
* How long we'll wait for an existing-but-not-yet-active registration to
|
|
1120
|
+
* become `ready` before falling through to the in-page timer path. A real
|
|
1121
|
+
* activation is near-instant; this cap only guards against a wedged
|
|
1122
|
+
* activation hanging the call.
|
|
1123
|
+
*/
|
|
1124
|
+
const SW_READY_TIMEOUT_MS = 1e3;
|
|
1125
|
+
/**
|
|
1126
|
+
* Resolve the Service Worker registration to use for OS-trigger
|
|
1127
|
+
* notifications — WITHOUT ever hanging.
|
|
1128
|
+
*
|
|
1129
|
+
* The footgun this avoids: `navigator.serviceWorker.ready` NEVER resolves
|
|
1130
|
+
* when no service worker is registered (the common case for a page that has
|
|
1131
|
+
* the Notifications API but no SW). Awaiting it unconditionally would hang
|
|
1132
|
+
* `scheduleLocal` / `cancelLocal` / `listScheduledLocal` forever instead of
|
|
1133
|
+
* falling back to the documented in-page timer path. (Round-6 HIGH.)
|
|
1134
|
+
*
|
|
1135
|
+
* Instead we first call `getRegistration()`, which resolves to `undefined`
|
|
1136
|
+
* when nothing is registered (no hang). Only if a registration exists do we
|
|
1137
|
+
* wait — briefly, raced against a timeout — for `.ready`, so an active SW is
|
|
1138
|
+
* used while a wedged activation can't stall the caller.
|
|
1139
|
+
*/
|
|
1140
|
+
async function getServiceWorkerRegistration() {
|
|
1141
|
+
const nav = globalThis.navigator;
|
|
1142
|
+
if (!nav || !("serviceWorker" in nav)) return void 0;
|
|
1143
|
+
const swc = nav.serviceWorker;
|
|
1144
|
+
let existing;
|
|
1145
|
+
try {
|
|
1146
|
+
existing = await swc.getRegistration();
|
|
1147
|
+
} catch {
|
|
1148
|
+
return;
|
|
1149
|
+
}
|
|
1150
|
+
if (!existing) return void 0;
|
|
1151
|
+
try {
|
|
1152
|
+
return await Promise.race([swc.ready, new Promise((resolve) => setTimeout(() => resolve(void 0), SW_READY_TIMEOUT_MS))]) ?? existing;
|
|
1153
|
+
} catch {
|
|
1154
|
+
return existing;
|
|
1155
|
+
}
|
|
1156
|
+
}
|
|
1157
|
+
/**
|
|
1158
|
+
* Cancel (close) any Service Worker OS-trigger notification scheduled by us
|
|
1159
|
+
* under `tag === id`. Passes `includeTriggered: true` so that
|
|
1160
|
+
* scheduled-but-not-yet-fired trigger notifications are returned by
|
|
1161
|
+
* `getNotifications` — without it, pending OS-trigger notifications are
|
|
1162
|
+
* invisible and therefore impossible to cancel. No-op when there's no
|
|
1163
|
+
* registration (degraded / timer-only environments).
|
|
1164
|
+
*/
|
|
1165
|
+
async function cancelOsTriggerNotification(registration, id) {
|
|
1166
|
+
if (!registration) return;
|
|
1167
|
+
try {
|
|
1168
|
+
const matches = await registration.getNotifications({
|
|
1169
|
+
tag: id,
|
|
1170
|
+
includeTriggered: true
|
|
1171
|
+
});
|
|
1172
|
+
for (const n of matches) {
|
|
1173
|
+
if ((n.data ?? {}).__ambaLocalId !== id) continue;
|
|
1174
|
+
n.close();
|
|
1175
|
+
}
|
|
1176
|
+
} catch {}
|
|
1177
|
+
}
|
|
1178
|
+
/**
|
|
1179
|
+
* Show the in-page `Notification` for a fired timer. Tolerant of permission
|
|
1180
|
+
* being revoked between scheduling and firing (construction can throw).
|
|
1181
|
+
*/
|
|
1182
|
+
function fireInPageNotification(record, id) {
|
|
1183
|
+
try {
|
|
1184
|
+
const N = globalThis.Notification;
|
|
1185
|
+
new N(record.title, {
|
|
1186
|
+
body: record.body,
|
|
1187
|
+
data: {
|
|
1188
|
+
...record.data,
|
|
1189
|
+
__ambaLocalId: id
|
|
1190
|
+
},
|
|
1191
|
+
tag: id
|
|
1192
|
+
});
|
|
1193
|
+
} catch {}
|
|
1194
|
+
}
|
|
1195
|
+
/**
|
|
1196
|
+
* Arm the next chunk of an in-page timer for the registry entry under `id`.
|
|
1197
|
+
* If the remaining delay until `entry.fireAt` exceeds `MAX_TIMEOUT_MS`, arm
|
|
1198
|
+
* for `MAX_TIMEOUT_MS` and re-arm on wake; otherwise arm for the exact
|
|
1199
|
+
* remainder, then fire and remove the entry.
|
|
1200
|
+
*
|
|
1201
|
+
* `entry.handle` is reassigned to each chunk's timeout id, so a concurrent
|
|
1202
|
+
* `clearTimeout(entry.handle)` (cancel / reschedule) always targets the live
|
|
1203
|
+
* chunk and stops the chain.
|
|
1204
|
+
*/
|
|
1205
|
+
function armTimerChunk(id, entry) {
|
|
1206
|
+
const remaining = entry.fireAt - Date.now();
|
|
1207
|
+
if (remaining > MAX_TIMEOUT_MS) {
|
|
1208
|
+
entry.handle = setTimeout(() => {
|
|
1209
|
+
if (pendingTimers.get(id) === entry) armTimerChunk(id, entry);
|
|
1210
|
+
}, MAX_TIMEOUT_MS);
|
|
1211
|
+
return;
|
|
1212
|
+
}
|
|
1213
|
+
entry.handle = setTimeout(() => {
|
|
1214
|
+
if (pendingTimers.get(id) !== entry) return;
|
|
1215
|
+
pendingTimers.delete(id);
|
|
1216
|
+
fireInPageNotification(entry.record, id);
|
|
1217
|
+
}, Math.max(0, remaining));
|
|
1218
|
+
}
|
|
1219
|
+
/**
|
|
1220
|
+
* The web `notifications` namespace. Web capability is partial — see the
|
|
1221
|
+
* module-level doc. The returned handle includes `scheduledVia` so apps
|
|
1222
|
+
* can detect whether the notification was handed to the OS
|
|
1223
|
+
* (`"os-trigger"`) or relies on an in-page timer (`"timer"`).
|
|
1224
|
+
*/
|
|
1225
|
+
const notifications = {
|
|
1226
|
+
async scheduleLocal(input) {
|
|
1227
|
+
validateContent(input);
|
|
1228
|
+
if (!hasNotificationApi()) throw new AmbaApiError("LOCAL_NOTIFICATIONS_UNAVAILABLE", "the Notifications API is not available in this environment (server-side rendering, or a browser with notifications disabled). Local notifications require a browser context.");
|
|
1229
|
+
const parsedTrigger = parseTrigger(input);
|
|
1230
|
+
const id = normalizeScheduleId(input.id);
|
|
1231
|
+
await ensurePermission();
|
|
1232
|
+
const fireAt = computeFireAt(parsedTrigger);
|
|
1233
|
+
const instanceToken = genInstanceToken();
|
|
1234
|
+
const TriggerCtor = timestampTriggerCtor();
|
|
1235
|
+
const registration = await getServiceWorkerRegistration();
|
|
1236
|
+
if (TriggerCtor && registration) {
|
|
1237
|
+
await registration.showNotification(input.title, {
|
|
1238
|
+
body: input.body,
|
|
1239
|
+
data: {
|
|
1240
|
+
...input.data,
|
|
1241
|
+
__ambaLocalId: id,
|
|
1242
|
+
__ambaInstance: instanceToken
|
|
1243
|
+
},
|
|
1244
|
+
tag: id,
|
|
1245
|
+
showTrigger: new TriggerCtor(fireAt)
|
|
1246
|
+
});
|
|
1247
|
+
const priorTimer$1 = pendingTimers.get(id);
|
|
1248
|
+
if (priorTimer$1) {
|
|
1249
|
+
clearTimeout(priorTimer$1.handle);
|
|
1250
|
+
pendingTimers.delete(id);
|
|
1251
|
+
}
|
|
1252
|
+
return {
|
|
1253
|
+
id,
|
|
1254
|
+
scheduledVia: "os-trigger"
|
|
1255
|
+
};
|
|
1256
|
+
}
|
|
1257
|
+
const priorTimer = pendingTimers.get(id);
|
|
1258
|
+
if (priorTimer) {
|
|
1259
|
+
clearTimeout(priorTimer.handle);
|
|
1260
|
+
pendingTimers.delete(id);
|
|
1261
|
+
}
|
|
1262
|
+
await cancelOsTriggerNotification(registration, id);
|
|
1263
|
+
const entry = {
|
|
1264
|
+
handle: void 0,
|
|
1265
|
+
fireAt,
|
|
1266
|
+
record: {
|
|
1267
|
+
id,
|
|
1268
|
+
title: input.title,
|
|
1269
|
+
body: input.body,
|
|
1270
|
+
data: input.data
|
|
1271
|
+
}
|
|
1272
|
+
};
|
|
1273
|
+
pendingTimers.set(id, entry);
|
|
1274
|
+
armTimerChunk(id, entry);
|
|
1275
|
+
return {
|
|
1276
|
+
id,
|
|
1277
|
+
scheduledVia: "timer"
|
|
1278
|
+
};
|
|
1279
|
+
},
|
|
1280
|
+
async cancelLocal(id) {
|
|
1281
|
+
if (typeof id !== "string" || id.trim() === "") throw new AmbaApiError("INVALID_ARGUMENT", "Amba.notifications.cancelLocal: id is required");
|
|
1282
|
+
const timer = pendingTimers.get(id);
|
|
1283
|
+
if (timer) {
|
|
1284
|
+
clearTimeout(timer.handle);
|
|
1285
|
+
pendingTimers.delete(id);
|
|
1286
|
+
}
|
|
1287
|
+
await cancelOsTriggerNotification(await getServiceWorkerRegistration(), id);
|
|
1288
|
+
},
|
|
1289
|
+
async listScheduledLocal() {
|
|
1290
|
+
const out = [];
|
|
1291
|
+
for (const { record } of pendingTimers.values()) out.push({ ...record });
|
|
1292
|
+
const registration = await getServiceWorkerRegistration();
|
|
1293
|
+
if (registration) try {
|
|
1294
|
+
const [withTriggered, shownOnly] = await Promise.all([registration.getNotifications({ includeTriggered: true }), registration.getNotifications()]);
|
|
1295
|
+
const shownInstances = /* @__PURE__ */ new Set();
|
|
1296
|
+
for (const n of shownOnly) {
|
|
1297
|
+
const token = (n.data ?? {}).__ambaInstance;
|
|
1298
|
+
if (token) shownInstances.add(token);
|
|
1299
|
+
}
|
|
1300
|
+
for (const n of withTriggered) {
|
|
1301
|
+
const data = n.data ?? {};
|
|
1302
|
+
const id = data.__ambaLocalId;
|
|
1303
|
+
if (!id) continue;
|
|
1304
|
+
const token = data.__ambaInstance;
|
|
1305
|
+
if (token && shownInstances.has(token)) continue;
|
|
1306
|
+
if (out.some((existing) => existing.id === id)) continue;
|
|
1307
|
+
out.push({
|
|
1308
|
+
id,
|
|
1309
|
+
title: n.title,
|
|
1310
|
+
body: n.body ?? "",
|
|
1311
|
+
data
|
|
1312
|
+
});
|
|
1313
|
+
}
|
|
1314
|
+
} catch {}
|
|
1315
|
+
return out;
|
|
1316
|
+
}
|
|
1317
|
+
};
|
|
257
1318
|
|
|
258
1319
|
//#endregion
|
|
259
1320
|
//#region src/index.ts
|
|
@@ -296,6 +1357,153 @@ let _currentSessionToken = null;
|
|
|
296
1357
|
*/
|
|
297
1358
|
let _configuredFunctionsBaseUrl = null;
|
|
298
1359
|
let _resolvedFunctionsProjectId = null;
|
|
1360
|
+
/**
|
|
1361
|
+
* Offline-resilience state. `_persistence` is the localStorage-backed store
|
|
1362
|
+
* captured at configure-time; `_offlineQueue` is lazily built the first time
|
|
1363
|
+
* `Amba.offline.enable()` runs. `_offlineEnabled` gates whether failed writes
|
|
1364
|
+
* are diverted to the durable outbox (opt-in — default behavior is unchanged,
|
|
1365
|
+
* a failed write throws). All three reset on every `configure()`.
|
|
1366
|
+
*/
|
|
1367
|
+
let _persistence = null;
|
|
1368
|
+
let _offlineQueue = null;
|
|
1369
|
+
let _offlineEnabled = false;
|
|
1370
|
+
/**
|
|
1371
|
+
* Detacher for the active queue's `online` auto-flush listener, if installed.
|
|
1372
|
+
* Held so a `configure()` (or a fresh `enable()`) can tear it down — otherwise
|
|
1373
|
+
* the previous queue's listener leaks and fires against a dead queue.
|
|
1374
|
+
*/
|
|
1375
|
+
let _offlineDetach = null;
|
|
1376
|
+
/**
|
|
1377
|
+
* Monotonic token identifying the CURRENT offline activation. Bumped on every
|
|
1378
|
+
* `enable()` AND every teardown/`configure()`, and captured by each `enable()`
|
|
1379
|
+
* into its disable callback. A disabler only acts while the token still matches
|
|
1380
|
+
* — so a stale disabler (held across a re-`enable()` OR a reconfigure) becomes
|
|
1381
|
+
* a no-op instead of wrongly turning the now-active outbox off.
|
|
1382
|
+
*/
|
|
1383
|
+
let _offlineEnableToken = 0;
|
|
1384
|
+
/**
|
|
1385
|
+
* Tear down any active offline wiring: detach the `online` listener, DISPOSE
|
|
1386
|
+
* the active queue (awaiting any in-flight flush so it can never write the
|
|
1387
|
+
* shared outbox again), and drop the references. Bumps the generation so stale
|
|
1388
|
+
* `enable()` disable callbacks no-op. Called before re-initializing on
|
|
1389
|
+
* `configure()`. Async so the in-flight flush is awaited before a replacement
|
|
1390
|
+
* queue is installed — preventing an orphaned flush from racing the new queue.
|
|
1391
|
+
*/
|
|
1392
|
+
async function teardownOffline() {
|
|
1393
|
+
if (_offlineDetach) {
|
|
1394
|
+
_offlineDetach();
|
|
1395
|
+
_offlineDetach = null;
|
|
1396
|
+
}
|
|
1397
|
+
const old = _offlineQueue;
|
|
1398
|
+
_offlineQueue = null;
|
|
1399
|
+
_offlineEnabled = false;
|
|
1400
|
+
_offlineEnableToken += 1;
|
|
1401
|
+
if (old) await old.dispose();
|
|
1402
|
+
}
|
|
1403
|
+
/**
|
|
1404
|
+
* Bridge the localStorage persistence adapter to the {@link KvStore} contract
|
|
1405
|
+
* the offline outbox persists through. Namespaced under the configured
|
|
1406
|
+
* storage prefix so multiple projects in one origin don't collide.
|
|
1407
|
+
*/
|
|
1408
|
+
function offlineStore() {
|
|
1409
|
+
const p = _persistence;
|
|
1410
|
+
if (!p) throw new AmbaApiError("NOT_INITIALIZED", "amba SDK not configured. Call Amba.configure({ projectId, clientKey }) before using Amba.offline.");
|
|
1411
|
+
return {
|
|
1412
|
+
get: (key) => p.read(key),
|
|
1413
|
+
set: (key, value) => p.write(key, value),
|
|
1414
|
+
delete: (key) => p.delete(key)
|
|
1415
|
+
};
|
|
1416
|
+
}
|
|
1417
|
+
/**
|
|
1418
|
+
* Replay a single queued mutation against the live API, forwarding the op's
|
|
1419
|
+
* idempotency key on collection writes so a write that landed before the
|
|
1420
|
+
* connection dropped is never double-applied. Used as the {@link OfflineQueue}
|
|
1421
|
+
* executor.
|
|
1422
|
+
*/
|
|
1423
|
+
async function replayOutboxOp(op) {
|
|
1424
|
+
switch (op.kind) {
|
|
1425
|
+
case "collection.insert":
|
|
1426
|
+
await coreCall((c) => c.collectionsInsert(op.collection, encodeJson({
|
|
1427
|
+
...op.payload ?? {},
|
|
1428
|
+
idempotency_key: op.idempotencyKey
|
|
1429
|
+
})));
|
|
1430
|
+
return;
|
|
1431
|
+
case "collection.update":
|
|
1432
|
+
await coreCall((c) => c.collectionsUpdate(op.collection, op.id, encodeJson(op.payload ?? {})));
|
|
1433
|
+
return;
|
|
1434
|
+
case "collection.delete":
|
|
1435
|
+
await coreCall((c) => c.collectionsDelete(op.collection, op.id));
|
|
1436
|
+
return;
|
|
1437
|
+
case "track":
|
|
1438
|
+
if (op.occurredAt !== void 0) await replayTrackDirect(op);
|
|
1439
|
+
else await coreCall((c) => c.track(op.event, op.properties ? encodeJson(op.properties) : void 0, op.telemetry));
|
|
1440
|
+
return;
|
|
1441
|
+
}
|
|
1442
|
+
}
|
|
1443
|
+
/**
|
|
1444
|
+
* Replay a buffered `track` op via a direct POST to `/v1/client/events`,
|
|
1445
|
+
* preserving the original `timestamp` captured at enqueue (the events route
|
|
1446
|
+
* honors body `timestamp` → `occurred_at`, but attributes the event to the
|
|
1447
|
+
* current session user — it has no body-`anonymous_id` attribution). Throws on
|
|
1448
|
+
* a transport failure or non-2xx so the queue retains the op.
|
|
1449
|
+
*
|
|
1450
|
+
* A `401`/`403` (no / expired session at replay) is surfaced as a coded
|
|
1451
|
+
* `NETWORK_ERROR` so the outbox RETAINS the event for a later attempt — an
|
|
1452
|
+
* unauthenticated replay must NOT be dropped as a deterministic rejection
|
|
1453
|
+
* (the session may refresh and the event then lands).
|
|
1454
|
+
*/
|
|
1455
|
+
async function replayTrackDirect(op) {
|
|
1456
|
+
const headers = { "content-type": "application/json" };
|
|
1457
|
+
if (_configuredClientKey) headers["X-Api-Key"] = _configuredClientKey;
|
|
1458
|
+
if (_currentSessionToken) headers["Authorization"] = `Bearer ${_currentSessionToken}`;
|
|
1459
|
+
const body = {
|
|
1460
|
+
event: op.event,
|
|
1461
|
+
properties: op.properties ?? void 0,
|
|
1462
|
+
timestamp: op.occurredAt,
|
|
1463
|
+
...op.telemetry ? { telemetry: true } : {}
|
|
1464
|
+
};
|
|
1465
|
+
const eventsUrl = `${_configuredApiUrl.replace(/\/$/, "")}/v1/client/events`;
|
|
1466
|
+
let resp;
|
|
1467
|
+
try {
|
|
1468
|
+
resp = await fetch(eventsUrl, {
|
|
1469
|
+
method: "POST",
|
|
1470
|
+
headers,
|
|
1471
|
+
body: JSON.stringify(body)
|
|
1472
|
+
});
|
|
1473
|
+
} catch (err) {
|
|
1474
|
+
throw new AmbaApiError("NETWORK_ERROR", `track replay network error: ${String(err)}`);
|
|
1475
|
+
}
|
|
1476
|
+
if (!resp.ok) {
|
|
1477
|
+
if (resp.status === 401 || resp.status === 403) throw new AmbaApiError("NETWORK_ERROR", `track replay deferred: no valid session (status ${resp.status})`);
|
|
1478
|
+
const text = await resp.text().catch(() => "");
|
|
1479
|
+
let code = `HTTP_${resp.status}`;
|
|
1480
|
+
try {
|
|
1481
|
+
const parsed = JSON.parse(text);
|
|
1482
|
+
if (typeof parsed?.error?.code === "string") code = parsed.error.code;
|
|
1483
|
+
} catch {}
|
|
1484
|
+
throw new AmbaApiError(code, `track replay failed with status ${resp.status}`, text);
|
|
1485
|
+
}
|
|
1486
|
+
}
|
|
1487
|
+
function getOfflineQueue() {
|
|
1488
|
+
if (!_offlineQueue) _offlineQueue = new OfflineQueue({
|
|
1489
|
+
store: offlineStore(),
|
|
1490
|
+
storageKey: `offline_outbox:${_configuredProjectId ?? "default"}`,
|
|
1491
|
+
executor: replayOutboxOp,
|
|
1492
|
+
onDropped: (op, err) => {
|
|
1493
|
+
if (typeof console !== "undefined") console.warn(`[amba] dropped un-replayable offline ${op.kind} (${op.collection ?? op.event ?? "?"}):`, err);
|
|
1494
|
+
}
|
|
1495
|
+
});
|
|
1496
|
+
return _offlineQueue;
|
|
1497
|
+
}
|
|
1498
|
+
async function insertDirect(name, row) {
|
|
1499
|
+
return await coreCall((c) => c.collectionsInsert(name, encodeJson(row)));
|
|
1500
|
+
}
|
|
1501
|
+
async function updateDirect(name, id, set) {
|
|
1502
|
+
return await coreCall((c) => c.collectionsUpdate(name, id, encodeJson(set)));
|
|
1503
|
+
}
|
|
1504
|
+
async function deleteDirect(name, id) {
|
|
1505
|
+
return await coreCall((c) => c.collectionsDelete(name, id));
|
|
1506
|
+
}
|
|
299
1507
|
function requireCore() {
|
|
300
1508
|
if (!coreInstance) throw new AmbaApiError("NOT_INITIALIZED", "amba SDK not configured. Call Amba.configure({ projectId, clientKey }) at app start before any other API.");
|
|
301
1509
|
return coreInstance;
|
|
@@ -316,6 +1524,26 @@ async function coreCall(fn) {
|
|
|
316
1524
|
}
|
|
317
1525
|
}
|
|
318
1526
|
const authSubscribers = /* @__PURE__ */ new Set();
|
|
1527
|
+
/**
|
|
1528
|
+
* Translate a public `TransactionOp` (camelCase `onConflict` /
|
|
1529
|
+
* `conflictTarget`) into the server's wire op (snake_case `on_conflict` /
|
|
1530
|
+
* `conflict_target`). Unset optionals are dropped so the server applies its
|
|
1531
|
+
* defaults.
|
|
1532
|
+
*/
|
|
1533
|
+
function toWireTransactionOp(op) {
|
|
1534
|
+
const wire = {
|
|
1535
|
+
collection: op.collection,
|
|
1536
|
+
op: op.op
|
|
1537
|
+
};
|
|
1538
|
+
if (op.id !== void 0) wire["id"] = op.id;
|
|
1539
|
+
if (op.row !== void 0) wire["row"] = op.row;
|
|
1540
|
+
if (op.set !== void 0) wire["set"] = op.set;
|
|
1541
|
+
if (op.where !== void 0) wire["where"] = op.where;
|
|
1542
|
+
if (op.expected !== void 0) wire["expected"] = op.expected;
|
|
1543
|
+
if (op.onConflict !== void 0) wire["on_conflict"] = op.onConflict;
|
|
1544
|
+
if (op.conflictTarget !== void 0) wire["conflict_target"] = op.conflictTarget;
|
|
1545
|
+
return wire;
|
|
1546
|
+
}
|
|
319
1547
|
function snapshotSession(user) {
|
|
320
1548
|
if (!user) return null;
|
|
321
1549
|
return {
|
|
@@ -348,6 +1576,35 @@ function realtimeAuthHeaders() {
|
|
|
348
1576
|
Authorization: `Bearer ${_currentSessionToken}`
|
|
349
1577
|
};
|
|
350
1578
|
}
|
|
1579
|
+
/** SDK-facing AI streaming routes (vendor split is a stable wire shape). */
|
|
1580
|
+
const AI_ANTHROPIC_PATH = "/v1/client/ai/anthropic/messages";
|
|
1581
|
+
const AI_OPENAI_PATH = "/v1/client/ai/openai/chat/completions";
|
|
1582
|
+
/**
|
|
1583
|
+
* Build the request (url + headers + body) for a streamed AI invocation.
|
|
1584
|
+
* Forces `stream: true` onto the request, injects the client key + live
|
|
1585
|
+
* session token, and targets the configured API base. Shared by the
|
|
1586
|
+
* Anthropic + OpenAI streaming methods so the auth/path wiring can't drift.
|
|
1587
|
+
*/
|
|
1588
|
+
function buildAiStreamRequest(path, request) {
|
|
1589
|
+
requireCore();
|
|
1590
|
+
if (!_configuredClientKey) throw new AmbaApiError("NOT_INITIALIZED", "amba SDK not configured. Call Amba.configure({ projectId, clientKey }) before streaming AI.");
|
|
1591
|
+
if (!request.prompt_slug || request.prompt_slug.trim() === "") throw new AmbaApiError("INVALID_ARGUMENT", "prompt_slug is required");
|
|
1592
|
+
const headers = {
|
|
1593
|
+
"X-Api-Key": _configuredClientKey,
|
|
1594
|
+
"content-type": "application/json",
|
|
1595
|
+
accept: "text/event-stream"
|
|
1596
|
+
};
|
|
1597
|
+
if (_currentSessionToken) headers["Authorization"] = `Bearer ${_currentSessionToken}`;
|
|
1598
|
+
const expanded = expandAiImages(request);
|
|
1599
|
+
return {
|
|
1600
|
+
url: `${_configuredApiUrl.replace(/\/$/, "")}${path}`,
|
|
1601
|
+
headers,
|
|
1602
|
+
body: JSON.stringify({
|
|
1603
|
+
...expanded,
|
|
1604
|
+
stream: true
|
|
1605
|
+
})
|
|
1606
|
+
};
|
|
1607
|
+
}
|
|
351
1608
|
/**
|
|
352
1609
|
* Resolve the full invocation URL for a deployed function.
|
|
353
1610
|
*
|
|
@@ -388,9 +1645,11 @@ const Amba = {
|
|
|
388
1645
|
else wasmJsUrl = pathToFileURL(createRequire(import.meta.url).resolve("@layers/amba-core/wasm")).href;
|
|
389
1646
|
await init(await readFile(fileURLToPath(wasmJsUrl)));
|
|
390
1647
|
} else await init();
|
|
391
|
-
new LocalStoragePersistence(config.storagePrefix ?? "amba")
|
|
1648
|
+
const persistence = new LocalStoragePersistence(config.storagePrefix ?? "amba");
|
|
1649
|
+
persistence.hydrate();
|
|
1650
|
+
let nextCore;
|
|
392
1651
|
try {
|
|
393
|
-
|
|
1652
|
+
nextCore = AmbaCoreWasm.init(encodeJson({
|
|
394
1653
|
api_key: config.clientKey,
|
|
395
1654
|
base_url: config.apiUrl,
|
|
396
1655
|
project_id: config.projectId,
|
|
@@ -402,6 +1661,9 @@ const Amba = {
|
|
|
402
1661
|
} catch (err) {
|
|
403
1662
|
throw toAmbaApiError(err);
|
|
404
1663
|
}
|
|
1664
|
+
await teardownOffline();
|
|
1665
|
+
_persistence = persistence;
|
|
1666
|
+
coreInstance = nextCore;
|
|
405
1667
|
_configuredProjectId = config.projectId;
|
|
406
1668
|
_configuredApiUrl = config.apiUrl ?? DEFAULT_API_URL;
|
|
407
1669
|
_configuredClientKey = config.clientKey;
|
|
@@ -424,9 +1686,59 @@ const Amba = {
|
|
|
424
1686
|
setDebug: (enabled) => {
|
|
425
1687
|
requireCore().setDebug(enabled);
|
|
426
1688
|
},
|
|
427
|
-
events: {
|
|
428
|
-
|
|
429
|
-
|
|
1689
|
+
events: {
|
|
1690
|
+
track: async (event, properties, options) => {
|
|
1691
|
+
try {
|
|
1692
|
+
await coreCall((c) => c.track(event, properties ? encodeJson(properties) : void 0, options?.telemetry));
|
|
1693
|
+
} catch (err) {
|
|
1694
|
+
if (_offlineEnabled && isOfflineError(err)) {
|
|
1695
|
+
await getOfflineQueue().enqueue({
|
|
1696
|
+
kind: "track",
|
|
1697
|
+
event,
|
|
1698
|
+
properties,
|
|
1699
|
+
telemetry: options?.telemetry,
|
|
1700
|
+
occurredAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
1701
|
+
});
|
|
1702
|
+
return;
|
|
1703
|
+
}
|
|
1704
|
+
throw err;
|
|
1705
|
+
}
|
|
1706
|
+
},
|
|
1707
|
+
explain: async (event, properties, options) => {
|
|
1708
|
+
if (!_configuredClientKey) throw new AmbaApiError("NOT_INITIALIZED", "amba SDK not configured. Call Amba.configure({ projectId, clientKey }) before Amba.events.explain().");
|
|
1709
|
+
if (!event || event.trim() === "") throw new AmbaApiError("INVALID_ARGUMENT", "Amba.events.explain: an event name is required.");
|
|
1710
|
+
const candidate = { name: event };
|
|
1711
|
+
if (properties !== void 0) candidate["properties"] = properties;
|
|
1712
|
+
if (options && "userId" in options) candidate["user_id"] = options.userId ?? null;
|
|
1713
|
+
const headers = {
|
|
1714
|
+
"Content-Type": "application/json",
|
|
1715
|
+
"X-Api-Key": _configuredClientKey
|
|
1716
|
+
};
|
|
1717
|
+
if (_currentSessionToken) headers["Authorization"] = `Bearer ${_currentSessionToken}`;
|
|
1718
|
+
let resp;
|
|
1719
|
+
try {
|
|
1720
|
+
resp = await fetch(`${_configuredApiUrl.replace(/\/$/, "")}/v1/client/events/explain`, {
|
|
1721
|
+
method: "POST",
|
|
1722
|
+
headers,
|
|
1723
|
+
body: JSON.stringify({ event: candidate })
|
|
1724
|
+
});
|
|
1725
|
+
} catch (err) {
|
|
1726
|
+
throw new AmbaApiError("NETWORK_ERROR", `Amba.events.explain("${event}") network error: ${String(err)}`);
|
|
1727
|
+
}
|
|
1728
|
+
const text = await resp.text();
|
|
1729
|
+
let parsed = void 0;
|
|
1730
|
+
if (text.length > 0) try {
|
|
1731
|
+
parsed = JSON.parse(text);
|
|
1732
|
+
} catch {
|
|
1733
|
+
parsed = void 0;
|
|
1734
|
+
}
|
|
1735
|
+
if (!resp.ok) {
|
|
1736
|
+
const envelope = parsed && typeof parsed === "object" ? parsed : void 0;
|
|
1737
|
+
throw new AmbaApiError(typeof envelope?.error?.code === "string" ? envelope.error.code : `HTTP_${resp.status}`, typeof envelope?.error?.message === "string" ? envelope.error.message : `Amba.events.explain("${event}") failed with status ${resp.status}`, parsed);
|
|
1738
|
+
}
|
|
1739
|
+
return parsed.data;
|
|
1740
|
+
}
|
|
1741
|
+
},
|
|
430
1742
|
auth: {
|
|
431
1743
|
signInAnonymously: async () => {
|
|
432
1744
|
const r = await coreCall((c) => c.signInAnonymously());
|
|
@@ -564,20 +1876,106 @@ const Amba = {
|
|
|
564
1876
|
return await coreCall((c) => c.collectionsFindOne(name, id));
|
|
565
1877
|
},
|
|
566
1878
|
insert: async (name, row) => {
|
|
1879
|
+
if (_offlineEnabled) {
|
|
1880
|
+
const idempotencyKey = (typeof row["idempotency_key"] === "string" ? row["idempotency_key"] : void 0) ?? newIdempotencyKey();
|
|
1881
|
+
const wireRow = {
|
|
1882
|
+
...row,
|
|
1883
|
+
idempotency_key: idempotencyKey
|
|
1884
|
+
};
|
|
1885
|
+
try {
|
|
1886
|
+
return await coreCall((c) => c.collectionsInsert(name, encodeJson(wireRow)));
|
|
1887
|
+
} catch (err) {
|
|
1888
|
+
if (isOfflineError(err)) {
|
|
1889
|
+
await getOfflineQueue().enqueue({
|
|
1890
|
+
kind: "collection.insert",
|
|
1891
|
+
collection: name,
|
|
1892
|
+
payload: row,
|
|
1893
|
+
idempotencyKey
|
|
1894
|
+
});
|
|
1895
|
+
return {
|
|
1896
|
+
...row,
|
|
1897
|
+
_amba_pending: true
|
|
1898
|
+
};
|
|
1899
|
+
}
|
|
1900
|
+
throw err;
|
|
1901
|
+
}
|
|
1902
|
+
}
|
|
567
1903
|
return await coreCall((c) => c.collectionsInsert(name, encodeJson(row)));
|
|
568
1904
|
},
|
|
569
1905
|
update: async (name, id, set) => {
|
|
1906
|
+
if (_offlineEnabled) try {
|
|
1907
|
+
return await coreCall((c) => c.collectionsUpdate(name, id, encodeJson(set)));
|
|
1908
|
+
} catch (err) {
|
|
1909
|
+
if (isOfflineError(err)) {
|
|
1910
|
+
await getOfflineQueue().enqueue({
|
|
1911
|
+
kind: "collection.update",
|
|
1912
|
+
collection: name,
|
|
1913
|
+
id,
|
|
1914
|
+
payload: set
|
|
1915
|
+
});
|
|
1916
|
+
return {
|
|
1917
|
+
id,
|
|
1918
|
+
...set,
|
|
1919
|
+
_amba_pending: true
|
|
1920
|
+
};
|
|
1921
|
+
}
|
|
1922
|
+
throw err;
|
|
1923
|
+
}
|
|
570
1924
|
return await coreCall((c) => c.collectionsUpdate(name, id, encodeJson(set)));
|
|
571
1925
|
},
|
|
572
1926
|
delete: async (name, id) => {
|
|
1927
|
+
if (_offlineEnabled) try {
|
|
1928
|
+
return await coreCall((c) => c.collectionsDelete(name, id));
|
|
1929
|
+
} catch (err) {
|
|
1930
|
+
if (isOfflineError(err)) {
|
|
1931
|
+
await getOfflineQueue().enqueue({
|
|
1932
|
+
kind: "collection.delete",
|
|
1933
|
+
collection: name,
|
|
1934
|
+
id
|
|
1935
|
+
});
|
|
1936
|
+
return { data: { deleted: true } };
|
|
1937
|
+
}
|
|
1938
|
+
throw err;
|
|
1939
|
+
}
|
|
573
1940
|
return await coreCall((c) => c.collectionsDelete(name, id));
|
|
574
1941
|
},
|
|
1942
|
+
upsert: async (name, row, options) => {
|
|
1943
|
+
const wire = {
|
|
1944
|
+
on_conflict: options.onConflict,
|
|
1945
|
+
conflict_target: options.conflictTarget
|
|
1946
|
+
};
|
|
1947
|
+
return await coreCall((c) => c.collectionsUpsert(name, encodeJson(row), encodeJson(wire)));
|
|
1948
|
+
},
|
|
1949
|
+
deleteWhere: async (name, filter) => {
|
|
1950
|
+
return await coreCall((c) => c.collectionsDeleteWhere(name, encodeJson(filter)));
|
|
1951
|
+
},
|
|
1952
|
+
restore: async (name, id) => {
|
|
1953
|
+
return await coreCall((c) => c.collectionsRestore(name, id));
|
|
1954
|
+
},
|
|
1955
|
+
transaction: async (operations) => {
|
|
1956
|
+
return (await coreCall((c) => c.collectionsTransaction(encodeJson(operations.map(toWireTransactionOp))))).data;
|
|
1957
|
+
},
|
|
575
1958
|
findNearest: async (name, options) => {
|
|
576
1959
|
return await coreCall((c) => c.collectionsFindNearest(name, encodeJson(options)));
|
|
577
1960
|
},
|
|
578
1961
|
count: async (name, filter) => {
|
|
579
1962
|
return await coreCall((c) => c.collectionsCount(name, filter ? encodeJson(filter) : void 0));
|
|
580
1963
|
},
|
|
1964
|
+
optimisticInsert: async (name, row, view) => withOptimistic({
|
|
1965
|
+
apply: view.apply,
|
|
1966
|
+
mutate: () => insertDirect(name, row),
|
|
1967
|
+
rollback: view.rollback
|
|
1968
|
+
}),
|
|
1969
|
+
optimisticUpdate: async (name, id, set, view) => withOptimistic({
|
|
1970
|
+
apply: view.apply,
|
|
1971
|
+
mutate: () => updateDirect(name, id, set),
|
|
1972
|
+
rollback: view.rollback
|
|
1973
|
+
}),
|
|
1974
|
+
optimisticDelete: async (name, id, view) => withOptimistic({
|
|
1975
|
+
apply: view.apply,
|
|
1976
|
+
mutate: () => deleteDirect(name, id),
|
|
1977
|
+
rollback: view.rollback
|
|
1978
|
+
}),
|
|
581
1979
|
where: {
|
|
582
1980
|
eq: (column, value) => ({
|
|
583
1981
|
column,
|
|
@@ -663,7 +2061,7 @@ const Amba = {
|
|
|
663
2061
|
headers: uploadHeaders,
|
|
664
2062
|
body: params.file
|
|
665
2063
|
});
|
|
666
|
-
if (!putResp.ok) throw new Error(`upload to
|
|
2064
|
+
if (!putResp.ok) throw new Error(`upload to storage failed: status ${putResp.status}`);
|
|
667
2065
|
return await coreCall((c) => c.storageCommit(presign.upload_id, presign.asset_id));
|
|
668
2066
|
},
|
|
669
2067
|
list: async (prefix) => {
|
|
@@ -677,6 +2075,32 @@ const Amba = {
|
|
|
677
2075
|
return new Blob([bytes]);
|
|
678
2076
|
}
|
|
679
2077
|
},
|
|
2078
|
+
media: { catalog: async (slug) => {
|
|
2079
|
+
if (!_configuredClientKey) throw new AmbaApiError("NOT_INITIALIZED", "amba SDK not configured. Call Amba.configure({ projectId, clientKey }) before reading a media catalog.");
|
|
2080
|
+
if (!slug || slug.trim() === "") throw new AmbaApiError("INVALID_ARGUMENT", "Amba.media.catalog: a catalog slug is required.");
|
|
2081
|
+
const url = `${_configuredApiUrl.replace(/\/$/, "")}/v1/client/media/catalogs/${encodeURIComponent(slug)}`;
|
|
2082
|
+
let resp;
|
|
2083
|
+
try {
|
|
2084
|
+
resp = await fetch(url, {
|
|
2085
|
+
method: "GET",
|
|
2086
|
+
headers: { "X-Api-Key": _configuredClientKey }
|
|
2087
|
+
});
|
|
2088
|
+
} catch (err) {
|
|
2089
|
+
throw new AmbaApiError("NETWORK_ERROR", `Amba.media.catalog("${slug}") network error: ${String(err)}`);
|
|
2090
|
+
}
|
|
2091
|
+
const text = await resp.text();
|
|
2092
|
+
let parsed = void 0;
|
|
2093
|
+
if (text.length > 0) try {
|
|
2094
|
+
parsed = JSON.parse(text);
|
|
2095
|
+
} catch {
|
|
2096
|
+
parsed = void 0;
|
|
2097
|
+
}
|
|
2098
|
+
if (!resp.ok) {
|
|
2099
|
+
const envelope = parsed && typeof parsed === "object" ? parsed : void 0;
|
|
2100
|
+
throw new AmbaApiError(typeof envelope?.error?.code === "string" ? envelope.error.code : `HTTP_${resp.status}`, typeof envelope?.error?.message === "string" ? envelope.error.message : `Amba.media.catalog("${slug}") failed with status ${resp.status}`, parsed);
|
|
2101
|
+
}
|
|
2102
|
+
return parsed.data;
|
|
2103
|
+
} },
|
|
680
2104
|
sync: {
|
|
681
2105
|
pushChanges: async (changes) => {
|
|
682
2106
|
return await coreCall((c) => c.syncPushChanges(encodeJson(changes)));
|
|
@@ -685,6 +2109,33 @@ const Amba = {
|
|
|
685
2109
|
return await coreCall((c) => c.syncPullChanges(encodeJson(since)));
|
|
686
2110
|
}
|
|
687
2111
|
},
|
|
2112
|
+
offline: {
|
|
2113
|
+
enable: () => {
|
|
2114
|
+
if (_offlineDetach) {
|
|
2115
|
+
_offlineDetach();
|
|
2116
|
+
_offlineDetach = null;
|
|
2117
|
+
}
|
|
2118
|
+
_offlineEnabled = true;
|
|
2119
|
+
_offlineEnableToken += 1;
|
|
2120
|
+
const token = _offlineEnableToken;
|
|
2121
|
+
const q = getOfflineQueue();
|
|
2122
|
+
_offlineDetach = q.startAutoFlush();
|
|
2123
|
+
q.flush();
|
|
2124
|
+
return () => {
|
|
2125
|
+
if (_offlineEnableToken !== token) return;
|
|
2126
|
+
_offlineEnabled = false;
|
|
2127
|
+
if (_offlineDetach) {
|
|
2128
|
+
_offlineDetach();
|
|
2129
|
+
_offlineDetach = null;
|
|
2130
|
+
}
|
|
2131
|
+
};
|
|
2132
|
+
},
|
|
2133
|
+
isEnabled: () => _offlineEnabled,
|
|
2134
|
+
pendingCount: async () => getOfflineQueue().pendingCount(),
|
|
2135
|
+
pending: async () => getOfflineQueue().pending(),
|
|
2136
|
+
flush: async () => getOfflineQueue().flush(),
|
|
2137
|
+
clear: async () => getOfflineQueue().clear()
|
|
2138
|
+
},
|
|
688
2139
|
push: {
|
|
689
2140
|
register: async (token, platform, bundleId) => {
|
|
690
2141
|
return await coreCall((c) => c.pushRegister(token, platform, bundleId ?? void 0));
|
|
@@ -700,19 +2151,49 @@ const Amba = {
|
|
|
700
2151
|
},
|
|
701
2152
|
unsubscribe: async (topic) => {
|
|
702
2153
|
await coreCall((c) => c.pushUnsubscribe(topic));
|
|
703
|
-
}
|
|
2154
|
+
},
|
|
2155
|
+
enableAutoRotation: () => enableWebPushAutoRotation((token) => Amba.push.register(token, "web"))
|
|
704
2156
|
},
|
|
2157
|
+
notifications,
|
|
705
2158
|
entitlements: {
|
|
706
2159
|
list: async () => {
|
|
707
2160
|
return await coreCall((c) => c.entitlementsList());
|
|
708
2161
|
},
|
|
709
2162
|
has: async (name) => {
|
|
710
2163
|
return await coreCall((c) => c.entitlementsHas(name));
|
|
2164
|
+
},
|
|
2165
|
+
restore: async () => {
|
|
2166
|
+
return await coreCall((c) => c.entitlementsRestore());
|
|
711
2167
|
}
|
|
712
2168
|
},
|
|
713
|
-
|
|
714
|
-
return await coreCall((c) => c.
|
|
715
|
-
}
|
|
2169
|
+
offerings: async (offeringId) => {
|
|
2170
|
+
return await coreCall((c) => offeringId ? c.offeringsGet(offeringId) : c.offeringsList());
|
|
2171
|
+
},
|
|
2172
|
+
ai: {
|
|
2173
|
+
anthropic: { messages: {
|
|
2174
|
+
create: async (request) => {
|
|
2175
|
+
return await coreCall((c) => c.aiAnthropicMessages(encodeJson(expandAiImages(request))));
|
|
2176
|
+
},
|
|
2177
|
+
stream: (request, options) => {
|
|
2178
|
+
const { url, headers, body } = buildAiStreamRequest(AI_ANTHROPIC_PATH, request);
|
|
2179
|
+
return invokeAiStream({
|
|
2180
|
+
url,
|
|
2181
|
+
headers,
|
|
2182
|
+
body,
|
|
2183
|
+
onChunk: options?.onChunk
|
|
2184
|
+
});
|
|
2185
|
+
}
|
|
2186
|
+
} },
|
|
2187
|
+
openai: { chat: { completions: { stream: (request, options) => {
|
|
2188
|
+
const { url, headers, body } = buildAiStreamRequest(AI_OPENAI_PATH, request);
|
|
2189
|
+
return invokeAiStream({
|
|
2190
|
+
url,
|
|
2191
|
+
headers,
|
|
2192
|
+
body,
|
|
2193
|
+
onChunk: options?.onChunk
|
|
2194
|
+
});
|
|
2195
|
+
} } } }
|
|
2196
|
+
},
|
|
716
2197
|
functions: { invoke: async (name, body, options) => {
|
|
717
2198
|
requireCore();
|
|
718
2199
|
if (!_configuredClientKey) throw new AmbaApiError("NOT_INITIALIZED", "amba SDK not configured. Call Amba.configure({ projectId, clientKey }) before Amba.functions.invoke().");
|
|
@@ -746,9 +2227,14 @@ const Amba = {
|
|
|
746
2227
|
} catch {
|
|
747
2228
|
parsed = text;
|
|
748
2229
|
}
|
|
2230
|
+
const envelopeRequestId = parsed && typeof parsed === "object" ? parsed.error?.request_id ?? parsed.request_id : void 0;
|
|
2231
|
+
const traceId = resp.headers.get("X-Amba-Request-Id") ?? (typeof envelopeRequestId === "string" ? envelopeRequestId : null);
|
|
2232
|
+
options?.onTraceId?.(traceId);
|
|
749
2233
|
if (!resp.ok) {
|
|
750
2234
|
const envelope = parsed && typeof parsed === "object" ? parsed : void 0;
|
|
751
|
-
|
|
2235
|
+
const error = new AmbaApiError(typeof envelope?.error?.code === "string" ? envelope.error.code : `HTTP_${resp.status}`, typeof envelope?.error?.message === "string" ? envelope.error.message : typeof parsed === "string" && parsed.length > 0 ? parsed : `Amba.functions.invoke("${name}") failed with status ${resp.status}`, parsed);
|
|
2236
|
+
if (traceId !== null) error.traceId = traceId;
|
|
2237
|
+
throw error;
|
|
752
2238
|
}
|
|
753
2239
|
return parsed;
|
|
754
2240
|
} },
|
|
@@ -813,6 +2299,12 @@ const Amba = {
|
|
|
813
2299
|
getAll: async () => await coreCall((c) => c.streaksGetAll()),
|
|
814
2300
|
qualify: async (streakKey) => await coreCall((c) => c.streaksQualify(streakKey))
|
|
815
2301
|
},
|
|
2302
|
+
get gamification() {
|
|
2303
|
+
return new GamificationSubscription({
|
|
2304
|
+
baseUrl: _configuredApiUrl,
|
|
2305
|
+
authHeaders: realtimeAuthHeaders
|
|
2306
|
+
});
|
|
2307
|
+
},
|
|
816
2308
|
feeds: { getActivity: async (feed, cursor) => await coreCall((c) => c.feedsGetActivity(feed ?? void 0, cursor ?? void 0)) },
|
|
817
2309
|
friends: {
|
|
818
2310
|
getList: async () => await coreCall((c) => c.friendsGetList()),
|
|
@@ -921,8 +2413,8 @@ function getCoreWasm() {
|
|
|
921
2413
|
* `verify-sdk-version-coherence` GH action gates every publish on the
|
|
922
2414
|
* pair agreeing (and matching the `web-v<X.Y.Z>` tag when tag-triggered).
|
|
923
2415
|
*/
|
|
924
|
-
const SDK_VERSION = "4.0.
|
|
2416
|
+
const SDK_VERSION = "4.0.6";
|
|
925
2417
|
|
|
926
2418
|
//#endregion
|
|
927
|
-
export { Amba, AmbaApiError, CollectionSubscription, ConversationSubscription, SDK_VERSION, getCoreWasm };
|
|
2419
|
+
export { Amba, AmbaApiError, CollectionSubscription, ConversationSubscription, GamificationSubscription, SDK_VERSION, getCoreWasm, withOptimistic };
|
|
928
2420
|
//# sourceMappingURL=index.js.map
|