@everfur/sdk 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (89) hide show
  1. package/CHANGELOG.md +74 -0
  2. package/LICENSE +21 -0
  3. package/README.md +161 -0
  4. package/animations/package.json +8 -0
  5. package/chat/package.json +8 -0
  6. package/client/package.json +8 -0
  7. package/core/package.json +8 -0
  8. package/dist/CameraPort-Cv31Pz7g.d.cts +29 -0
  9. package/dist/CameraPort-Cv31Pz7g.d.ts +29 -0
  10. package/dist/ChatController-CKdBvPj2.d.ts +146 -0
  11. package/dist/ChatController-CpUMvvZf.d.cts +146 -0
  12. package/dist/EverfurResult-D92-uL82.d.cts +240 -0
  13. package/dist/EverfurResult-D92-uL82.d.ts +240 -0
  14. package/dist/FilePort-BabWrv7I.d.cts +22 -0
  15. package/dist/FilePort-BabWrv7I.d.ts +22 -0
  16. package/dist/PhotoController-BItt5M7u.d.cts +43 -0
  17. package/dist/PhotoController-D8zMTdcW.d.ts +43 -0
  18. package/dist/TelemetryPort-BDNr00hu.d.cts +12 -0
  19. package/dist/TelemetryPort-BDNr00hu.d.ts +12 -0
  20. package/dist/animations/index.cjs +1997 -0
  21. package/dist/animations/index.d.cts +517 -0
  22. package/dist/animations/index.d.ts +517 -0
  23. package/dist/animations/index.js +1972 -0
  24. package/dist/cacheEpoch-DknKn3S0.d.cts +36 -0
  25. package/dist/cacheEpoch-DknKn3S0.d.ts +36 -0
  26. package/dist/chat/index.cjs +1170 -0
  27. package/dist/chat/index.d.cts +59 -0
  28. package/dist/chat/index.d.ts +59 -0
  29. package/dist/chat/index.js +1167 -0
  30. package/dist/client/index.cjs +2317 -0
  31. package/dist/client/index.d.cts +65 -0
  32. package/dist/client/index.d.ts +65 -0
  33. package/dist/client/index.js +2217 -0
  34. package/dist/config-BSjBdxrZ.d.cts +501 -0
  35. package/dist/config-CiJ0PVBB.d.ts +501 -0
  36. package/dist/core/index.cjs +3175 -0
  37. package/dist/core/index.d.cts +70 -0
  38. package/dist/core/index.d.ts +70 -0
  39. package/dist/core/index.js +3163 -0
  40. package/dist/identity-Brl-lDd6.d.cts +91 -0
  41. package/dist/identity-DK9zORrG.d.ts +91 -0
  42. package/dist/ids-CJ1S6adf.d.cts +46 -0
  43. package/dist/ids-CJ1S6adf.d.ts +46 -0
  44. package/dist/index.cjs +4488 -0
  45. package/dist/index.d.cts +156 -0
  46. package/dist/index.d.ts +156 -0
  47. package/dist/index.js +4464 -0
  48. package/dist/petsRepository-BEGb97M9.d.cts +326 -0
  49. package/dist/petsRepository-Bu18r2kK.d.ts +326 -0
  50. package/dist/photo/index.cjs +2189 -0
  51. package/dist/photo/index.d.cts +43 -0
  52. package/dist/photo/index.d.ts +43 -0
  53. package/dist/photo/index.js +2186 -0
  54. package/dist/projection-CeIUsbSk.d.cts +8 -0
  55. package/dist/projection-CeIUsbSk.d.ts +8 -0
  56. package/dist/records/index.cjs +2840 -0
  57. package/dist/records/index.d.cts +224 -0
  58. package/dist/records/index.d.ts +224 -0
  59. package/dist/records/index.js +2834 -0
  60. package/dist/requestFunnel-DuUH-kAe.d.cts +28 -0
  61. package/dist/requestFunnel-dio5OmR9.d.ts +28 -0
  62. package/dist/resolve-Dq_4_agU.d.cts +86 -0
  63. package/dist/resolve-Dq_4_agU.d.ts +86 -0
  64. package/dist/runtime-BgQnA594.d.cts +349 -0
  65. package/dist/runtime-CBA-LvdM.d.ts +349 -0
  66. package/dist/server/index.cjs +533 -0
  67. package/dist/server/index.d.cts +48 -0
  68. package/dist/server/index.d.ts +48 -0
  69. package/dist/server/index.js +530 -0
  70. package/dist/testing/index.cjs +825 -0
  71. package/dist/testing/index.d.cts +113 -0
  72. package/dist/testing/index.d.ts +113 -0
  73. package/dist/testing/index.js +822 -0
  74. package/dist/testing/rn/index.cjs +449 -0
  75. package/dist/testing/rn/index.d.cts +49 -0
  76. package/dist/testing/rn/index.d.ts +49 -0
  77. package/dist/testing/rn/index.js +444 -0
  78. package/dist/video/index.cjs +1941 -0
  79. package/dist/video/index.d.cts +66 -0
  80. package/dist/video/index.d.ts +66 -0
  81. package/dist/video/index.js +1938 -0
  82. package/package.json +311 -0
  83. package/photo/package.json +8 -0
  84. package/records/package.json +8 -0
  85. package/server/device-blocked.cjs +15 -0
  86. package/server/package.json +9 -0
  87. package/testing/package.json +8 -0
  88. package/testing/rn/package.json +8 -0
  89. package/video/package.json +8 -0
package/dist/index.js ADDED
@@ -0,0 +1,4464 @@
1
+ import { SafeAreaProvider, useSafeAreaInsets } from 'react-native-safe-area-context';
2
+ import { createContext, useContext, useSyncExternalStore, useMemo, createElement, useState, useEffect, useRef, useReducer, useLayoutEffect, useCallback } from 'react';
3
+ import { z } from 'zod';
4
+ import EventSource from 'react-native-sse';
5
+ import { useColorScheme, AccessibilityInfo, View, Text, StyleSheet, KeyboardAvoidingView, Platform, TextInput, Pressable, ActivityIndicator, ScrollView, Animated } from 'react-native';
6
+ import { jsx, jsxs } from 'react/jsx-runtime';
7
+
8
+ // src/client/text.ts
9
+ function hasLoneSurrogate(value) {
10
+ for (let i = 0; i < value.length; i += 1) {
11
+ const code = value.charCodeAt(i);
12
+ if (code >= 55296 && code <= 56319) {
13
+ const low = value.charCodeAt(i + 1);
14
+ if (!(low >= 56320 && low <= 57343)) return true;
15
+ i += 1;
16
+ } else if (code >= 56320 && code <= 57343) {
17
+ return true;
18
+ }
19
+ }
20
+ return false;
21
+ }
22
+ function serverLength(value) {
23
+ return [...value].length;
24
+ }
25
+
26
+ // src/client/errors/EverfurResult.ts
27
+ function ok(value, warning) {
28
+ return Object.freeze(
29
+ { ok: true, value }
30
+ );
31
+ }
32
+ function err(error) {
33
+ return Object.freeze({ ok: false, error });
34
+ }
35
+ function isOk(r) {
36
+ return r.ok;
37
+ }
38
+ function isErr(r) {
39
+ return !r.ok;
40
+ }
41
+ var EverfurThrownError = class _EverfurThrownError extends Error {
42
+ constructor(error) {
43
+ super(`${error.code}: ${error.displayMessage}`);
44
+ this.name = "EverfurThrownError";
45
+ this.error = error;
46
+ this.code = error.code;
47
+ this.category = error.category;
48
+ Object.setPrototypeOf(this, _EverfurThrownError.prototype);
49
+ }
50
+ };
51
+ function unwrap(r) {
52
+ if (r.ok) return r.value;
53
+ throw new EverfurThrownError(r.error);
54
+ }
55
+ var EverfurConfigError = class _EverfurConfigError extends Error {
56
+ constructor(kind, message) {
57
+ super(message);
58
+ this.name = "EverfurConfigError";
59
+ this.kind = kind;
60
+ Object.setPrototypeOf(this, _EverfurConfigError.prototype);
61
+ }
62
+ };
63
+
64
+ // src/client/ids.ts
65
+ var MAX_USER_REF_LEN = 128;
66
+ var MAX_PET_REF_LEN = 128;
67
+ var CONTROL_CHAR = /[\u0000-\u001F\u007F]/;
68
+ var UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
69
+ function petRef(raw) {
70
+ const v = raw;
71
+ const length = serverLength(v);
72
+ if (length === 0 || length > MAX_PET_REF_LEN) {
73
+ throw new EverfurConfigError(
74
+ "invalid-argument",
75
+ `petRef must be 1..${MAX_PET_REF_LEN} characters`
76
+ );
77
+ }
78
+ if (CONTROL_CHAR.test(v)) {
79
+ throw new EverfurConfigError("invalid-argument", "petRef must be printable (no control characters)");
80
+ }
81
+ return v;
82
+ }
83
+ function userRef(raw) {
84
+ const v = raw;
85
+ const length = serverLength(v);
86
+ if (length === 0 || length > MAX_USER_REF_LEN) {
87
+ throw new EverfurConfigError(
88
+ "invalid-argument",
89
+ `userRef must be 1..${MAX_USER_REF_LEN} characters`
90
+ );
91
+ }
92
+ if (v.includes("@")) {
93
+ throw new EverfurConfigError("invalid-argument", "userRef must not contain '@'");
94
+ }
95
+ if (CONTROL_CHAR.test(v)) {
96
+ throw new EverfurConfigError("invalid-argument", "userRef must be printable (no control characters)");
97
+ }
98
+ return v;
99
+ }
100
+ function conversationId(raw) {
101
+ if (!UUID_RE.test(raw)) {
102
+ throw new EverfurConfigError("invalid-argument", "conversationId must be a UUID");
103
+ }
104
+ return raw;
105
+ }
106
+ var CONTRACT_RETRYABILITY = Object.freeze([
107
+ Object.freeze({ wireCode: "AccessDeniedException", envelope: "http_envelope", httpStatus: 403, retryable: false }),
108
+ Object.freeze({ wireCode: "AuthorizationException", envelope: "http_envelope", httpStatus: 401, retryable: false }),
109
+ Object.freeze({ wireCode: "ConflictException", envelope: "http_envelope", httpStatus: 409, retryable: true }),
110
+ Object.freeze({ wireCode: "DAILY_QUOTA_EXCEEDED", envelope: "http_envelope", httpStatus: 429, retryable: true }),
111
+ Object.freeze({ wireCode: "IDEMPOTENCY_KEY_IN_FLIGHT", envelope: "http_envelope", httpStatus: 409, retryable: true }),
112
+ Object.freeze({ wireCode: "IDEMPOTENCY_KEY_REUSED_DIFFERENT_REQUEST", envelope: "http_envelope", httpStatus: 409, retryable: false }),
113
+ Object.freeze({ wireCode: "InternalFailureException", envelope: "http_envelope", httpStatus: 500, retryable: true }),
114
+ Object.freeze({ wireCode: "NotImplementedException", envelope: "http_envelope", httpStatus: 501, retryable: false }),
115
+ Object.freeze({ wireCode: "PaymentRequiredException", envelope: "http_envelope", httpStatus: 402, retryable: false }),
116
+ Object.freeze({ wireCode: "ResourceNotFoundException", envelope: "http_envelope", httpStatus: 404, retryable: false }),
117
+ Object.freeze({ wireCode: "ServiceUnavailableException", envelope: "http_envelope", httpStatus: 503, retryable: true }),
118
+ Object.freeze({ wireCode: "TIER_UPGRADE_REQUIRED", envelope: "http_envelope", httpStatus: 402, retryable: false }),
119
+ Object.freeze({ wireCode: "ThrottlingException", envelope: "http_envelope", httpStatus: 429, retryable: true }),
120
+ Object.freeze({ wireCode: "ValidationException", envelope: "http_envelope", httpStatus: 400, retryable: false }),
121
+ Object.freeze({ wireCode: "accessDenied", envelope: "http_envelope", httpStatus: 403, retryable: false }),
122
+ Object.freeze({ wireCode: "authExpired", envelope: "http_envelope", httpStatus: 401, retryable: true }),
123
+ Object.freeze({ wireCode: "internal_error", envelope: "sse_frame", httpStatus: 200, retryable: false }),
124
+ Object.freeze({ wireCode: "invalidRequest", envelope: "http_envelope", httpStatus: 400, retryable: false }),
125
+ Object.freeze({ wireCode: "not_found", envelope: "sse_frame", httpStatus: 200, retryable: false }),
126
+ Object.freeze({ wireCode: "session_required", envelope: "http_envelope", httpStatus: 403, retryable: false }),
127
+ Object.freeze({ wireCode: "timeout", envelope: "sse_frame", httpStatus: 200, retryable: true }),
128
+ Object.freeze({ wireCode: "unavailable", envelope: "http_envelope", httpStatus: 503, retryable: true })
129
+ ]);
130
+ Object.freeze(
131
+ CONTRACT_RETRYABILITY.map((row) => row.wireCode)
132
+ );
133
+
134
+ // src/client/errors/contract.ts
135
+ var NORMALIZED_FOLD = Object.freeze({
136
+ // the default status-mapped envelope
137
+ ValidationException: "validationFailed",
138
+ AuthorizationException: "authRejected",
139
+ PaymentRequiredException: "paymentRequired",
140
+ AccessDeniedException: "accessDenied",
141
+ ResourceNotFoundException: "resourceNotFound",
142
+ ConflictException: "conflict",
143
+ ThrottlingException: "rateLimited",
144
+ InternalFailureException: "internalError",
145
+ NotImplementedException: "notImplemented",
146
+ ServiceUnavailableException: "serviceUnavailable",
147
+ // dict-detail codes on the widget surface
148
+ authExpired: "authExpired",
149
+ unavailable: "serviceUnavailable",
150
+ session_required: "sessionRequired",
151
+ accessDenied: "accessDenied",
152
+ invalidRequest: "sdkUpdateRequired",
153
+ // typed codes
154
+ IDEMPOTENCY_KEY_IN_FLIGHT: "idempotencyInFlight",
155
+ IDEMPOTENCY_KEY_REUSED_DIFFERENT_REQUEST: "idempotencyConflict",
156
+ DAILY_QUOTA_EXCEEDED: "quotaExceeded",
157
+ TIER_UPGRADE_REQUIRED: "paymentRequired",
158
+ // SSE error frames
159
+ not_found: "conversationNotFound",
160
+ timeout: "streamTimeout",
161
+ internal_error: "internalError"
162
+ });
163
+ var CONTRACT_ERROR_ROWS = Object.freeze(
164
+ CONTRACT_RETRYABILITY.map(
165
+ (generated) => Object.freeze({
166
+ wireCode: generated.wireCode,
167
+ envelope: generated.envelope,
168
+ retryable: generated.retryable,
169
+ normalized: NORMALIZED_FOLD[generated.wireCode]
170
+ })
171
+ )
172
+ );
173
+ var BY_UPPER = new Map(
174
+ CONTRACT_ERROR_ROWS.map((r) => [r.wireCode.toUpperCase(), r])
175
+ );
176
+ function contractErrorFor(wireCode) {
177
+ if (typeof wireCode !== "string") return void 0;
178
+ const key = wireCode.trim().toUpperCase();
179
+ return key.length > 0 ? BY_UPPER.get(key) : void 0;
180
+ }
181
+ var CATEGORY_OF = Object.freeze({
182
+ // the caller's sign-in state is wrong and a credential change is the remedy
183
+ authExpired: "authentication",
184
+ authRejected: "authentication",
185
+ sessionRequired: "authentication",
186
+ // signed in, correctly identified, and still not allowed
187
+ accessDenied: "authorization",
188
+ // a plan gate, not a permission failure: the remedy is commercial
189
+ paymentRequired: "entitlement",
190
+ // slow down / come back later
191
+ quotaExceeded: "rateLimit",
192
+ rateLimited: "rateLimit",
193
+ // the request itself was wrong; retrying it unchanged can never succeed
194
+ validationFailed: "invalidRequest",
195
+ sdkUpdateRequired: "invalidRequest",
196
+ // the target is gone, hidden, or was never visible to this caller
197
+ conversationNotFound: "notFound",
198
+ petNotFound: "notFound",
199
+ resourceNotFound: "notFound",
200
+ // something else already holds the thing
201
+ conflict: "conflict",
202
+ idempotencyConflict: "conflict",
203
+ idempotencyInFlight: "conflict",
204
+ // the pipe, not the request: timeouts, drops, a briefly unreachable dependency
205
+ streamTimeout: "connection",
206
+ streamIncomplete: "connection",
207
+ upstreamLlmTimeout: "connection",
208
+ serviceUnavailable: "connection",
209
+ // the server admits fault
210
+ internalError: "server",
211
+ notImplemented: "server",
212
+ mediaUploadFailed: "media",
213
+ moderationBlocked: "policy",
214
+ unknown: "unknown"
215
+ });
216
+ function categoryFor(code) {
217
+ return CATEGORY_OF[code];
218
+ }
219
+ function fromWire(wire) {
220
+ const contractRow = contractErrorFor(wire);
221
+ if (contractRow) return contractRow.normalized;
222
+ const upper = (wire ?? "").trim().toUpperCase();
223
+ const canonical = upper.replace(/[^A-Z0-9]/g, "");
224
+ if (canonical === "AUTHREJECTED") return "authRejected";
225
+ if (upper.startsWith("AUTH")) return "authExpired";
226
+ switch (canonical) {
227
+ case "DAILYQUOTAEXCEEDED":
228
+ case "QUOTAEXCEEDED":
229
+ return "quotaExceeded";
230
+ case "RATELIMITED":
231
+ case "TOOMANYREQUESTS":
232
+ return "rateLimited";
233
+ case "IDEMPOTENCYKEYCONFLICT":
234
+ case "IDEMPOTENCYCONFLICT":
235
+ return "idempotencyConflict";
236
+ case "ACCESSDENIED":
237
+ case "FORBIDDEN":
238
+ return "accessDenied";
239
+ case "NOTFOUND":
240
+ case "CONVERSATIONNOTFOUND":
241
+ return "conversationNotFound";
242
+ case "PETNOTFOUND":
243
+ return "petNotFound";
244
+ case "TIMEOUT":
245
+ case "STREAMTIMEOUT":
246
+ return "streamTimeout";
247
+ // Analysis-domain deterministic 400s (NON-retryable). Additive per SPEC-00 §3.1 / SPEC-11b §2.6:
248
+ // fold to a NON-retried target so the SDK never retries a permanently-failing bad-input request.
249
+ // (Comment above the group so the empty fall-through cases stay lint-clean under no-fallthrough.)
250
+ case "MEDIAUPLOADFAILED":
251
+ case "UNRECOGNIZEDVIDEOFORMAT":
252
+ case "FILETOOSMALL":
253
+ return "mediaUploadFailed";
254
+ case "MODERATIONBLOCKED":
255
+ return "moderationBlocked";
256
+ case "UPSTREAMLLMTIMEOUT":
257
+ return "upstreamLlmTimeout";
258
+ case "INTERNALERROR":
259
+ case "INTERNALSERVERERROR":
260
+ return "internalError";
261
+ case "STREAMINCOMPLETE":
262
+ case "CHATSTREAMINCOMPLETE":
263
+ return "streamIncomplete";
264
+ // Deterministic 400s that can only come from an SDK bug -> unknown (NON-retryable). NEVER internalError
265
+ // (which IS auto-retried): mapping a bad-input 400 to a retryable code retries a request that never succeeds.
266
+ case "INVALIDANALYSISTYPE":
267
+ case "INVALIDUPLOADPURPOSE":
268
+ return "unknown";
269
+ default:
270
+ return "unknown";
271
+ }
272
+ }
273
+ function fromHttpStatus(status) {
274
+ if (status === 401) return "authExpired";
275
+ if (status === 403) return "accessDenied";
276
+ if (status === 404) return "conversationNotFound";
277
+ if (status === 409) return "idempotencyConflict";
278
+ if (status === 421) return "unknown";
279
+ if (status === 429) return "rateLimited";
280
+ if (status === 400 || status === 422) return "unknown";
281
+ if (status >= 500) return "internalError";
282
+ return "unknown";
283
+ }
284
+ var AUTO_RETRYABLE_CODES = /* @__PURE__ */ new Set([
285
+ "streamTimeout",
286
+ "rateLimited",
287
+ "internalError",
288
+ "upstreamLlmTimeout",
289
+ "streamIncomplete"
290
+ ]);
291
+ function isAutoRetryable(code) {
292
+ return AUTO_RETRYABLE_CODES.has(code);
293
+ }
294
+ var RETRYABLE_CONTRACT_CODES = /* @__PURE__ */ new Set([
295
+ "serviceUnavailable",
296
+ "conflict",
297
+ "idempotencyInFlight"
298
+ ]);
299
+ function isRetryableCode(code) {
300
+ return isAutoRetryable(code) || RETRYABLE_CONTRACT_CODES.has(code);
301
+ }
302
+ function shouldRetry(code, frameRetryable = false) {
303
+ return frameRetryable || isAutoRetryable(code);
304
+ }
305
+ var BACKOFF_BASE_MS = 500;
306
+ var BACKOFF_CAP_MS = 8e3;
307
+ var MAX_RETRY_ATTEMPTS = 4;
308
+ function backoffDelayMs(attempt, rng = Math.random) {
309
+ const bounded = Math.max(0, attempt);
310
+ const ceiling = Math.min(BACKOFF_BASE_MS * 2 ** bounded, BACKOFF_CAP_MS);
311
+ return Math.floor(rng() * ceiling);
312
+ }
313
+ function canRecreateOnNotFound(code) {
314
+ return code === "conversationNotFound";
315
+ }
316
+
317
+ // src/client/errors/EverfurError.ts
318
+ var USER_FACING_COPY = Object.freeze({
319
+ authExpired: "Please sign in again to continue.",
320
+ authRejected: "Please sign in again to continue.",
321
+ sessionRequired: "This app needs to be updated to keep using Everfur.",
322
+ accessDenied: "This feature isn't available on your account right now.",
323
+ paymentRequired: "This is part of a paid plan.",
324
+ quotaExceeded: "You have used today's messages. This resets tomorrow.",
325
+ rateLimited: "You are sending messages quickly. Try again in a few seconds.",
326
+ validationFailed: "Something in that request was not right. Check the details and try again.",
327
+ sdkUpdateRequired: "This app needs to be updated to keep using Everfur.",
328
+ conflict: "That is already running. Wait for it to finish, then try again.",
329
+ idempotencyConflict: "That message was already delivered.",
330
+ idempotencyInFlight: "That is still processing. Give it a moment.",
331
+ conversationNotFound: "This conversation is no longer available.",
332
+ petNotFound: "We could not find that pet. Please pick a pet and try again.",
333
+ resourceNotFound: "We could not find that.",
334
+ streamTimeout: "The response timed out. Tap retry to try again.",
335
+ mediaUploadFailed: "We could not upload that photo. Please attach it again.",
336
+ moderationBlocked: "This request cannot be answered here.",
337
+ upstreamLlmTimeout: "The response timed out. Tap retry to try again.",
338
+ internalError: "We hit a snag on our end. Please try again.",
339
+ notImplemented: "That is not available yet.",
340
+ serviceUnavailable: "That service is briefly unavailable. Try again shortly.",
341
+ streamIncomplete: "The connection dropped mid-answer. Tap retry to continue.",
342
+ unknown: "Something went wrong. Please try again."
343
+ });
344
+ function userFacingError(code) {
345
+ return USER_FACING_COPY[code];
346
+ }
347
+ function defineHidden(target, key, value) {
348
+ Object.defineProperty(target, key, {
349
+ value,
350
+ enumerable: false,
351
+ writable: false,
352
+ configurable: false
353
+ });
354
+ }
355
+ function makeEverfurError(code, opts) {
356
+ contractErrorFor(opts?.wireCode);
357
+ const error = {
358
+ code,
359
+ category: categoryFor(code),
360
+ retryable: opts?.retryable ?? isRetryableCode(code),
361
+ displayMessage: userFacingError(code)
362
+ };
363
+ if (opts?.httpStatus !== void 0) error.httpStatus = opts.httpStatus;
364
+ if (opts?.requestId) error.requestId = opts.requestId;
365
+ if (opts?.wireMessage) defineHidden(error, "wireMessage", opts.wireMessage);
366
+ if (opts?.raw !== void 0 && opts.raw !== null) defineHidden(error, "raw", opts.raw);
367
+ return Object.freeze(error);
368
+ }
369
+
370
+ // src/core/ports/TelemetryPort.ts
371
+ var noopTelemetry = Object.freeze({
372
+ track() {
373
+ },
374
+ trackExpectedFailure() {
375
+ }
376
+ });
377
+
378
+ // src/core/ports/ErrorPolicyPort.ts
379
+ var defaultErrorPolicy = Object.freeze({
380
+ shouldRetry(code, attempt) {
381
+ return isAutoRetryable(code) && attempt < MAX_RETRY_ATTEMPTS;
382
+ },
383
+ maxAttempts() {
384
+ return MAX_RETRY_ATTEMPTS;
385
+ }
386
+ });
387
+
388
+ // src/core/ports/CameraPort.ts
389
+ var unavailableCamera = Object.freeze({
390
+ isAvailable: false,
391
+ async capture() {
392
+ return Promise.reject(
393
+ new Error("CameraPort is unavailable; check isAvailable before calling capture")
394
+ );
395
+ }
396
+ });
397
+
398
+ // src/client/protocol/frames.ts
399
+ function assertNever(x) {
400
+ throw new Error(
401
+ `assertNever: unhandled discriminated-union member ${JSON.stringify(x)}`
402
+ );
403
+ }
404
+ function acceptedFrame(streamId, lastEventId, serverRequestId = null) {
405
+ return Object.freeze({ kind: "accepted", streamId, lastEventId, serverRequestId, terminal: false });
406
+ }
407
+ function heartbeatFrame(lastEventId, serverRequestId = null) {
408
+ return Object.freeze({ kind: "heartbeat", lastEventId, serverRequestId, terminal: false });
409
+ }
410
+ function deltaFrame(delta, lastEventId, serverRequestId = null) {
411
+ return Object.freeze({ kind: "delta", delta, lastEventId, serverRequestId, terminal: false });
412
+ }
413
+ function doneFrame(fields, serverRequestId = null) {
414
+ return Object.freeze({
415
+ kind: "done",
416
+ terminal: true,
417
+ conversationId: fields.conversationId,
418
+ messageId: fields.messageId,
419
+ title: fields.title,
420
+ followUpQuestions: Object.freeze([...fields.followUpQuestions]),
421
+ citations: Object.freeze([...fields.citations]),
422
+ citationStatus: fields.citationStatus,
423
+ urgencyLevel: fields.urgencyLevel,
424
+ urgencyReason: fields.urgencyReason,
425
+ resultId: fields.resultId,
426
+ lastEventId: fields.lastEventId,
427
+ serverRequestId
428
+ });
429
+ }
430
+ function errorFrame(fields) {
431
+ return Object.freeze({
432
+ kind: "error",
433
+ terminal: true,
434
+ code: fields.code,
435
+ retryable: fields.retryable,
436
+ wireMessage: fields.wireMessage,
437
+ synthesized: fields.synthesized,
438
+ lastEventId: fields.lastEventId,
439
+ serverRequestId: fields.serverRequestId ?? null
440
+ });
441
+ }
442
+ function analysisStartedFrame(requestId, lastEventId, serverRequestId = null) {
443
+ return Object.freeze({
444
+ kind: "analysisStarted",
445
+ requestId,
446
+ lastEventId,
447
+ serverRequestId,
448
+ terminal: false
449
+ });
450
+ }
451
+ function analysisCompleteFrame(fields, serverRequestId = null) {
452
+ return Object.freeze({
453
+ kind: "analysisComplete",
454
+ terminal: false,
455
+ resultId: fields.resultId,
456
+ analysisType: fields.analysisType,
457
+ modelVersion: fields.modelVersion,
458
+ confidence: fields.confidence,
459
+ detections: Object.freeze([...fields.detections]),
460
+ interpretation: fields.interpretation,
461
+ lastEventId: fields.lastEventId,
462
+ serverRequestId
463
+ });
464
+ }
465
+ function unknownFrame(raw, lastEventId, serverRequestId = null) {
466
+ return Object.freeze({
467
+ kind: "unknown",
468
+ raw: { ...raw },
469
+ lastEventId,
470
+ serverRequestId,
471
+ terminal: false
472
+ });
473
+ }
474
+
475
+ // src/client/identity.ts
476
+ function createIdentityProvider(userRef2, getToken) {
477
+ let cached = null;
478
+ let inFlight = null;
479
+ let revoked = false;
480
+ const load = () => {
481
+ if (inFlight) return inFlight;
482
+ inFlight = (async () => {
483
+ try {
484
+ const token = await getToken();
485
+ if (typeof token !== "string" || token.length === 0) {
486
+ throw new EverfurConfigError("invalid-argument", "TokenProvider returned an empty token");
487
+ }
488
+ cached = token;
489
+ return token;
490
+ } finally {
491
+ inFlight = null;
492
+ }
493
+ })();
494
+ return inFlight;
495
+ };
496
+ return {
497
+ userRef: userRef2,
498
+ async currentToken(opts) {
499
+ if (revoked) {
500
+ throw new EverfurConfigError("not-initialized", "This identity was cleared (sign-out); mint a new one.");
501
+ }
502
+ if (opts?.forceRefresh) cached = null;
503
+ if (cached !== null) return cached;
504
+ return load();
505
+ },
506
+ hasToken() {
507
+ return !revoked && cached !== null;
508
+ },
509
+ clear() {
510
+ revoked = true;
511
+ cached = null;
512
+ }
513
+ };
514
+ }
515
+ function newSessionId() {
516
+ const bytes = new Uint8Array(16);
517
+ const cryptoObj = globalThis.crypto;
518
+ if (typeof cryptoObj?.getRandomValues === "function") {
519
+ cryptoObj.getRandomValues(bytes);
520
+ } else {
521
+ for (let i = 0; i < bytes.length; i += 1) bytes[i] = Math.floor(Math.random() * 256);
522
+ }
523
+ bytes[6] = bytes[6] & 15 | 64;
524
+ bytes[8] = bytes[8] & 63 | 128;
525
+ const hex = [];
526
+ for (let i = 0; i < bytes.length; i += 1) hex.push(bytes[i].toString(16).padStart(2, "0"));
527
+ return hex.slice(0, 4).join("") + "-" + hex.slice(4, 6).join("") + "-" + hex.slice(6, 8).join("") + "-" + hex.slice(8, 10).join("") + "-" + hex.slice(10, 16).join("");
528
+ }
529
+ function authHeaders(auth) {
530
+ const headers = {};
531
+ if (auth.mode === "personalized") {
532
+ headers.authorization = `Bearer ${auth.token}`;
533
+ } else {
534
+ headers["x-everfur-partner-key"] = auth.publishableKey;
535
+ }
536
+ if (auth.userRef) headers["x-everfur-user-ref"] = auth.userRef;
537
+ if (auth.sessionId) headers["x-everfur-session-id"] = auth.sessionId;
538
+ return headers;
539
+ }
540
+ function withAuthHeaders(req, auth) {
541
+ return { ...req, headers: { ...stripAuthHeaders(req.headers), ...authHeaders(auth) } };
542
+ }
543
+ function stripAuthHeaders(headers) {
544
+ if (!headers) return {};
545
+ const out = {};
546
+ for (const [key, value] of Object.entries(headers)) {
547
+ const lower = key.toLowerCase();
548
+ if (lower === "authorization" || lower === "x-everfur-partner-key") continue;
549
+ out[key] = value;
550
+ }
551
+ return out;
552
+ }
553
+ async function authedSend(req, ctx) {
554
+ if (ctx.mode === "anonymous") {
555
+ return ctx.transport.request(
556
+ withAuthHeaders(req, {
557
+ mode: "anonymous",
558
+ publishableKey: ctx.publishableKey,
559
+ userRef: ctx.userRef,
560
+ ...ctx.sessionId ? { sessionId: ctx.sessionId } : {}
561
+ })
562
+ );
563
+ }
564
+ let token;
565
+ try {
566
+ token = await ctx.identity.currentToken();
567
+ } catch {
568
+ return err(authRejectedError());
569
+ }
570
+ const first = await ctx.transport.request(
571
+ withAuthHeaders(req, {
572
+ mode: "personalized",
573
+ token,
574
+ userRef: ctx.userRef,
575
+ ...ctx.sessionId ? { sessionId: ctx.sessionId } : {}
576
+ })
577
+ );
578
+ if (first.ok || first.error.httpStatus !== 401) return first;
579
+ let refreshed;
580
+ try {
581
+ refreshed = await ctx.identity.currentToken({ forceRefresh: true });
582
+ } catch {
583
+ return err(authRejectedError());
584
+ }
585
+ const retry = await ctx.transport.request(
586
+ withAuthHeaders(req, {
587
+ mode: "personalized",
588
+ token: refreshed,
589
+ userRef: ctx.userRef,
590
+ ...ctx.sessionId ? { sessionId: ctx.sessionId } : {}
591
+ })
592
+ );
593
+ if (!retry.ok && retry.error.httpStatus === 401) {
594
+ return err(authRejectedError(retry.error.httpStatus));
595
+ }
596
+ return retry;
597
+ }
598
+ function authRejectedError(httpStatus) {
599
+ return makeEverfurError("authRejected", {
600
+ retryable: false,
601
+ ...httpStatus !== void 0 ? { httpStatus } : {}
602
+ });
603
+ }
604
+ var BLOCK_SEPARATOR = "\n\n";
605
+ var MAX_PENDING_BLOCK_CHARS = 1048576;
606
+ var wireObjectSchema = z.record(z.string(), z.unknown());
607
+ var URGENCY_LEVELS = ["emergency", "schedule_soon", "home_care"];
608
+ async function* parseSse(bytes, serverRequestId = null) {
609
+ let resolvedRequestId = null;
610
+ const requestIdNow = () => {
611
+ if (resolvedRequestId !== null) return resolvedRequestId;
612
+ resolvedRequestId = typeof serverRequestId === "function" ? serverRequestId() : serverRequestId;
613
+ return resolvedRequestId;
614
+ };
615
+ const decoder = new TextDecoder("utf-8");
616
+ let buffer = "";
617
+ let scanFrom = 0;
618
+ let sawDelta = false;
619
+ for await (const chunk of bytes) {
620
+ buffer += decoder.decode(chunk, { stream: true });
621
+ for (; ; ) {
622
+ const sep = buffer.indexOf(BLOCK_SEPARATOR, scanFrom);
623
+ if (sep === -1) break;
624
+ const block = buffer.slice(0, sep);
625
+ buffer = buffer.slice(sep + BLOCK_SEPARATOR.length);
626
+ scanFrom = 0;
627
+ const frame = parseBlock(block, requestIdNow());
628
+ if (frame === null) continue;
629
+ if (frame.kind === "delta") sawDelta = true;
630
+ yield frame;
631
+ if (frame.terminal) return;
632
+ }
633
+ scanFrom = buffer.length > 0 ? buffer.length - 1 : 0;
634
+ if (buffer.length > MAX_PENDING_BLOCK_CHARS) {
635
+ yield errorFrame({
636
+ code: sawDelta ? "CHAT_STREAM_INCOMPLETE" : "internal_error",
637
+ retryable: true,
638
+ wireMessage: null,
639
+ synthesized: true,
640
+ lastEventId: null,
641
+ serverRequestId: requestIdNow()
642
+ });
643
+ return;
644
+ }
645
+ }
646
+ buffer += decoder.decode();
647
+ if (buffer.trim().length > 0) {
648
+ const frame = parseBlock(buffer, requestIdNow());
649
+ if (frame !== null) {
650
+ if (frame.kind === "delta") sawDelta = true;
651
+ yield frame;
652
+ if (frame.terminal) return;
653
+ }
654
+ }
655
+ yield errorFrame({
656
+ code: sawDelta ? "CHAT_STREAM_INCOMPLETE" : "internal_error",
657
+ retryable: true,
658
+ wireMessage: null,
659
+ synthesized: true,
660
+ lastEventId: null,
661
+ serverRequestId: requestIdNow()
662
+ });
663
+ }
664
+ function parseBlock(block, serverRequestId) {
665
+ let id = null;
666
+ const dataLines = [];
667
+ for (const rawLine of block.split("\n")) {
668
+ const line = rawLine.replace(/\s+$/, "");
669
+ if (line.length === 0 || line.startsWith(":")) continue;
670
+ if (line.startsWith("id:")) {
671
+ id = line.slice(3).trim();
672
+ } else if (line.startsWith("data:")) {
673
+ dataLines.push(line.slice(5).replace(/^ /, ""));
674
+ }
675
+ }
676
+ if (dataLines.length === 0) return null;
677
+ let decoded;
678
+ try {
679
+ decoded = JSON.parse(dataLines.join("\n"));
680
+ } catch {
681
+ return null;
682
+ }
683
+ if (typeof decoded !== "object" || decoded === null || Array.isArray(decoded)) return null;
684
+ const parsed = wireObjectSchema.safeParse(decoded);
685
+ if (!parsed.success) return null;
686
+ return frameFromWire(parsed.data, id, serverRequestId);
687
+ }
688
+ function frameFromWire(json, lastEventId, serverRequestId) {
689
+ const type = json["type"];
690
+ const event = json["event"];
691
+ if (type === "error" || "error" in json) {
692
+ return errorFrame({
693
+ code: asString(json["code"]) ?? "unknown",
694
+ retryable: json["retryable"] === true,
695
+ wireMessage: asString(json["error"]),
696
+ synthesized: false,
697
+ lastEventId,
698
+ serverRequestId
699
+ });
700
+ }
701
+ if (type === "done" || json["done"] === true) {
702
+ return doneFrame({
703
+ conversationId: asString(json["conversation_id"]) ?? "",
704
+ messageId: asString(json["message_id"]),
705
+ title: asString(json["title"]),
706
+ followUpQuestions: asStringList(json["follow_up_questions"]),
707
+ citations: asMapList(json["citations"]),
708
+ citationStatus: asString(json["citation_status"]),
709
+ urgencyLevel: asUrgency(json["urgency_level"]),
710
+ urgencyReason: asString(json["urgency_reason"]),
711
+ resultId: asString(json["result_id"]),
712
+ lastEventId
713
+ }, serverRequestId);
714
+ }
715
+ if (type === "accepted" || json["status"] === "reasoning") {
716
+ return acceptedFrame(asString(json["stream_id"]), lastEventId, serverRequestId);
717
+ }
718
+ if (type === "heartbeat" || json["heartbeat"] === true) {
719
+ return heartbeatFrame(lastEventId, serverRequestId);
720
+ }
721
+ if (type === "text.delta" || "delta" in json || "token" in json) {
722
+ const delta = asString(json["delta"]) ?? asString(json["token"]) ?? "";
723
+ return deltaFrame(delta, lastEventId, serverRequestId);
724
+ }
725
+ if (event === "analysis_started") {
726
+ return analysisStartedFrame(asString(json["request_id"]), lastEventId, serverRequestId);
727
+ }
728
+ if (event === "analysis_complete") {
729
+ return analysisCompleteFrame({
730
+ resultId: asString(json["result_id"]),
731
+ analysisType: asString(json["analysis_type"]),
732
+ modelVersion: asString(json["model_version"]),
733
+ confidence: asNumber(json["confidence"]),
734
+ detections: asMapList(json["detections"]),
735
+ interpretation: asString(json["interpretation"]),
736
+ lastEventId
737
+ }, serverRequestId);
738
+ }
739
+ return unknownFrame(json, lastEventId, serverRequestId);
740
+ }
741
+ function asString(v) {
742
+ return typeof v === "string" ? v : null;
743
+ }
744
+ function asNumber(v) {
745
+ return typeof v === "number" && Number.isFinite(v) ? v : null;
746
+ }
747
+ function asUrgency(v) {
748
+ return typeof v === "string" && URGENCY_LEVELS.includes(v) ? v : null;
749
+ }
750
+ function asStringList(v) {
751
+ if (!Array.isArray(v)) return [];
752
+ return v.map((e) => typeof e === "string" ? e : String(e));
753
+ }
754
+ function isPlainObject(v) {
755
+ return typeof v === "object" && v !== null && !Array.isArray(v);
756
+ }
757
+ function asMapList(v) {
758
+ if (!Array.isArray(v)) return [];
759
+ return v.filter(isPlainObject);
760
+ }
761
+
762
+ // src/client/config.ts
763
+ var SDK_VERSION = "0.1.0";
764
+ var SDK_PLATFORM = "react-native";
765
+ var DEFAULT_CONTRACT_VERSION = "2026-08-01";
766
+ var ENV_API_BASE_URL = "EVERFUR_API_BASE_URL";
767
+ function configFailure(reason, message) {
768
+ return Object.freeze({ ok: false, failure: Object.freeze({ reason, message }) });
769
+ }
770
+ function checkPublishableKey(raw) {
771
+ const publishableKey = typeof raw === "string" ? raw.trim() : "";
772
+ if (publishableKey.length === 0) {
773
+ return { reason: "missing-publishable-key", message: "publishableKey is required" };
774
+ }
775
+ if (/^sk[_-]/i.test(publishableKey)) {
776
+ return {
777
+ reason: "secret-key-as-publishable-key",
778
+ message: "publishableKey looks like a SECRET key (sk_...). A device must never hold a partner secret key: use the pk_ publishable key here, and keep the secret key on your server."
779
+ };
780
+ }
781
+ return null;
782
+ }
783
+ function tryResolveClientConfig(config) {
784
+ const keyFailure = checkPublishableKey(config?.publishableKey);
785
+ if (keyFailure !== null) {
786
+ return Object.freeze({ ok: false, failure: keyFailure });
787
+ }
788
+ const publishableKey = config.publishableKey.trim();
789
+ const baseUrl = tryResolveApiBaseUrl(config.apiBaseUrl);
790
+ if (!baseUrl.ok) {
791
+ return baseUrl;
792
+ }
793
+ const contractVersion = config.contractVersion?.trim() || DEFAULT_CONTRACT_VERSION;
794
+ return Object.freeze({
795
+ ok: true,
796
+ config: Object.freeze({
797
+ publishableKey,
798
+ apiBaseUrl: baseUrl.value,
799
+ contractVersion,
800
+ sdkVersion: SDK_VERSION,
801
+ platform: SDK_PLATFORM,
802
+ debug: config.debug === true
803
+ })
804
+ });
805
+ }
806
+ function tryResolveApiBaseUrl(apiBaseUrl) {
807
+ const explicit = apiBaseUrl?.trim();
808
+ const candidate = explicit && explicit.length > 0 ? explicit : readEnv(ENV_API_BASE_URL);
809
+ if (!candidate) {
810
+ return configFailure(
811
+ "missing-api-base-url",
812
+ `apiBaseUrl is required: pass config.apiBaseUrl or set ${ENV_API_BASE_URL}. The SDK never ships a hardcoded host.`
813
+ );
814
+ }
815
+ return normalizeBaseUrl(candidate);
816
+ }
817
+ function buildBaseHeaders(cfg) {
818
+ return {
819
+ "X-Everfur-SDK-Version": cfg.sdkVersion,
820
+ "X-Everfur-SDK-Platform": cfg.platform,
821
+ "X-Everfur-Contract": cfg.contractVersion
822
+ };
823
+ }
824
+ var ABSOLUTE_URL = /^([A-Za-z][A-Za-z0-9+.-]*):\/\/([^/?#]*)/;
825
+ function hostOf(authority) {
826
+ const afterUserinfo = authority.slice(authority.lastIndexOf("@") + 1);
827
+ return afterUserinfo.replace(/:\d+$/, "").toLowerCase();
828
+ }
829
+ function isPrintableHost(host) {
830
+ if (host.length === 0) return false;
831
+ if (host.includes("@")) return false;
832
+ if (host.startsWith("[") && host.endsWith("]")) return true;
833
+ return !host.includes(":");
834
+ }
835
+ function canEchoOrigin(rawTrimmed, host) {
836
+ const schemeEnd = rawTrimmed.indexOf("://");
837
+ if (schemeEnd < 0) return false;
838
+ if (rawTrimmed.slice(schemeEnd + 3).includes("@")) return false;
839
+ return isPrintableHost(host);
840
+ }
841
+ function safeOrigin(scheme, host) {
842
+ return `${scheme}://${host}`;
843
+ }
844
+ function normalizeBaseUrl(raw) {
845
+ const trimmed = raw.trim();
846
+ const match = ABSOLUTE_URL.exec(trimmed);
847
+ if (match === null || match[2] === void 0 || match[2].length === 0) {
848
+ return configFailure("malformed-api-base-url", "apiBaseUrl is not a valid absolute URL");
849
+ }
850
+ const scheme = (match[1] ?? "").toLowerCase();
851
+ const host = hostOf(match[2]);
852
+ if (host.length === 0) {
853
+ return configFailure("malformed-api-base-url", "apiBaseUrl is not a valid absolute URL");
854
+ }
855
+ const shown = canEchoOrigin(trimmed, host) ? `: ${safeOrigin(scheme, host)}` : "";
856
+ if (scheme === "https") ; else if (scheme === "http" && isLoopbackHost(host)) ; else if (scheme === "http") {
857
+ return configFailure(
858
+ "insecure-api-base-url",
859
+ `apiBaseUrl must use https (cleartext http is only allowed for localhost)${shown}`
860
+ );
861
+ } else {
862
+ return configFailure("unsupported-api-base-url-scheme", `apiBaseUrl must be http(s)${shown}`);
863
+ }
864
+ const value = trimmed.endsWith("/") ? trimmed.slice(0, -1) : trimmed;
865
+ return Object.freeze({ ok: true, value });
866
+ }
867
+ function isLoopbackHost(hostname) {
868
+ const host = hostname.toLowerCase();
869
+ return host === "localhost" || host === "127.0.0.1" || host === "[::1]" || host === "::1";
870
+ }
871
+ function readEnv(name) {
872
+ const g = globalThis;
873
+ const value = g.process?.env?.[name];
874
+ return typeof value === "string" && value.trim().length > 0 ? value.trim() : void 0;
875
+ }
876
+
877
+ // src/client/transport.ts
878
+ var UNARY_TIMEOUT_MS = 3e4;
879
+ var REQUEST_ID_HEADER = "x-request-id";
880
+ async function* fetchByteSource(body) {
881
+ if (!body) return;
882
+ const reader = body.getReader();
883
+ try {
884
+ for (; ; ) {
885
+ const { done, value } = await reader.read();
886
+ if (done) break;
887
+ if (value && value.length > 0) yield value;
888
+ }
889
+ } finally {
890
+ await reader.cancel?.();
891
+ }
892
+ }
893
+ function eventSourceByteSource(es) {
894
+ const enc = new TextEncoder();
895
+ const queue = createByteQueue();
896
+ let cleaned = false;
897
+ const onMessage = (ev) => {
898
+ let block = "";
899
+ if (ev.lastEventId) block += `id: ${ev.lastEventId}
900
+ `;
901
+ const data = ev.data ?? "";
902
+ for (const line of data.split("\n")) block += `data: ${line}
903
+ `;
904
+ block += "\n";
905
+ queue.push(enc.encode(block));
906
+ };
907
+ const onDone = () => {
908
+ cleanup();
909
+ queue.end();
910
+ };
911
+ const onError = (ev) => {
912
+ const status = typeof ev.xhrStatus === "number" ? ev.xhrStatus : 0;
913
+ if (status >= 400) {
914
+ const wireCode = statusToWireCode(status);
915
+ const retryable = isAutoRetryable(fromWire(wireCode));
916
+ queue.push(enc.encode(`data: ${JSON.stringify({ type: "error", code: wireCode, retryable })}
917
+
918
+ `));
919
+ }
920
+ cleanup();
921
+ queue.end();
922
+ };
923
+ es.addEventListener("message", onMessage);
924
+ es.addEventListener("done", onDone);
925
+ es.addEventListener("error", onError);
926
+ function cleanup() {
927
+ if (cleaned) return;
928
+ cleaned = true;
929
+ es.removeEventListener("message", onMessage);
930
+ es.removeEventListener("done", onDone);
931
+ es.removeEventListener("error", onError);
932
+ try {
933
+ es.close();
934
+ } catch {
935
+ }
936
+ }
937
+ return sourceWithCleanup(queue.source, cleanup);
938
+ }
939
+ async function* sourceWithCleanup(source, cleanup) {
940
+ try {
941
+ yield* source;
942
+ } finally {
943
+ cleanup();
944
+ }
945
+ }
946
+ function createByteQueue() {
947
+ const buffer = [];
948
+ let done = false;
949
+ let wake = null;
950
+ const signal = () => {
951
+ if (wake) {
952
+ const fn = wake;
953
+ wake = null;
954
+ fn();
955
+ }
956
+ };
957
+ async function* gen() {
958
+ for (; ; ) {
959
+ const next = buffer.shift();
960
+ if (next !== void 0) {
961
+ yield next;
962
+ continue;
963
+ }
964
+ if (done) return;
965
+ await new Promise((resolve) => {
966
+ wake = resolve;
967
+ });
968
+ }
969
+ }
970
+ return {
971
+ source: gen(),
972
+ push: (u) => {
973
+ buffer.push(u);
974
+ signal();
975
+ },
976
+ end: () => {
977
+ done = true;
978
+ signal();
979
+ }
980
+ };
981
+ }
982
+ async function requestJson(req, deps) {
983
+ const fetchImpl = deps.fetchImpl ?? getGlobalFetch();
984
+ const url = buildUrl(deps.config.apiBaseUrl, req.path, req.query);
985
+ const headers = mergeHeaders(deps.config, req.headers, "application/json", req.body !== void 0 && req.multipart === void 0);
986
+ const deadline2 = timeoutSignal(UNARY_TIMEOUT_MS);
987
+ const signal = mergeAbortSignals(deadline2.signal, req.signal);
988
+ let res;
989
+ try {
990
+ res = await fetchImpl(url, buildInit({ ...req, signal }, headers));
991
+ } catch (cause) {
992
+ return err(networkError(cause));
993
+ } finally {
994
+ deadline2.cancel();
995
+ }
996
+ const bodyJson = await safeJson(res);
997
+ if (!res.ok) return err(errorFromResponse(res.status, bodyJson, requestIdOf(res)));
998
+ return ok(bodyJson);
999
+ }
1000
+ function createHttpTransport(deps) {
1001
+ return {
1002
+ request: (req) => requestJson(req, deps),
1003
+ stream: (req, signal) => streamFrames(withSignal(req, signal), deps)
1004
+ };
1005
+ }
1006
+ async function* streamFrames(req, deps) {
1007
+ const url = buildUrl(deps.config.apiBaseUrl, req.path, req.query);
1008
+ const headers = mergeHeaders(deps.config, req.headers, "text/event-stream", req.body !== void 0 && req.multipart === void 0);
1009
+ if (deps.eventSourceFactory) {
1010
+ const es = deps.eventSourceFactory(url, buildEventSourceInit(req, headers));
1011
+ yield* parseSse(eventSourceByteSource(es), () => eventSourceRequestId(es));
1012
+ return;
1013
+ }
1014
+ const fetchImpl = deps.fetchImpl ?? getGlobalFetch();
1015
+ let res;
1016
+ try {
1017
+ res = await fetchImpl(url, buildInit(req, headers));
1018
+ } catch (cause) {
1019
+ yield syntheticErrorFrame("", true, describeCause(cause));
1020
+ return;
1021
+ }
1022
+ const requestId = requestIdOf(res);
1023
+ if (!res.ok) {
1024
+ const body = await safeJson(res);
1025
+ const wireCode = extractWireCode(body) ?? statusToWireCode(res.status);
1026
+ const retryable = extractRetryable(body) || isAutoRetryable(fromWire(wireCode));
1027
+ yield syntheticErrorFrame(wireCode, retryable, extractWireMessage(body), requestId);
1028
+ return;
1029
+ }
1030
+ if (res.body) {
1031
+ yield* parseSse(fetchByteSource(res.body), requestId);
1032
+ return;
1033
+ }
1034
+ yield* parseSse(fetchByteSource(null), requestId);
1035
+ }
1036
+ function buildEventSourceInit(req, headers) {
1037
+ return {
1038
+ method: req.method,
1039
+ headers,
1040
+ pollingInterval: 0,
1041
+ ...req.body !== void 0 ? { body: JSON.stringify(req.body) } : {}
1042
+ };
1043
+ }
1044
+ function errorFromResponse(status, body, requestId) {
1045
+ const wireCode = extractWireCode(body);
1046
+ const code = wireCode ? fromWire(wireCode) : fromHttpStatus(status);
1047
+ const wireMessage = extractWireMessage(body);
1048
+ return makeEverfurError(code, {
1049
+ httpStatus: status,
1050
+ ...extractRetryable(body) ? { retryable: true } : {},
1051
+ ...requestId ? { requestId } : {},
1052
+ ...wireCode ? { wireCode } : {},
1053
+ ...wireMessage ? { wireMessage } : {},
1054
+ ...body !== null && body !== void 0 ? { raw: body } : {}
1055
+ });
1056
+ }
1057
+ function networkError(cause) {
1058
+ return makeEverfurError("internalError", { retryable: true, wireMessage: describeCause(cause) });
1059
+ }
1060
+ function requestIdOf(res) {
1061
+ const value = res.headers.get(REQUEST_ID_HEADER);
1062
+ return typeof value === "string" && value.length > 0 ? value : null;
1063
+ }
1064
+ function eventSourceRequestId(es) {
1065
+ if (typeof es.getResponseHeader !== "function") return null;
1066
+ let value;
1067
+ try {
1068
+ value = es.getResponseHeader(REQUEST_ID_HEADER);
1069
+ } catch {
1070
+ return null;
1071
+ }
1072
+ return typeof value === "string" && value.length > 0 ? value : null;
1073
+ }
1074
+ function statusToWireCode(status) {
1075
+ if (status === 401) return "AUTH_EXPIRED";
1076
+ if (status === 403) return "ACCESS_DENIED";
1077
+ if (status === 404) return "NOT_FOUND";
1078
+ if (status === 409) return "IDEMPOTENCY_CONFLICT";
1079
+ if (status === 421) return "MISDIRECTED_REQUEST";
1080
+ if (status === 429) return "RATE_LIMITED";
1081
+ if (status === 400 || status === 422) return "INVALID_REQUEST";
1082
+ if (status === 503) return "INTERNAL_ERROR";
1083
+ if (status >= 500) return "INTERNAL_ERROR";
1084
+ return "";
1085
+ }
1086
+ function syntheticErrorFrame(code, retryable, wireMessage, serverRequestId = null) {
1087
+ return errorFrame({ code, retryable, wireMessage, synthesized: true, lastEventId: null, serverRequestId });
1088
+ }
1089
+ function getGlobalFetch() {
1090
+ const candidate = globalThis.fetch;
1091
+ if (typeof candidate !== "function") {
1092
+ throw new EverfurConfigError(
1093
+ "missing-peer-dependency",
1094
+ "global fetch is unavailable; provide config.transport or an injected fetch implementation"
1095
+ );
1096
+ }
1097
+ return candidate;
1098
+ }
1099
+ function buildUrl(base, path, query) {
1100
+ const rel = path.startsWith("/") ? path : `/${path}`;
1101
+ let url = `${base}${rel}`;
1102
+ if (query) {
1103
+ const qs = Object.entries(query).filter((entry) => entry[1] !== void 0).map(([k, v]) => `${encodeURIComponent(k)}=${encodeURIComponent(String(v))}`).join("&");
1104
+ if (qs) url += `?${qs}`;
1105
+ }
1106
+ return url;
1107
+ }
1108
+ function mergeHeaders(config, reqHeaders, accept, hasJsonBody) {
1109
+ const headers = { ...buildBaseHeaders(config), accept };
1110
+ if (hasJsonBody) headers["content-type"] = "application/json";
1111
+ if (reqHeaders) Object.assign(headers, reqHeaders);
1112
+ return headers;
1113
+ }
1114
+ function buildInit(req, headers) {
1115
+ const init = { method: req.method, headers };
1116
+ if (req.multipart !== void 0) init.body = req.multipart;
1117
+ else if (req.body !== void 0) init.body = JSON.stringify(req.body);
1118
+ if (req.signal) init.signal = req.signal;
1119
+ return init;
1120
+ }
1121
+ function withSignal(req, signal) {
1122
+ return req.signal ? req : { ...req, signal };
1123
+ }
1124
+ function timeoutSignal(ms) {
1125
+ const ctrl = new AbortController();
1126
+ const handle = setTimeout(() => ctrl.abort(), ms);
1127
+ return {
1128
+ signal: ctrl.signal,
1129
+ cancel: () => clearTimeout(handle)
1130
+ };
1131
+ }
1132
+ function mergeAbortSignals(deadline2, caller) {
1133
+ if (!caller) return deadline2;
1134
+ const ctrl = new AbortController();
1135
+ if (deadline2.aborted || caller.aborted) {
1136
+ ctrl.abort();
1137
+ return ctrl.signal;
1138
+ }
1139
+ const onAbort = () => ctrl.abort();
1140
+ deadline2.addEventListener("abort", onAbort, { once: true });
1141
+ caller.addEventListener("abort", onAbort, { once: true });
1142
+ return ctrl.signal;
1143
+ }
1144
+ async function safeJson(res) {
1145
+ try {
1146
+ return await res.json();
1147
+ } catch {
1148
+ return null;
1149
+ }
1150
+ }
1151
+ function extractWireCode(body) {
1152
+ const b = body;
1153
+ const code = b?.error?.code ?? b?.code;
1154
+ return typeof code === "string" && code.length > 0 ? code : null;
1155
+ }
1156
+ function extractWireMessage(body) {
1157
+ const b = body;
1158
+ const message = b?.error?.message ?? b?.message;
1159
+ return typeof message === "string" && message.length > 0 ? message : null;
1160
+ }
1161
+ function extractRetryable(body) {
1162
+ const b = body;
1163
+ return b?.error?.retryable === true || b?.retryable === true;
1164
+ }
1165
+ function describeCause(cause) {
1166
+ if (cause instanceof Error) return cause.message;
1167
+ return typeof cause === "string" ? cause : "network request failed";
1168
+ }
1169
+
1170
+ // src/client/funnel/requestFunnel.ts
1171
+ var FUNNEL_UNARY_TIMEOUT_MS = 3e4;
1172
+ var RETRY_OVERRIDE_MAX_MS = BACKOFF_CAP_MS * 2;
1173
+ var IDEMPOTENCY_HEADER = "idempotency-key";
1174
+ var MUTATING_METHODS = /* @__PURE__ */ new Set(["POST", "PUT", "PATCH", "DELETE"]);
1175
+ var NOOP_OBSERVER = Object.freeze({
1176
+ onEvent() {
1177
+ }
1178
+ });
1179
+ var defaultFunnelTimers = Object.freeze({
1180
+ setTimeout: (handler, ms) => setTimeout(handler, ms),
1181
+ clearTimeout: (handle) => clearTimeout(handle),
1182
+ now: () => Date.now()
1183
+ });
1184
+ function createRequestFunnel(deps) {
1185
+ const observer = deps.observer ?? NOOP_OBSERVER;
1186
+ const timers = deps.timers ?? defaultFunnelTimers;
1187
+ const rng = deps.rng ?? Math.random;
1188
+ const sleep = deps.sleep ?? ((ms, signal) => delayAbortable(ms, timers, signal));
1189
+ const ceiling = deps.maxAttempts ?? MAX_RETRY_ATTEMPTS;
1190
+ const timeoutMs = deps.unaryTimeoutMs ?? FUNNEL_UNARY_TIMEOUT_MS;
1191
+ const mintKey = deps.newIdempotencyKey ?? defaultIdempotencyKeyFactory();
1192
+ const emit = (event) => {
1193
+ try {
1194
+ observer.onEvent(event);
1195
+ } catch {
1196
+ }
1197
+ };
1198
+ async function send(call, req, opts) {
1199
+ const perCallMaxAttempts = opts?.maxAttempts;
1200
+ const maxAttempts = Math.max(1, perCallMaxAttempts ?? ceiling);
1201
+ const idempotent = opts?.idempotent ?? MUTATING_METHODS.has(req.method);
1202
+ const idempotencyKey = idempotent ? mintKey() : null;
1203
+ const base = assembleHeaders(req, idempotencyKey);
1204
+ let attempt = 0;
1205
+ for (; ; ) {
1206
+ const stamp = (extra) => Object.freeze({
1207
+ call,
1208
+ method: req.method,
1209
+ path: req.path,
1210
+ attempt,
1211
+ ...idempotencyKey ? { idempotencyKey } : {},
1212
+ ...extra
1213
+ });
1214
+ emit(stamp({ phase: "attempt" }));
1215
+ const deadline2 = boundedSignal(timeoutMs, timers);
1216
+ const merged = mergeSignals(deadline2.signal, req.signal);
1217
+ let settled;
1218
+ try {
1219
+ settled = await authedSend({ ...base, signal: merged.signal }, deps.auth);
1220
+ } catch (cause) {
1221
+ settled = err(networkError(cause));
1222
+ } finally {
1223
+ merged.dispose();
1224
+ deadline2.cancel();
1225
+ }
1226
+ if (settled.ok) {
1227
+ emit(stamp({ phase: "settled", ok: true, reason: "ok" }));
1228
+ return settled;
1229
+ }
1230
+ const error = settled.error;
1231
+ const decision = decideRetry(error, attempt, {
1232
+ maxAttempts,
1233
+ rng,
1234
+ now: timers.now(),
1235
+ aborted: req.signal?.aborted === true,
1236
+ ...perCallMaxAttempts !== void 0 ? { perCallMaxAttempts } : {},
1237
+ ...deps.errorPolicy !== void 0 ? { policy: deps.errorPolicy } : {}
1238
+ });
1239
+ const settledEvent = {
1240
+ ok: false,
1241
+ code: error.code,
1242
+ reason: decision.reason,
1243
+ ...error.httpStatus !== void 0 ? { httpStatus: error.httpStatus } : {},
1244
+ ...error.requestId !== void 0 ? { requestId: error.requestId } : {}
1245
+ };
1246
+ if (!decision.retry) {
1247
+ emit(stamp({ phase: "settled", ...settledEvent }));
1248
+ return err(error);
1249
+ }
1250
+ emit(stamp({ phase: "retry", ...settledEvent, delayMs: decision.delayMs }));
1251
+ await sleep(decision.delayMs, req.signal);
1252
+ if (req.signal?.aborted === true) {
1253
+ emit(stamp({ phase: "settled", ...settledEvent, reason: "aborted" }));
1254
+ return err(error);
1255
+ }
1256
+ attempt += 1;
1257
+ }
1258
+ }
1259
+ async function authorize(req) {
1260
+ return withAuthHeaders(req, await resolveDeviceAuth(deps.auth));
1261
+ }
1262
+ async function* stream(call, req, signal) {
1263
+ emit(
1264
+ Object.freeze({
1265
+ call,
1266
+ phase: "stream.open",
1267
+ method: req.method,
1268
+ path: req.path,
1269
+ attempt: 0
1270
+ })
1271
+ );
1272
+ try {
1273
+ yield* deps.auth.transport.stream(req, signal);
1274
+ } catch {
1275
+ yield errorFrame({
1276
+ // The same wire spelling sse.ts synthesizes, so `fromWire` folds it to the retryable `internalError`
1277
+ // like any other transport failure. wireMessage stays null: it is the SERVER's text, and a thrown
1278
+ // host exception's `.message` is not that.
1279
+ code: "internal_error",
1280
+ retryable: true,
1281
+ wireMessage: null,
1282
+ synthesized: true,
1283
+ lastEventId: null,
1284
+ serverRequestId: null
1285
+ });
1286
+ }
1287
+ }
1288
+ return Object.freeze({ send, authorize, stream });
1289
+ }
1290
+ function assembleHeaders(req, idempotencyKey) {
1291
+ const headers = {};
1292
+ for (const [key, value] of Object.entries(req.headers ?? {})) {
1293
+ if (key.toLowerCase() === IDEMPOTENCY_HEADER) continue;
1294
+ headers[key] = value;
1295
+ }
1296
+ if (idempotencyKey !== null) headers["Idempotency-Key"] = idempotencyKey;
1297
+ return { ...req, headers };
1298
+ }
1299
+ function defaultIdempotencyKeyFactory() {
1300
+ let counter = 0;
1301
+ return () => `efk_${Date.now().toString(36)}_${(counter++).toString(36)}_${Math.random().toString(36).slice(2, 12)}`;
1302
+ }
1303
+ var POLICY_MAX_ATTEMPTS_CAP = 10;
1304
+ function decideRetry(error, attempt, ctx) {
1305
+ if (ctx.aborted) return { retry: false, reason: "aborted" };
1306
+ const throttle = throttleKind(error);
1307
+ if (throttle === "quota") {
1308
+ return { retry: false, reason: "daily-quota-exhausted" };
1309
+ }
1310
+ if (throttle !== "burst" && !isAutoRetryable(error.code)) {
1311
+ return { retry: false, reason: "terminal-code" };
1312
+ }
1313
+ const reason = throttle === "burst" ? "burst-throttle" : "retryable-code";
1314
+ const policyVetoedRetry = () => {
1315
+ if (ctx.policy === void 0) return false;
1316
+ try {
1317
+ return !ctx.policy.shouldRetry(error.code, attempt);
1318
+ } catch {
1319
+ return false;
1320
+ }
1321
+ };
1322
+ if (policyVetoedRetry()) return { retry: false, reason: "terminal-code" };
1323
+ const policyCeiling = () => {
1324
+ if (ctx.policy === void 0) return null;
1325
+ let raw;
1326
+ try {
1327
+ raw = ctx.policy.maxAttempts(error.code);
1328
+ } catch {
1329
+ return null;
1330
+ }
1331
+ if (typeof raw !== "number" || !Number.isFinite(raw)) return null;
1332
+ return Math.max(1, Math.min(POLICY_MAX_ATTEMPTS_CAP, Math.floor(raw)));
1333
+ };
1334
+ const ceiling = ctx.perCallMaxAttempts ?? policyCeiling() ?? ctx.maxAttempts;
1335
+ if (attempt + 1 >= ceiling) return { retry: false, reason: "attempts-exhausted" };
1336
+ const override = retryOverrideMs(error, ctx.now);
1337
+ if (override !== null) {
1338
+ if (override > RETRY_OVERRIDE_MAX_MS) {
1339
+ return { retry: false, reason: "server-reset-beyond-budget" };
1340
+ }
1341
+ return { retry: true, reason, delayMs: override };
1342
+ }
1343
+ return { retry: true, reason, delayMs: backoffDelayMs(attempt, ctx.rng) };
1344
+ }
1345
+ function throttleKind(error) {
1346
+ const code = error.code === "unknown" ? fromWire(rawWireCode(error.raw)) : error.code;
1347
+ if (code === "quotaExceeded") return "quota";
1348
+ if (code === "rateLimited") return "burst";
1349
+ if (error.httpStatus === 429) {
1350
+ return "burst";
1351
+ }
1352
+ return null;
1353
+ }
1354
+ function retryOverrideMs(error, now) {
1355
+ const at = findResetsAt(error.raw);
1356
+ if (at === null) return null;
1357
+ const delta = at - now;
1358
+ return delta > 0 ? delta : 0;
1359
+ }
1360
+ function findResetsAt(raw) {
1361
+ for (const scope of candidateScopes(raw)) {
1362
+ const value = scope["resets_at"];
1363
+ const parsed = parseInstantMs(value);
1364
+ if (parsed !== null) return parsed;
1365
+ }
1366
+ return null;
1367
+ }
1368
+ function candidateScopes(raw) {
1369
+ if (!isRecord(raw)) return [];
1370
+ const out = [raw];
1371
+ for (const nested of ["error", "detail"]) {
1372
+ const value = raw[nested];
1373
+ if (isRecord(value)) out.push(value);
1374
+ }
1375
+ return out;
1376
+ }
1377
+ function parseInstantMs(value) {
1378
+ if (typeof value === "number" && Number.isFinite(value)) {
1379
+ return value < 1e11 ? Math.round(value * 1e3) : Math.round(value);
1380
+ }
1381
+ if (typeof value === "string" && value.trim().length > 0) {
1382
+ const parsed = Date.parse(value);
1383
+ return Number.isFinite(parsed) ? parsed : null;
1384
+ }
1385
+ return null;
1386
+ }
1387
+ function rawWireCode(raw) {
1388
+ for (const scope of candidateScopes(raw)) {
1389
+ const code = scope["code"];
1390
+ if (typeof code === "string" && code.length > 0) return code;
1391
+ }
1392
+ return null;
1393
+ }
1394
+ function isRecord(value) {
1395
+ return typeof value === "object" && value !== null;
1396
+ }
1397
+ async function resolveDeviceAuth(auth) {
1398
+ if (auth.mode === "anonymous") {
1399
+ return {
1400
+ mode: "anonymous",
1401
+ publishableKey: auth.publishableKey,
1402
+ userRef: auth.userRef,
1403
+ ...auth.sessionId ? { sessionId: auth.sessionId } : {}
1404
+ };
1405
+ }
1406
+ return {
1407
+ mode: "personalized",
1408
+ token: await auth.identity.currentToken(),
1409
+ userRef: auth.userRef,
1410
+ ...auth.sessionId ? { sessionId: auth.sessionId } : {}
1411
+ };
1412
+ }
1413
+ function boundedSignal(ms, timers) {
1414
+ const ctrl = new AbortController();
1415
+ const handle = timers.setTimeout(() => ctrl.abort(), ms);
1416
+ return { signal: ctrl.signal, cancel: () => timers.clearTimeout(handle) };
1417
+ }
1418
+ function mergeSignals(deadline2, caller) {
1419
+ const noop = () => void 0;
1420
+ if (!caller) return { signal: deadline2, dispose: noop };
1421
+ const ctrl = new AbortController();
1422
+ if (deadline2.aborted || caller.aborted) {
1423
+ ctrl.abort();
1424
+ return { signal: ctrl.signal, dispose: noop };
1425
+ }
1426
+ const onAbort = () => ctrl.abort();
1427
+ deadline2.addEventListener("abort", onAbort, { once: true });
1428
+ caller.addEventListener("abort", onAbort, { once: true });
1429
+ return {
1430
+ signal: ctrl.signal,
1431
+ dispose: () => {
1432
+ deadline2.removeEventListener("abort", onAbort);
1433
+ caller.removeEventListener("abort", onAbort);
1434
+ }
1435
+ };
1436
+ }
1437
+ function delayAbortable(ms, timers, signal) {
1438
+ if (ms <= 0 || signal?.aborted === true) return Promise.resolve();
1439
+ return new Promise((resolve) => {
1440
+ const handle = timers.setTimeout(() => {
1441
+ signal?.removeEventListener("abort", onAbort);
1442
+ resolve();
1443
+ }, ms);
1444
+ const onAbort = () => {
1445
+ timers.clearTimeout(handle);
1446
+ resolve();
1447
+ };
1448
+ signal?.addEventListener("abort", onAbort, { once: true });
1449
+ });
1450
+ }
1451
+
1452
+ // src/core/media/ports.ts
1453
+ var unavailableUpload = Object.freeze({
1454
+ async presignedPut() {
1455
+ return Promise.reject(new Error("UploadPort is unavailable; no presigned-upload adapter was injected"));
1456
+ }
1457
+ });
1458
+ function delayAbortable2(ms, signal, timers) {
1459
+ return new Promise((resolve) => {
1460
+ if (signal.aborted) {
1461
+ resolve();
1462
+ return;
1463
+ }
1464
+ const holder = { handle: void 0 };
1465
+ const done = () => {
1466
+ timers.clearTimeout(holder.handle);
1467
+ signal.removeEventListener("abort", done);
1468
+ resolve();
1469
+ };
1470
+ holder.handle = timers.setTimeout(done, ms);
1471
+ signal.addEventListener("abort", done, { once: true });
1472
+ });
1473
+ }
1474
+ function mergeSignals2(a, b) {
1475
+ if (!b) return a;
1476
+ const ctrl = new AbortController();
1477
+ if (a.aborted || b.aborted) {
1478
+ ctrl.abort();
1479
+ return ctrl.signal;
1480
+ }
1481
+ const onAbort = () => ctrl.abort();
1482
+ a.addEventListener("abort", onAbort, { once: true });
1483
+ b.addEventListener("abort", onAbort, { once: true });
1484
+ return ctrl.signal;
1485
+ }
1486
+ var MediaStore = class {
1487
+ constructor(initial) {
1488
+ this.listeners = /* @__PURE__ */ new Set();
1489
+ this.epoch = 0;
1490
+ this.inFlight = null;
1491
+ this.snapshot = Object.freeze({ ...initial });
1492
+ }
1493
+ subscribe(listener) {
1494
+ this.listeners.add(listener);
1495
+ return () => {
1496
+ this.listeners.delete(listener);
1497
+ };
1498
+ }
1499
+ getSnapshot() {
1500
+ return this.snapshot;
1501
+ }
1502
+ patch(partial) {
1503
+ this.snapshot = Object.freeze({ ...this.snapshot, ...partial });
1504
+ for (const listener of this.listeners) listener();
1505
+ }
1506
+ beginOperation(external) {
1507
+ this.inFlight?.abort();
1508
+ const ctrl = new AbortController();
1509
+ this.inFlight = ctrl;
1510
+ const epoch = this.epoch;
1511
+ const signal = external ? mergeSignals2(ctrl.signal, external) : ctrl.signal;
1512
+ return {
1513
+ signal,
1514
+ epoch,
1515
+ settle: () => {
1516
+ if (this.inFlight === ctrl) this.inFlight = null;
1517
+ }
1518
+ };
1519
+ }
1520
+ alive(epoch) {
1521
+ return epoch === this.epoch;
1522
+ }
1523
+ /** Re-scope on user/pet switch: aborts in-flight and bumps the epoch so a late write drops. */
1524
+ rescope() {
1525
+ this.epoch += 1;
1526
+ this.inFlight?.abort();
1527
+ this.inFlight = null;
1528
+ }
1529
+ /** Idempotent teardown: aborts in-flight, bumps the epoch, drops every listener. */
1530
+ dispose() {
1531
+ this.epoch += 1;
1532
+ this.inFlight?.abort();
1533
+ this.inFlight = null;
1534
+ this.listeners.clear();
1535
+ }
1536
+ };
1537
+
1538
+ // src/core/chat/chatMappers.ts
1539
+ function makeUser(id, text) {
1540
+ return Object.freeze({ id, role: "user", text, pending: true });
1541
+ }
1542
+ function makeAssistant(id, text) {
1543
+ return Object.freeze({ id, role: "assistant", text });
1544
+ }
1545
+ function stripPending(m) {
1546
+ return Object.freeze({ id: m.id, role: m.role, text: m.text });
1547
+ }
1548
+ function appendText(m, text) {
1549
+ const next = {
1550
+ id: m.id,
1551
+ role: m.role,
1552
+ text: m.text + text
1553
+ };
1554
+ if (m.citations) next.citations = m.citations;
1555
+ if (m.responseId) next.responseId = m.responseId;
1556
+ return Object.freeze(next);
1557
+ }
1558
+ function finalizeAssistant(m, done) {
1559
+ const next = {
1560
+ id: done.messageId ? done.messageId : m.id,
1561
+ role: "assistant",
1562
+ text: m.text
1563
+ };
1564
+ if (done.citations.length > 0) next.citations = done.citations;
1565
+ if (done.messageId) next.responseId = brandResponseId(done.messageId);
1566
+ return Object.freeze(next);
1567
+ }
1568
+ function freezeSnapshot(s) {
1569
+ return Object.freeze({
1570
+ status: s.status,
1571
+ messages: Object.freeze([...s.messages]),
1572
+ conversationId: s.conversationId,
1573
+ error: s.error,
1574
+ isStreaming: s.isStreaming,
1575
+ isBootstrapping: s.isBootstrapping,
1576
+ suggestedPrompts: Object.freeze([...s.suggestedPrompts])
1577
+ });
1578
+ }
1579
+ function makeError(code, retryable, wireMessage) {
1580
+ return makeEverfurError(code, { retryable, ...wireMessage ? { wireMessage } : {} });
1581
+ }
1582
+ function errorFromFrame(frame) {
1583
+ const code = fromWire(frame.code);
1584
+ return makeEverfurError(code, {
1585
+ retryable: frame.retryable || shouldRetry(code),
1586
+ wireCode: frame.code,
1587
+ ...frame.serverRequestId ? { requestId: frame.serverRequestId } : {},
1588
+ ...frame.wireMessage ? { wireMessage: frame.wireMessage } : {},
1589
+ raw: frame
1590
+ });
1591
+ }
1592
+ function synthErrorFrame(error) {
1593
+ return errorFrame({
1594
+ code: canonicalWireCode(error.code),
1595
+ retryable: error.retryable,
1596
+ wireMessage: error.wireMessage ?? null,
1597
+ synthesized: true,
1598
+ lastEventId: null,
1599
+ serverRequestId: error.requestId ?? null
1600
+ });
1601
+ }
1602
+ function canonicalWireCode(code) {
1603
+ switch (code) {
1604
+ case "authExpired":
1605
+ return "AUTH_EXPIRED";
1606
+ case "authRejected":
1607
+ return "AuthorizationException";
1608
+ case "sessionRequired":
1609
+ return "session_required";
1610
+ case "accessDenied":
1611
+ return "ACCESS_DENIED";
1612
+ case "paymentRequired":
1613
+ return "TIER_UPGRADE_REQUIRED";
1614
+ case "quotaExceeded":
1615
+ return "QUOTA_EXCEEDED";
1616
+ case "rateLimited":
1617
+ return "RATE_LIMITED";
1618
+ case "validationFailed":
1619
+ return "ValidationException";
1620
+ case "sdkUpdateRequired":
1621
+ return "invalidRequest";
1622
+ case "conflict":
1623
+ return "ConflictException";
1624
+ case "idempotencyConflict":
1625
+ return "IDEMPOTENCY_CONFLICT";
1626
+ case "idempotencyInFlight":
1627
+ return "IDEMPOTENCY_KEY_IN_FLIGHT";
1628
+ case "conversationNotFound":
1629
+ return "CONVERSATION_NOT_FOUND";
1630
+ case "petNotFound":
1631
+ return "PET_NOT_FOUND";
1632
+ case "resourceNotFound":
1633
+ return "ResourceNotFoundException";
1634
+ case "streamTimeout":
1635
+ return "STREAM_TIMEOUT";
1636
+ case "mediaUploadFailed":
1637
+ return "MEDIA_UPLOAD_FAILED";
1638
+ case "moderationBlocked":
1639
+ return "MODERATION_BLOCKED";
1640
+ case "upstreamLlmTimeout":
1641
+ return "UPSTREAM_LLM_TIMEOUT";
1642
+ case "internalError":
1643
+ return "INTERNAL_ERROR";
1644
+ case "notImplemented":
1645
+ return "NotImplementedException";
1646
+ case "serviceUnavailable":
1647
+ return "ServiceUnavailableException";
1648
+ case "streamIncomplete":
1649
+ return "STREAM_INCOMPLETE";
1650
+ case "unknown":
1651
+ return "UNKNOWN";
1652
+ default:
1653
+ return assertNever(code);
1654
+ }
1655
+ }
1656
+ function parsePromptCategories(raw) {
1657
+ const list = Array.isArray(raw) ? raw : isPlainObject2(raw) && Array.isArray(raw["categories"]) ? raw["categories"] : [];
1658
+ const out = [];
1659
+ for (const entry of list) {
1660
+ if (!isPlainObject2(entry)) continue;
1661
+ const category = asStr(entry["category"]) ?? asStr(entry["title"]) ?? "";
1662
+ const prompts = asPromptTextList(entry["prompts"] ?? entry["questions"]);
1663
+ if (category.length === 0 && prompts.length === 0) continue;
1664
+ out.push(Object.freeze({ category, prompts: Object.freeze(prompts) }));
1665
+ }
1666
+ return Object.freeze(out);
1667
+ }
1668
+ function flattenPrompts(categories) {
1669
+ const seen = /* @__PURE__ */ new Set();
1670
+ const out = [];
1671
+ for (const category of categories) {
1672
+ for (const prompt of category.prompts) {
1673
+ const trimmed = prompt.trim();
1674
+ if (trimmed.length === 0 || seen.has(trimmed)) continue;
1675
+ seen.add(trimmed);
1676
+ out.push(trimmed);
1677
+ }
1678
+ }
1679
+ return out;
1680
+ }
1681
+ function isPlainObject2(v) {
1682
+ return typeof v === "object" && v !== null && !Array.isArray(v);
1683
+ }
1684
+ function asStr(v) {
1685
+ return typeof v === "string" ? v : null;
1686
+ }
1687
+ function asPromptTextList(v) {
1688
+ if (!Array.isArray(v)) return [];
1689
+ const out = [];
1690
+ for (const entry of v) {
1691
+ if (typeof entry === "string") {
1692
+ out.push(entry);
1693
+ } else if (isPlainObject2(entry)) {
1694
+ const text = asStr(entry["text"]) ?? asStr(entry["prompt"]) ?? asStr(entry["title"]);
1695
+ if (text !== null) out.push(text);
1696
+ }
1697
+ }
1698
+ return out;
1699
+ }
1700
+ function defaultIdFactory() {
1701
+ let counter = 0;
1702
+ return () => `m-${Date.now().toString(36)}-${(counter++).toString(36)}-${Math.random().toString(36).slice(2, 8)}`;
1703
+ }
1704
+ function defaultIdempotencyFactory() {
1705
+ let counter = 0;
1706
+ return () => `chat-send-${Date.now().toString(36)}-${(counter++).toString(36)}-${Math.random().toString(36).slice(2, 10)}`;
1707
+ }
1708
+ function brandConversationId(raw) {
1709
+ return raw;
1710
+ }
1711
+ function brandResponseId(raw) {
1712
+ return raw;
1713
+ }
1714
+
1715
+ // src/core/chat/watchdog.ts
1716
+ var defaultTimers2 = {
1717
+ setTimeout: (handler, ms) => setTimeout(handler, ms),
1718
+ clearTimeout: (handle) => clearTimeout(handle),
1719
+ now: () => Date.now()
1720
+ };
1721
+ async function* withWatchdog(source, budget, signal, timers) {
1722
+ const it = source[Symbol.asyncIterator]();
1723
+ const overall = deadline(budget.overallMs, timers);
1724
+ const idle = deadline(budget.idleMs, timers);
1725
+ const abort = abortPromise(signal);
1726
+ try {
1727
+ for (; ; ) {
1728
+ if (signal.aborted) return;
1729
+ const nextTagged = it.next().then(
1730
+ (value) => ({ tag: "next", value }),
1731
+ // A rejected it.next() is a RAW mid-stream transport drop (WiFi->cellular, backgrounding), NOT a clean
1732
+ // end-of-stream. The prior code coerced it to { done: true }, which silently short-circuited the SDK's
1733
+ // own retry ladder (SPEC-10 §7). Tag it so the loop can emit a retryable frame instead.
1734
+ () => ({ tag: "streamError" })
1735
+ );
1736
+ const outcome = await Promise.race([
1737
+ nextTagged,
1738
+ idle.promise.then(() => ({ tag: "idle" })),
1739
+ overall.promise.then(() => ({ tag: "overall" })),
1740
+ abort.then(() => ({ tag: "abort" }))
1741
+ ]);
1742
+ if (outcome.tag === "abort") return;
1743
+ if (outcome.tag === "streamError") {
1744
+ if (signal.aborted) return;
1745
+ yield synthStreamErrorFrame();
1746
+ return;
1747
+ }
1748
+ if (outcome.tag === "idle" || outcome.tag === "overall") {
1749
+ yield synthTimeoutFrame();
1750
+ return;
1751
+ }
1752
+ const result = outcome.value;
1753
+ if (result.done) return;
1754
+ idle.reset(budget.idleMs);
1755
+ yield result.value;
1756
+ if (result.value.terminal) return;
1757
+ }
1758
+ } finally {
1759
+ idle.cancel();
1760
+ overall.cancel();
1761
+ void Promise.resolve(it.return?.(void 0)).catch(() => {
1762
+ });
1763
+ }
1764
+ }
1765
+ function synthTimeoutFrame() {
1766
+ return errorFrame({
1767
+ code: "STREAM_TIMEOUT",
1768
+ retryable: true,
1769
+ wireMessage: null,
1770
+ synthesized: true,
1771
+ lastEventId: null
1772
+ });
1773
+ }
1774
+ function synthStreamErrorFrame() {
1775
+ return errorFrame({
1776
+ code: "STREAM_INCOMPLETE",
1777
+ retryable: true,
1778
+ wireMessage: null,
1779
+ synthesized: true,
1780
+ lastEventId: null
1781
+ });
1782
+ }
1783
+ function deadline(ms, timers) {
1784
+ let resolveFn = () => {
1785
+ };
1786
+ const promise = new Promise((resolve) => {
1787
+ resolveFn = resolve;
1788
+ });
1789
+ let handle = timers.setTimeout(() => resolveFn(), ms);
1790
+ return {
1791
+ promise,
1792
+ reset(next) {
1793
+ timers.clearTimeout(handle);
1794
+ handle = timers.setTimeout(() => resolveFn(), next);
1795
+ },
1796
+ cancel() {
1797
+ timers.clearTimeout(handle);
1798
+ }
1799
+ };
1800
+ }
1801
+ function abortPromise(signal) {
1802
+ return new Promise((resolve) => {
1803
+ if (signal.aborted) {
1804
+ resolve();
1805
+ return;
1806
+ }
1807
+ signal.addEventListener("abort", () => resolve(), { once: true });
1808
+ });
1809
+ }
1810
+
1811
+ // src/core/chat/ChatController.ts
1812
+ var DEFAULT_IDLE_MS = 6e4;
1813
+ var DEFAULT_OVERALL_MS = 18e4;
1814
+ var DELTA_FLUSH_MS = 24;
1815
+ var DELTA_FLUSH_CHARS = 512;
1816
+ var SEND_IS_SERVER_DEDUPED = false;
1817
+ function createChatController(deps) {
1818
+ return new ChatControllerImpl(deps);
1819
+ }
1820
+ var ChatControllerImpl = class extends MediaStore {
1821
+ constructor(deps) {
1822
+ super(
1823
+ freezeSnapshot({
1824
+ status: "idle",
1825
+ messages: [],
1826
+ conversationId: deps.initialConversationId ?? null,
1827
+ error: null,
1828
+ isStreaming: false,
1829
+ isBootstrapping: false,
1830
+ suggestedPrompts: []
1831
+ })
1832
+ );
1833
+ this.handlerTeardowns = /* @__PURE__ */ new Set();
1834
+ this.lastTurn = null;
1835
+ this.lastResponseIdValue = null;
1836
+ /** Delta coalescing buffer (PERF1): accumulated assistant text not yet flushed to the snapshot. */
1837
+ this.pendingDelta = "";
1838
+ this.flushHandle = null;
1839
+ this.auth = deps.auth;
1840
+ this.funnel = deps.funnel ?? createRequestFunnel({
1841
+ auth: deps.auth,
1842
+ ...deps.errorPolicy ? { errorPolicy: deps.errorPolicy } : {}
1843
+ });
1844
+ this.telemetry = deps.telemetry ?? noopTelemetry;
1845
+ this.errorPolicy = deps.errorPolicy ?? defaultErrorPolicy;
1846
+ this.timers = deps.timers ?? defaultTimers2;
1847
+ this.rng = deps.rng ?? Math.random;
1848
+ this.newId = deps.newId ?? defaultIdFactory();
1849
+ this.makeIdempotencyKey = deps.makeIdempotencyKey ?? defaultIdempotencyFactory();
1850
+ this.budget = {
1851
+ idleMs: deps.budget?.idleMs ?? DEFAULT_IDLE_MS,
1852
+ overallMs: deps.budget?.overallMs ?? DEFAULT_OVERALL_MS
1853
+ };
1854
+ }
1855
+ // ---- store ------------------------------------------------------------
1856
+ // subscribe / getSnapshot / beginOperation / alive are inherited from MediaStore. patch is overridden so the
1857
+ // messages array stays deep-frozen (the base freezes only the snapshot object).
1858
+ patch(partial) {
1859
+ if (partial.messages !== void 0) {
1860
+ const frozen = Object.freeze([...partial.messages]);
1861
+ super.patch({ ...partial, messages: frozen });
1862
+ return;
1863
+ }
1864
+ super.patch(partial);
1865
+ }
1866
+ send(text, opts, handlers) {
1867
+ const options = opts ?? {};
1868
+ const invalid2 = validateMessageText(text);
1869
+ if (invalid2 !== null) {
1870
+ this.telemetry.track("chat.send.rejected", { reason: invalid2.reason });
1871
+ this.patch({ status: "error", isStreaming: false, error: invalid2.error });
1872
+ if (handlers) {
1873
+ handlers.onError(invalid2.error);
1874
+ return () => {
1875
+ };
1876
+ }
1877
+ return singleFrameStream(synthErrorFrame(invalid2.error));
1878
+ }
1879
+ if (handlers) return this.driveWithHandlers(text, options, handlers);
1880
+ const turn = this.beginTurn(text, options);
1881
+ return this.runTurn(turn, options.signal);
1882
+ }
1883
+ retryLast() {
1884
+ const turn = this.lastTurn;
1885
+ if (turn === null) return emptyStream();
1886
+ turn.assistantMessageId = null;
1887
+ turn.sawDelta = false;
1888
+ turn.conversationIdOverride = null;
1889
+ this.discardPendingDelta();
1890
+ const hasUser = this.snapshot.messages.some((m) => m.id === turn.userMessageId);
1891
+ const messages = hasUser ? this.snapshot.messages : [...this.snapshot.messages, makeUser(turn.userMessageId, turn.text)];
1892
+ this.patch({ error: null, messages });
1893
+ return this.runTurn(turn, void 0);
1894
+ }
1895
+ stop() {
1896
+ this.inFlight?.abort();
1897
+ this.inFlight = null;
1898
+ this.discardPendingDelta();
1899
+ this.telemetry.track("chat.cancel", {});
1900
+ const messages = this.snapshot.messages.filter((m) => !(m.role === "user" && m.pending === true));
1901
+ const changed = messages.length !== this.snapshot.messages.length;
1902
+ if (this.snapshot.status === "streaming" || changed) {
1903
+ this.patch({ status: "idle", isStreaming: false, ...changed ? { messages } : {} });
1904
+ }
1905
+ }
1906
+ rescope() {
1907
+ super.rescope();
1908
+ this.discardPendingDelta();
1909
+ if (this.snapshot.status === "streaming") this.patch({ status: "idle", isStreaming: false });
1910
+ }
1911
+ dispose() {
1912
+ this.discardPendingDelta();
1913
+ for (const teardown of this.handlerTeardowns) teardown();
1914
+ this.handlerTeardowns.clear();
1915
+ super.dispose();
1916
+ }
1917
+ adoptConversation(id) {
1918
+ if (this.snapshot.conversationId === id) return;
1919
+ this.patch({ conversationId: id });
1920
+ }
1921
+ adoptPrompts(categories) {
1922
+ const prompts = flattenPrompts(categories);
1923
+ if (prompts.length === 0 && this.snapshot.suggestedPrompts.length === 0) return;
1924
+ this.patch({ suggestedPrompts: Object.freeze(prompts) });
1925
+ }
1926
+ // ---- unary bootstrap helpers (§8) -------------------------------------
1927
+ async createConversation(opts) {
1928
+ return this.createConversationBounded(opts?.petRef ?? null);
1929
+ }
1930
+ /** The bounded create used by both the public helper and the turn pipeline (a caller signal ties it to op). */
1931
+ async createConversationBounded(petRef2, signal) {
1932
+ const req = {
1933
+ method: "POST",
1934
+ path: "/widget/v1/conversations",
1935
+ body: petRef2 ? { pet_ref: petRef2 } : {}
1936
+ };
1937
+ const res = await this.authedUnary(
1938
+ "chat.createConversation",
1939
+ req,
1940
+ signal,
1941
+ // The widget lane does NOT read `Idempotency-Key`: its router is a plain APIRouter with no
1942
+ // idempotency route class, so a replay is a second CREATE, not a dedup, and retrying leaves the
1943
+ // partner with orphan threads nobody asked for. `maxAttempts: 1` stops the replay.
1944
+ //
1945
+ // The key itself is deliberately STILL SENT (no `idempotent: false`): it costs nothing on the wire,
1946
+ // it is what the funnel would mint anyway, and it starts working by itself the day the route dedups.
1947
+ // Deleting this one option is then the whole reversal.
1948
+ { maxAttempts: 1 }
1949
+ );
1950
+ if (!res.ok) return err(res.error);
1951
+ const raw = res.value?.conversation_id ?? res.value?.id;
1952
+ if (typeof raw !== "string" || raw.length === 0) {
1953
+ return err(makeError("internalError", true));
1954
+ }
1955
+ return ok(brandConversationId(raw));
1956
+ }
1957
+ async getPrompts(opts) {
1958
+ const petRef2 = opts?.petRef ?? null;
1959
+ if (petRef2 !== null && hasLoneSurrogate(petRef2)) {
1960
+ return err(
1961
+ makeEverfurError("validationFailed", {
1962
+ retryable: false,
1963
+ wireMessage: "pet_ref contains an unpaired surrogate and cannot be encoded"
1964
+ })
1965
+ );
1966
+ }
1967
+ const query = petRef2 !== null ? `?pet_ref=${encodeURIComponent(petRef2)}` : "";
1968
+ const res = await this.authedUnary("chat.getPrompts", {
1969
+ method: "GET",
1970
+ path: `/widget/v1/suggested-prompts${query}`
1971
+ });
1972
+ if (!res.ok) return err(res.error);
1973
+ return ok(parsePromptCategories(res.value));
1974
+ }
1975
+ /**
1976
+ * A unary authed hop, through the ONE REQUEST FUNNEL. The funnel owns the per-attempt deadline (PERF2:
1977
+ * a stalled connection settles to a retryable error instead of hanging the spinner forever), the auth
1978
+ * spine, retry with full jitter, the client-minted idempotency key, and telemetry. Settles; never throws.
1979
+ */
1980
+ async authedUnary(call, req, external, opts) {
1981
+ return this.funnel.send(call, external ? { ...req, signal: external } : req, opts);
1982
+ }
1983
+ // ---- imperative escape hatch ------------------------------------------
1984
+ driveWithHandlers(text, opts, handlers) {
1985
+ const cancel = new AbortController();
1986
+ const signal = mergeSignals2(cancel.signal, opts.signal);
1987
+ const turn = this.beginTurn(text, opts);
1988
+ const iterable = this.runTurn(turn, signal);
1989
+ let torn = false;
1990
+ const teardown = () => {
1991
+ if (torn) return;
1992
+ torn = true;
1993
+ cancel.abort();
1994
+ this.handlerTeardowns.delete(teardown);
1995
+ };
1996
+ this.handlerTeardowns.add(teardown);
1997
+ void (async () => {
1998
+ for await (const frame of iterable) {
1999
+ if (torn) break;
2000
+ handlers.onFrame(frame);
2001
+ if (frame.kind === "done") handlers.onDone(this.lastResponseIdValue);
2002
+ }
2003
+ if (!torn && this.snapshot.status === "error" && this.snapshot.error !== null) {
2004
+ handlers.onError(this.snapshot.error);
2005
+ }
2006
+ this.handlerTeardowns.delete(teardown);
2007
+ })();
2008
+ return teardown;
2009
+ }
2010
+ // ---- the turn pipeline ------------------------------------------------
2011
+ beginTurn(text, opts) {
2012
+ const turn = {
2013
+ epoch: this.epoch,
2014
+ text,
2015
+ petRef: opts.petRef ?? null,
2016
+ idempotencyKey: opts.idempotencyKey ?? this.makeIdempotencyKey(),
2017
+ userMessageId: this.newId(),
2018
+ assistantMessageId: null,
2019
+ sawDelta: false,
2020
+ conversationIdOverride: opts.conversationId ?? null
2021
+ };
2022
+ this.patch({
2023
+ error: null,
2024
+ messages: [...this.snapshot.messages, makeUser(turn.userMessageId, text)]
2025
+ });
2026
+ return turn;
2027
+ }
2028
+ async *runTurn(turn, external) {
2029
+ const op = this.beginOperation(external);
2030
+ turn.epoch = op.epoch;
2031
+ this.patch({ status: "streaming", isStreaming: true, error: null });
2032
+ this.lastTurn = turn;
2033
+ let retries = 0;
2034
+ let recreated = false;
2035
+ let refreshedOnce = false;
2036
+ try {
2037
+ for (; ; ) {
2038
+ if (op.signal.aborted || !this.alive(op.epoch)) return;
2039
+ const needsConversation = turn.conversationIdOverride === null && this.snapshot.conversationId === null;
2040
+ if (needsConversation) {
2041
+ const created = await this.createConversationBounded(turn.petRef, op.signal);
2042
+ if (op.signal.aborted || !this.alive(op.epoch)) return;
2043
+ if (!created.ok) {
2044
+ yield* this.emitTerminal(turn, created.error, synthErrorFrame(created.error));
2045
+ return;
2046
+ }
2047
+ this.adoptConversation(created.value);
2048
+ }
2049
+ const convId = turn.conversationIdOverride ?? this.snapshot.conversationId;
2050
+ if (convId === null) {
2051
+ const e = makeError("internalError", true);
2052
+ yield* this.emitTerminal(turn, e, synthErrorFrame(e));
2053
+ return;
2054
+ }
2055
+ this.clearAssistantInProgress(turn);
2056
+ const attemptCtrl = new AbortController();
2057
+ const attemptSignal = mergeSignals2(op.signal, attemptCtrl.signal);
2058
+ let terminalError = null;
2059
+ try {
2060
+ let authedReq;
2061
+ try {
2062
+ authedReq = await this.funnel.authorize(this.buildSendRequest(turn, convId));
2063
+ } catch {
2064
+ const e = this.authRejected();
2065
+ yield* this.emitTerminal(turn, e, synthErrorFrame(e));
2066
+ return;
2067
+ }
2068
+ if (op.signal.aborted || !this.alive(op.epoch)) return;
2069
+ const source = this.funnel.stream("chat.send", authedReq, attemptSignal);
2070
+ for await (const frame of withWatchdog(source, this.budget, attemptSignal, this.timers)) {
2071
+ if (!this.alive(op.epoch)) return;
2072
+ if (frame.kind === "error" && frame.terminal) {
2073
+ terminalError = frame;
2074
+ break;
2075
+ }
2076
+ this.applyFrame(frame, turn);
2077
+ yield frame;
2078
+ if (frame.terminal) {
2079
+ op.settle();
2080
+ return;
2081
+ }
2082
+ }
2083
+ } finally {
2084
+ attemptCtrl.abort();
2085
+ }
2086
+ if (op.signal.aborted || !this.alive(op.epoch)) return;
2087
+ if (terminalError === null) {
2088
+ if (this.snapshot.status === "complete") return;
2089
+ const e = makeError("streamIncomplete", true);
2090
+ yield* this.emitTerminal(turn, e, synthErrorFrame(e));
2091
+ return;
2092
+ }
2093
+ const code = fromWire(terminalError.code);
2094
+ if (code === "authExpired" && this.auth.mode === "personalized" && !refreshedOnce) {
2095
+ refreshedOnce = true;
2096
+ this.telemetry.track("chat.auth.refresh", {});
2097
+ const refreshed = await this.tryForceRefresh();
2098
+ if (op.signal.aborted || !this.alive(op.epoch)) return;
2099
+ if (!refreshed) {
2100
+ const e = this.authRejected();
2101
+ yield* this.emitTerminal(turn, e, terminalError);
2102
+ return;
2103
+ }
2104
+ continue;
2105
+ }
2106
+ if (code === "authExpired") {
2107
+ this.telemetry.track("chat.auth.rejected", {});
2108
+ const e = this.authRejected();
2109
+ yield* this.emitTerminal(turn, e, terminalError);
2110
+ return;
2111
+ }
2112
+ if (code === "accessDenied") {
2113
+ this.telemetry.track("chat.access_denied", {});
2114
+ yield* this.emitTerminal(turn, errorFromFrame(terminalError), terminalError);
2115
+ return;
2116
+ }
2117
+ if (canRecreateOnNotFound(code) && !recreated) {
2118
+ recreated = true;
2119
+ this.telemetry.track("chat.conv.recreate", {});
2120
+ this.adoptConversation(null);
2121
+ turn.conversationIdOverride = null;
2122
+ continue;
2123
+ }
2124
+ const framedRetry = terminalError.retryable && shouldRetry(code, true);
2125
+ if (SEND_IS_SERVER_DEDUPED && framedRetry && retries + 1 < this.errorPolicy.maxAttempts(code)) ;
2126
+ yield* this.emitTerminal(turn, errorFromFrame(terminalError), terminalError);
2127
+ return;
2128
+ }
2129
+ } finally {
2130
+ op.settle();
2131
+ }
2132
+ }
2133
+ *emitTerminal(turn, error, frame) {
2134
+ this.applyError(turn, error);
2135
+ yield frame;
2136
+ }
2137
+ // ---- frame -> state ---------------------------------------------------
2138
+ applyFrame(frame, turn) {
2139
+ switch (frame.kind) {
2140
+ case "accepted":
2141
+ if (!this.snapshot.isStreaming) this.patch({ status: "streaming", isStreaming: true });
2142
+ return;
2143
+ case "heartbeat":
2144
+ return;
2145
+ // silent; the watchdog resets its idle timer on any frame
2146
+ case "delta":
2147
+ this.applyDelta(frame.delta, turn);
2148
+ return;
2149
+ case "done":
2150
+ this.applyDone(frame, turn);
2151
+ return;
2152
+ case "analysisStarted":
2153
+ case "analysisComplete":
2154
+ return;
2155
+ // not part of chat render (analyze streams project elsewhere)
2156
+ case "unknown":
2157
+ this.telemetry.track("chat.frame.unknown", {});
2158
+ return;
2159
+ // forward-compat: ignore for render, keep streaming, never crash
2160
+ case "error":
2161
+ return;
2162
+ // terminal errors are driven by the recovery switch, never here
2163
+ default:
2164
+ return assertNever(frame);
2165
+ }
2166
+ }
2167
+ applyDelta(text, turn) {
2168
+ if (turn.assistantMessageId === null) {
2169
+ const assistantId = this.newId();
2170
+ turn.assistantMessageId = assistantId;
2171
+ turn.sawDelta = true;
2172
+ const cleared = this.snapshot.messages.map(
2173
+ (m) => m.id === turn.userMessageId && m.pending === true ? stripPending(m) : m
2174
+ );
2175
+ this.patch({
2176
+ status: "streaming",
2177
+ isStreaming: true,
2178
+ messages: [...cleared, makeAssistant(assistantId, text)]
2179
+ });
2180
+ return;
2181
+ }
2182
+ this.pendingDelta += text;
2183
+ if (this.pendingDelta.length >= DELTA_FLUSH_CHARS) {
2184
+ this.flushPendingDelta(turn);
2185
+ return;
2186
+ }
2187
+ this.scheduleDeltaFlush(turn);
2188
+ }
2189
+ scheduleDeltaFlush(turn) {
2190
+ if (this.flushHandle !== null) return;
2191
+ const scheduledEpoch = this.epoch;
2192
+ this.flushHandle = this.timers.setTimeout(() => {
2193
+ this.flushHandle = null;
2194
+ if (!this.alive(scheduledEpoch)) {
2195
+ this.pendingDelta = "";
2196
+ return;
2197
+ }
2198
+ this.flushPendingDelta(turn);
2199
+ }, DELTA_FLUSH_MS);
2200
+ }
2201
+ /** Fold the buffered deltas into the streaming assistant message as ONE patch (one listener notification). */
2202
+ flushPendingDelta(turn) {
2203
+ this.clearFlushTimer();
2204
+ if (this.pendingDelta.length === 0) return;
2205
+ const chunk = this.pendingDelta;
2206
+ this.pendingDelta = "";
2207
+ const assistantId = turn.assistantMessageId;
2208
+ if (assistantId === null) return;
2209
+ const messages = this.snapshot.messages.map((m) => m.id === assistantId ? appendText(m, chunk) : m);
2210
+ this.patch({ messages });
2211
+ }
2212
+ /** Drop a buffered-but-unflushed delta (cancel / rescope / dispose / retry): no stale text leaks forward. */
2213
+ discardPendingDelta() {
2214
+ this.clearFlushTimer();
2215
+ this.pendingDelta = "";
2216
+ }
2217
+ clearFlushTimer() {
2218
+ if (this.flushHandle !== null) {
2219
+ this.timers.clearTimeout(this.flushHandle);
2220
+ this.flushHandle = null;
2221
+ }
2222
+ }
2223
+ applyDone(done, turn) {
2224
+ this.flushPendingDelta(turn);
2225
+ this.lastResponseIdValue = done.messageId ? brandResponseId(done.messageId) : null;
2226
+ const nextConv = done.conversationId ? brandConversationId(done.conversationId) : this.snapshot.conversationId;
2227
+ let messages;
2228
+ if (turn.assistantMessageId !== null) {
2229
+ messages = this.snapshot.messages.map(
2230
+ (m) => m.id === turn.assistantMessageId ? finalizeAssistant(m, done) : m
2231
+ );
2232
+ } else {
2233
+ const assistantId = this.newId();
2234
+ turn.assistantMessageId = assistantId;
2235
+ turn.sawDelta = true;
2236
+ const cleared = this.snapshot.messages.map(
2237
+ (m) => m.id === turn.userMessageId && m.pending === true ? stripPending(m) : m
2238
+ );
2239
+ messages = [...cleared, finalizeAssistant(makeAssistant(assistantId, ""), done)];
2240
+ }
2241
+ this.patch({
2242
+ status: "complete",
2243
+ isStreaming: false,
2244
+ error: null,
2245
+ conversationId: nextConv,
2246
+ messages
2247
+ });
2248
+ }
2249
+ applyError(turn, error) {
2250
+ this.flushPendingDelta(turn);
2251
+ this.errorPolicy.onExpectedFailure?.(error);
2252
+ const messages = turn.sawDelta ? this.snapshot.messages : this.snapshot.messages.filter((m) => m.id !== turn.userMessageId);
2253
+ this.patch({ status: "error", isStreaming: false, error, messages });
2254
+ }
2255
+ clearAssistantInProgress(turn) {
2256
+ this.discardPendingDelta();
2257
+ if (turn.assistantMessageId === null) return;
2258
+ const assistantId = turn.assistantMessageId;
2259
+ turn.assistantMessageId = null;
2260
+ turn.sawDelta = false;
2261
+ const messages = this.snapshot.messages.filter((m) => m.id !== assistantId);
2262
+ if (messages.length !== this.snapshot.messages.length) this.patch({ messages });
2263
+ }
2264
+ // ---- auth + request build --------------------------------------------
2265
+ buildSendRequest(turn, convId) {
2266
+ const body = { message: turn.text };
2267
+ return {
2268
+ method: "POST",
2269
+ path: `/widget/v1/conversations/${convId}/messages`,
2270
+ body,
2271
+ // The TURN's own key, not a funnel mint. This is the streaming path, which the funnel deliberately
2272
+ // leaves alone, and the key is the identity of one logical turn: the same value is replayed by the
2273
+ // 404 recreate-and-resend and by the mid-stream refresh replay, so neither duplicates the user's
2274
+ // message. It is SDK-minted (`defaultIdempotencyFactory`), never taken from partner code.
2275
+ headers: { "Idempotency-Key": turn.idempotencyKey }
2276
+ };
2277
+ }
2278
+ async tryForceRefresh() {
2279
+ if (this.auth.mode !== "personalized") return false;
2280
+ try {
2281
+ await this.auth.identity.currentToken({ forceRefresh: true });
2282
+ return true;
2283
+ } catch {
2284
+ return false;
2285
+ }
2286
+ }
2287
+ authRejected() {
2288
+ return makeError("authRejected", false);
2289
+ }
2290
+ };
2291
+ var MESSAGE_MAX_CHARS = 4e3;
2292
+ function validateMessageText(text) {
2293
+ const raw = typeof text === "string" ? text : "";
2294
+ if (raw.trim().length === 0) {
2295
+ return { reason: "empty", error: makeError("validationFailed", false, "message is empty or whitespace-only") };
2296
+ }
2297
+ const codePoints = [...raw].length;
2298
+ if (codePoints > MESSAGE_MAX_CHARS) {
2299
+ return {
2300
+ reason: "too_long",
2301
+ error: makeError(
2302
+ "validationFailed",
2303
+ false,
2304
+ `message is ${codePoints} characters; the server accepts at most ${MESSAGE_MAX_CHARS}`
2305
+ )
2306
+ };
2307
+ }
2308
+ return null;
2309
+ }
2310
+ async function* singleFrameStream(frame) {
2311
+ yield frame;
2312
+ }
2313
+ async function* emptyStream() {
2314
+ }
2315
+
2316
+ // src/core/bootstrap.ts
2317
+ async function bootstrapChat(input, deps) {
2318
+ const { controller } = deps;
2319
+ const petRef2 = input.petRef ?? null;
2320
+ const resume = input.resumeConversationId ?? null;
2321
+ const candidateConversationIds = [];
2322
+ let sawForbidden = false;
2323
+ let sawUnauthorized = false;
2324
+ let sawConversationInitFailure = false;
2325
+ let authBlock = null;
2326
+ const conversationPromise = resume ? Promise.resolve(ok(resume)) : controller.createConversation(petRef2 ? { petRef: petRef2 } : void 0);
2327
+ const promptsPromise = controller.getPrompts(petRef2 !== null ? { petRef: petRef2 } : void 0);
2328
+ const [conversationRes, initialPromptsRes] = await Promise.all([conversationPromise, promptsPromise]);
2329
+ let conversationId2 = null;
2330
+ if (conversationRes.ok) {
2331
+ conversationId2 = conversationRes.value;
2332
+ candidateConversationIds.push(conversationRes.value);
2333
+ controller.adoptConversation(conversationRes.value);
2334
+ } else {
2335
+ const e = conversationRes.error;
2336
+ if (isUnauthorized(e)) {
2337
+ sawUnauthorized = true;
2338
+ authBlock = e;
2339
+ } else if (isForbidden(e)) {
2340
+ sawForbidden = true;
2341
+ sawConversationInitFailure = true;
2342
+ } else {
2343
+ sawConversationInitFailure = true;
2344
+ }
2345
+ }
2346
+ let suggestedPrompts = [];
2347
+ if (initialPromptsRes.ok) {
2348
+ suggestedPrompts = initialPromptsRes.value;
2349
+ } else {
2350
+ recordAuthSignals(initialPromptsRes.error);
2351
+ }
2352
+ function recordAuthSignals(e) {
2353
+ if (isUnauthorized(e)) {
2354
+ sawUnauthorized = true;
2355
+ if (authBlock === null) authBlock = e;
2356
+ } else if (isForbidden(e)) {
2357
+ sawForbidden = true;
2358
+ }
2359
+ }
2360
+ const error = authBlock !== null ? authBlock.displayMessage : null;
2361
+ const warning = error === null && conversationId2 === null && sawConversationInitFailure ? CONVERSATION_NOT_PRIMED_WARNING : null;
2362
+ return Object.freeze({
2363
+ conversationId: conversationId2,
2364
+ petRef: petRef2,
2365
+ suggestedPrompts,
2366
+ error,
2367
+ warning,
2368
+ diagnostics: Object.freeze({
2369
+ candidateConversationIds: Object.freeze([...candidateConversationIds]),
2370
+ sawForbidden,
2371
+ sawUnauthorized,
2372
+ sawConversationInitFailure
2373
+ })
2374
+ });
2375
+ }
2376
+ var CONVERSATION_NOT_PRIMED_WARNING = "Chat is ready. Your first message will start the conversation.";
2377
+ function isUnauthorized(e) {
2378
+ return e.httpStatus === 401 || e.code === "authExpired" || e.code === "authRejected";
2379
+ }
2380
+ function isForbidden(e) {
2381
+ return e.httpStatus === 403 || e.code === "accessDenied";
2382
+ }
2383
+
2384
+ // src/client/pets/petsRepository.ts
2385
+ var PET_NAME_MAX = 100;
2386
+ var PET_SPECIES_MAX = 50;
2387
+ var PET_BREED_MAX = 100;
2388
+ var PET_AGE_YEARS_MAX = 50;
2389
+ var PET_WEIGHT_KG_MAX = 500;
2390
+ var PET_REF_MAX = 128;
2391
+ function invalid(wireMessage) {
2392
+ return makeEverfurError("validationFailed", { retryable: false, wireMessage });
2393
+ }
2394
+ function checkString(field, value, max) {
2395
+ if (typeof value !== "string") return invalid(`${field} must be a string`);
2396
+ const length = serverLength(value);
2397
+ if (length <= max) return null;
2398
+ return invalid(`${field} is ${length} characters; the server accepts at most ${max}`);
2399
+ }
2400
+ function outOfRange(field, value, max) {
2401
+ if (typeof value === "number" && Number.isFinite(value) && value >= 0 && value <= max) return null;
2402
+ return invalid(`${field} must be a finite number between 0 and ${max}`);
2403
+ }
2404
+ function validate(petRef2, profile) {
2405
+ if (typeof petRef2 !== "string") return invalid("pet_ref must be a string");
2406
+ if (petRef2.trim().length === 0) return invalid("pet_ref must not be blank");
2407
+ if (hasLoneSurrogate(petRef2)) return invalid("pet_ref contains an unpaired surrogate and cannot be encoded");
2408
+ if (profile !== void 0 && profile !== null && typeof profile !== "object") {
2409
+ return invalid("profile must be an object");
2410
+ }
2411
+ const checks = [checkString("pet_ref", petRef2, PET_REF_MAX)];
2412
+ if (profile?.name !== void 0) checks.push(checkString("name", profile.name, PET_NAME_MAX));
2413
+ if (profile?.species !== void 0) checks.push(checkString("species", profile.species, PET_SPECIES_MAX));
2414
+ if (profile?.breed !== void 0) checks.push(checkString("breed", profile.breed, PET_BREED_MAX));
2415
+ if (profile?.ageYears !== void 0) checks.push(outOfRange("age_years", profile.ageYears, PET_AGE_YEARS_MAX));
2416
+ if (profile?.weightKg !== void 0) checks.push(outOfRange("weight_kg", profile.weightKg, PET_WEIGHT_KG_MAX));
2417
+ return checks.find((c) => c !== null) ?? null;
2418
+ }
2419
+ function toWire(profile) {
2420
+ if (profile === void 0 || profile === null) return {};
2421
+ return {
2422
+ ...profile.name !== void 0 ? { name: profile.name } : {},
2423
+ ...profile.species !== void 0 ? { species: profile.species } : {},
2424
+ ...profile.breed !== void 0 ? { breed: profile.breed } : {},
2425
+ ...profile.ageYears !== void 0 ? { age_years: profile.ageYears } : {},
2426
+ ...profile.weightKg !== void 0 ? { weight_kg: profile.weightKg } : {}
2427
+ };
2428
+ }
2429
+ function fromWire2(raw, petRef2) {
2430
+ const o = typeof raw === "object" && raw !== null ? raw : {};
2431
+ const str = (v) => typeof v === "string" ? v : null;
2432
+ const num = (v) => typeof v === "number" && Number.isFinite(v) ? v : null;
2433
+ return Object.freeze({
2434
+ petRef: str(o["pet_ref"]) ?? petRef2,
2435
+ name: str(o["name"]),
2436
+ species: str(o["species"]),
2437
+ breed: str(o["breed"]),
2438
+ ageYears: num(o["age_years"]),
2439
+ weightKg: num(o["weight_kg"])
2440
+ });
2441
+ }
2442
+ function createPetsRepository(auth) {
2443
+ return createPetsRepositoryOver(createRequestFunnel({ auth }));
2444
+ }
2445
+ function createPetsRepositoryOver(funnel) {
2446
+ return {
2447
+ async registerPet(petRef2, profile, opts) {
2448
+ const invalid2 = validate(petRef2, profile);
2449
+ if (invalid2 !== null) return err(invalid2);
2450
+ const path = `/widget/v1/pets/${encodeURIComponent(petRef2)}`;
2451
+ const base = { method: "POST", path, body: toWire(profile) };
2452
+ const res = await funnel.send(
2453
+ "pets.registerPet",
2454
+ opts?.signal ? { ...base, signal: opts.signal } : base
2455
+ );
2456
+ if (!res.ok) return err(res.error);
2457
+ return ok(fromWire2(res.value, petRef2));
2458
+ }
2459
+ };
2460
+ }
2461
+
2462
+ // src/client/entitlements/resolve.ts
2463
+ var REQUIRES = Object.freeze({
2464
+ chat: Object.freeze(["chat.message.create"]),
2465
+ records: Object.freeze(["records.upload.create", "records.record.read"]),
2466
+ video: Object.freeze(["video.gait.execute"]),
2467
+ photo: Object.freeze(["photo.checkup.execute"]),
2468
+ animations: Object.freeze(["animations.state.read"])
2469
+ });
2470
+ function requires(name) {
2471
+ return REQUIRES[name];
2472
+ }
2473
+ function deniedDecisionsFor(level, reason) {
2474
+ const disabled = Object.freeze({ reason, level, recoverable: false });
2475
+ const rows = [];
2476
+ const seen = /* @__PURE__ */ new Set();
2477
+ for (const name of Object.keys(REQUIRES)) {
2478
+ for (const resource of REQUIRES[name]) {
2479
+ if (seen.has(resource)) continue;
2480
+ seen.add(resource);
2481
+ rows.push(Object.freeze({ resource, granted: false, disabled }));
2482
+ }
2483
+ }
2484
+ return Object.freeze(rows);
2485
+ }
2486
+ function decideCapability(name, decisions, opts) {
2487
+ if (opts?.isPending === true) {
2488
+ return freezeDecision({ name, enabled: false, isPending: true, limits: {} });
2489
+ }
2490
+ const keys = requires(name);
2491
+ const byResource = /* @__PURE__ */ new Map();
2492
+ for (const decision of decisions) byResource.set(decision.resource, decision);
2493
+ const limits = mergeLimits(keys, byResource);
2494
+ const missing = keys.filter((key) => byResource.get(key)?.granted !== true);
2495
+ if (missing.length === 0) {
2496
+ return freezeDecision({ name, enabled: true, isPending: false, limits });
2497
+ }
2498
+ return freezeDecision({
2499
+ name,
2500
+ enabled: false,
2501
+ isPending: false,
2502
+ limits,
2503
+ disabled: disabledFor(keys, byResource)
2504
+ });
2505
+ }
2506
+ function mergeLimits(keys, byResource) {
2507
+ const out = {};
2508
+ for (const key of keys) {
2509
+ const decisionLimits = byResource.get(key)?.limits;
2510
+ if (!decisionLimits) continue;
2511
+ for (const [limitKey, limitValue] of Object.entries(decisionLimits)) {
2512
+ const existing = out[limitKey];
2513
+ out[limitKey] = existing === void 0 ? limitValue : Math.min(existing, limitValue);
2514
+ }
2515
+ }
2516
+ return out;
2517
+ }
2518
+ function disabledFor(keys, byResource) {
2519
+ for (const key of keys) {
2520
+ const explicit = byResource.get(key)?.disabled;
2521
+ if (explicit) {
2522
+ return Object.freeze({
2523
+ reason: explicit.reason,
2524
+ level: explicit.level,
2525
+ recoverable: explicit.recoverable
2526
+ });
2527
+ }
2528
+ }
2529
+ return Object.freeze({
2530
+ reason: userFacingError("accessDenied"),
2531
+ level: "user_entitlement",
2532
+ recoverable: false
2533
+ });
2534
+ }
2535
+ function freezeDecision(d) {
2536
+ const base = {
2537
+ name: d.name,
2538
+ enabled: d.enabled,
2539
+ isPending: d.isPending,
2540
+ limits: Object.freeze({ ...d.limits })
2541
+ };
2542
+ if (d.disabled !== void 0) base.disabled = d.disabled;
2543
+ return Object.freeze(base);
2544
+ }
2545
+
2546
+ // src/client/theme/tokens.ts
2547
+ function deepFreeze(value) {
2548
+ if (value !== null && typeof value === "object" && !Object.isFrozen(value)) {
2549
+ Object.freeze(value);
2550
+ for (const key of Object.keys(value)) {
2551
+ deepFreeze(value[key]);
2552
+ }
2553
+ }
2554
+ return value;
2555
+ }
2556
+ var SPACE = { xs: 4, sm: 8, md: 12, lg: 16, xl: 24, xxl: 32 };
2557
+ var RADIUS = { tile: 5, xs: 6, sm: 10, md: 14, lg: 20, xl: 28, pill: 500 };
2558
+ var TYPE_SIZE = {
2559
+ nano: 8,
2560
+ small: 9,
2561
+ micro: 10,
2562
+ tiny: 11,
2563
+ caption: 12,
2564
+ bodyTight: 13,
2565
+ body: 14,
2566
+ subtitle: 16,
2567
+ heading: 18,
2568
+ verdict: 24
2569
+ };
2570
+ var LINE_HEIGHT = { tight: 1.15, snug: 1.3, normal: 1.4, relaxed: 1.55 };
2571
+ var WEIGHT = { regular: "400", medium: "500", bold: "700" };
2572
+ var LETTER_SPACING = {
2573
+ eyebrow: 1,
2574
+ monoWide: 0.9,
2575
+ headerBrand: -0.42,
2576
+ tight: -0.35
2577
+ };
2578
+ function baseType() {
2579
+ return {
2580
+ family: "System",
2581
+ mono: "monospace",
2582
+ fontUrl: null,
2583
+ size: TYPE_SIZE,
2584
+ lineHeight: LINE_HEIGHT,
2585
+ weight: WEIGHT,
2586
+ letterSpacing: LETTER_SPACING
2587
+ };
2588
+ }
2589
+ var MOTION = {
2590
+ duration: { instant: 80, fast: 140, normal: 220, slow: 320 },
2591
+ spring: { gentle: { damping: 18, stiffness: 200 } },
2592
+ easing: { standard: "cubic-bezier(0.4, 0, 0.2, 1)" },
2593
+ reducedMotion: false
2594
+ };
2595
+ var LIGHT_COLOR = {
2596
+ brand: "#10462E",
2597
+ brandSoft: "rgba(16,70,46,0.10)",
2598
+ brandSofter: "rgba(16,70,46,0.15)",
2599
+ brandBorder: "rgba(16,70,46,0.18)",
2600
+ borderHairlineGreen: "rgba(16,70,46,0.25)",
2601
+ surface: "#FFFFFF",
2602
+ surfaceCream: "#FDFBF8",
2603
+ surfaceSubtle: "#EFE9E3",
2604
+ background: "#FFFFFF",
2605
+ borderRingCream: "#D8D2C8",
2606
+ text: {
2607
+ primary: "#111111",
2608
+ secondary: "#0E462E",
2609
+ muted: "#6E6660",
2610
+ placeholder: "rgba(0,0,0,0.30)",
2611
+ onBrand: "#FFFFFF",
2612
+ metaCool: "#3D3D3D"
2613
+ },
2614
+ primary: "#10462E",
2615
+ onPrimary: "#FFFFFF",
2616
+ accent: "#10462E",
2617
+ onAccent: "#FFFFFF",
2618
+ accentEdge: "#07C168",
2619
+ success: "#07C168",
2620
+ danger: "#B91C1C",
2621
+ errorRed: "#FF1B00",
2622
+ warningStrong: "#A45610",
2623
+ cautionAccent: "#D9821D",
2624
+ riskConcern: "#EFA700",
2625
+ badgeBgPositive: "rgba(7,193,104,0.12)",
2626
+ badgeBgCaution: "rgba(217,130,29,0.14)",
2627
+ badgeBgCritical: "rgba(185,28,28,0.12)",
2628
+ badgeBgNeutral: "rgba(110,102,96,0.12)",
2629
+ bubbleUser: "#10462E",
2630
+ bubbleAssistant: "#FFFFFF",
2631
+ skeleton: "#EFE9E3",
2632
+ scanButtonPink: "#FFC3BC",
2633
+ checkupCardLowRiskBg: "rgba(7,193,104,0.10)",
2634
+ checkupCardConcernBg: "rgba(239,167,0,0.10)"
2635
+ };
2636
+ var EVERFUR_LIGHT = deepFreeze({
2637
+ brightness: "light",
2638
+ meta: { displayName: "Everfur", logoUrl: null, placeholder: null, hidePoweredBy: false },
2639
+ color: LIGHT_COLOR,
2640
+ space: SPACE,
2641
+ radius: RADIUS,
2642
+ type: baseType(),
2643
+ motion: MOTION
2644
+ });
2645
+ var DARK_COLOR = {
2646
+ brand: "#6BD39A",
2647
+ brandSoft: "rgba(107,211,154,0.12)",
2648
+ brandSofter: "rgba(107,211,154,0.18)",
2649
+ brandBorder: "rgba(107,211,154,0.22)",
2650
+ borderHairlineGreen: "rgba(107,211,154,0.28)",
2651
+ surface: "#1C1F23",
2652
+ surfaceCream: "#23272C",
2653
+ surfaceSubtle: "#23272C",
2654
+ background: "#15171A",
2655
+ borderRingCream: "#3A3F45",
2656
+ text: {
2657
+ primary: "#F5F3F0",
2658
+ secondary: "#A9E4C4",
2659
+ muted: "#9A938C",
2660
+ placeholder: "rgba(255,255,255,0.35)",
2661
+ onBrand: "#0E1F17",
2662
+ metaCool: "#C9C9C9"
2663
+ },
2664
+ primary: "#6BD39A",
2665
+ onPrimary: "#0E1F17",
2666
+ accent: "#6BD39A",
2667
+ onAccent: "#0E1F17",
2668
+ accentEdge: "#34D888",
2669
+ success: "#07C168",
2670
+ danger: "#B91C1C",
2671
+ errorRed: "#FF1B00",
2672
+ warningStrong: "#A45610",
2673
+ cautionAccent: "#D9821D",
2674
+ riskConcern: "#EFA700",
2675
+ badgeBgPositive: "rgba(7,193,104,0.18)",
2676
+ badgeBgCaution: "rgba(217,130,29,0.20)",
2677
+ badgeBgCritical: "rgba(185,28,28,0.22)",
2678
+ badgeBgNeutral: "rgba(255,255,255,0.10)",
2679
+ bubbleUser: "#6BD39A",
2680
+ bubbleAssistant: "#1C1F23",
2681
+ skeleton: "#23272C",
2682
+ scanButtonPink: "#FFC3BC",
2683
+ checkupCardLowRiskBg: "rgba(7,193,104,0.16)",
2684
+ checkupCardConcernBg: "rgba(239,167,0,0.16)"
2685
+ };
2686
+ var EVERFUR_DARK = deepFreeze({
2687
+ brightness: "dark",
2688
+ meta: { displayName: "Everfur", logoUrl: null, placeholder: null, hidePoweredBy: false },
2689
+ color: DARK_COLOR,
2690
+ space: SPACE,
2691
+ radius: RADIUS,
2692
+ type: baseType(),
2693
+ motion: MOTION
2694
+ });
2695
+
2696
+ // src/client/theme/resolve.ts
2697
+ function isEmptyBranding(b) {
2698
+ return b.displayName === null && b.logoUrl === null && b.primaryColor === null && b.accentColor === null && b.brightness === null && b.fontFamily === null && b.fontUrl === null && b.placeholder === null && b.hidePoweredBy === null;
2699
+ }
2700
+ function parseClientBranding(json) {
2701
+ if (json === null || typeof json !== "object") return null;
2702
+ const raw = json;
2703
+ const branding = {
2704
+ displayName: parseNonEmptyString(pick(raw, "display_name", "displayName")),
2705
+ logoUrl: parseNonEmptyString(pick(raw, "logo_url", "logoUrl")),
2706
+ primaryColor: parseColor(pick(raw, "primary_color", "primaryColor")),
2707
+ accentColor: parseColor(pick(raw, "accent_color", "accentColor")),
2708
+ brightness: parseBrightness(pick(raw, "brightness")),
2709
+ fontFamily: parseNonEmptyString(pick(raw, "font_family", "fontFamily")),
2710
+ fontUrl: parseNonEmptyString(pick(raw, "font_url", "fontUrl")),
2711
+ placeholder: parseNonEmptyString(pick(raw, "chat_placeholder", "placeholder", "chatPlaceholder")),
2712
+ hidePoweredBy: parseBool(pick(raw, "hide_powered_by", "hidePoweredBy"))
2713
+ };
2714
+ return isEmptyBranding(branding) ? null : Object.freeze(branding);
2715
+ }
2716
+ function parseBool(value) {
2717
+ if (typeof value === "boolean") return value;
2718
+ if (typeof value === "string") {
2719
+ const lower = value.trim().toLowerCase();
2720
+ if (lower === "true") return true;
2721
+ if (lower === "false") return false;
2722
+ }
2723
+ return null;
2724
+ }
2725
+ function pick(raw, ...keys) {
2726
+ for (const key of keys) {
2727
+ if (Object.prototype.hasOwnProperty.call(raw, key)) {
2728
+ const value = raw[key];
2729
+ if (value !== void 0) return value;
2730
+ }
2731
+ }
2732
+ return void 0;
2733
+ }
2734
+ function parseNonEmptyString(value) {
2735
+ if (typeof value !== "string") return null;
2736
+ const trimmed = value.trim();
2737
+ return trimmed.length === 0 ? null : trimmed;
2738
+ }
2739
+ function parseBrightness(value) {
2740
+ if (typeof value !== "string") return null;
2741
+ const lower = value.trim().toLowerCase();
2742
+ return lower === "light" || lower === "dark" ? lower : null;
2743
+ }
2744
+ function parseColor(value) {
2745
+ const rgba = toRgba(value);
2746
+ return rgba === null ? null : normalizeRgba(rgba);
2747
+ }
2748
+ function toRgba(value) {
2749
+ if (typeof value === "number") return argbIntToRgba(value);
2750
+ if (typeof value !== "string") return null;
2751
+ const s = value.trim();
2752
+ if (s.length === 0) return null;
2753
+ if (s.startsWith("#")) return fromHex(s.slice(1));
2754
+ if (s.toLowerCase().startsWith("0x")) return fromArgbHex(s.slice(2));
2755
+ if (s.toLowerCase().startsWith("rgb")) return fromRgbFunc(s);
2756
+ if (/^[0-9a-fA-F]+$/.test(s)) {
2757
+ const hex = fromHex(s);
2758
+ if (hex !== null) return hex;
2759
+ }
2760
+ if (/^\d+$/.test(s)) return argbIntToRgba(Number.parseInt(s, 10));
2761
+ return null;
2762
+ }
2763
+ function fromHex(hex) {
2764
+ const h = hex.trim();
2765
+ if (!/^[0-9a-fA-F]+$/.test(h)) return null;
2766
+ if (h.length === 3) {
2767
+ const r = dup(h[0]);
2768
+ const g = dup(h[1]);
2769
+ const b = dup(h[2]);
2770
+ return { r, g, b, a: 1 };
2771
+ }
2772
+ if (h.length === 6) {
2773
+ return { r: byte(h, 0), g: byte(h, 2), b: byte(h, 4), a: 1 };
2774
+ }
2775
+ if (h.length === 8) {
2776
+ const a = byte(h, 0);
2777
+ return { r: byte(h, 2), g: byte(h, 4), b: byte(h, 6), a: a / 255 };
2778
+ }
2779
+ return null;
2780
+ }
2781
+ function fromArgbHex(hex) {
2782
+ return fromHex(hex);
2783
+ }
2784
+ function fromRgbFunc(input) {
2785
+ const open = input.indexOf("(");
2786
+ const close = input.indexOf(")");
2787
+ if (open < 0 || close < 0 || close < open) return null;
2788
+ const parts = input.slice(open + 1, close).split(",").map((p) => p.trim());
2789
+ if (parts.length < 3) return null;
2790
+ const r = clampByte(Number(parts[0]));
2791
+ const g = clampByte(Number(parts[1]));
2792
+ const b = clampByte(Number(parts[2]));
2793
+ if (r === null || g === null || b === null) return null;
2794
+ let a = 1;
2795
+ if (parts.length >= 4) {
2796
+ const alpha = Number(parts[3]);
2797
+ if (!Number.isFinite(alpha)) return null;
2798
+ a = Math.min(1, Math.max(0, alpha));
2799
+ }
2800
+ return { r, g, b, a };
2801
+ }
2802
+ function argbIntToRgba(n) {
2803
+ if (!Number.isFinite(n)) return null;
2804
+ const int = Math.trunc(n) >>> 0;
2805
+ const a = int >>> 24 & 255;
2806
+ return {
2807
+ r: int >>> 16 & 255,
2808
+ g: int >>> 8 & 255,
2809
+ b: int & 255,
2810
+ // A 0x00RRGGBB with no alpha byte reads as fully transparent; treat a zero alpha byte as opaque so a
2811
+ // bare 0xRRGGBB (or small decimal) is not silently invisible.
2812
+ a: a === 0 ? 1 : a / 255
2813
+ };
2814
+ }
2815
+ function byte(hex, at) {
2816
+ return Number.parseInt(hex.slice(at, at + 2), 16);
2817
+ }
2818
+ function dup(nibble) {
2819
+ return Number.parseInt(`${nibble ?? "0"}${nibble ?? "0"}`, 16);
2820
+ }
2821
+ function clampByte(n) {
2822
+ if (!Number.isFinite(n)) return null;
2823
+ return Math.min(255, Math.max(0, Math.round(n)));
2824
+ }
2825
+ function normalizeRgba(rgba) {
2826
+ if (rgba.a >= 1) {
2827
+ return `#${hex2(rgba.r)}${hex2(rgba.g)}${hex2(rgba.b)}`.toUpperCase();
2828
+ }
2829
+ const a = Math.round(rgba.a * 1e3) / 1e3;
2830
+ return `rgba(${rgba.r},${rgba.g},${rgba.b},${a})`;
2831
+ }
2832
+ function hex2(n) {
2833
+ return n.toString(16).padStart(2, "0");
2834
+ }
2835
+ var NEAR_BLACK = "#111111";
2836
+ var WHITE = "#FFFFFF";
2837
+ function readableOn(background) {
2838
+ const rgba = toRgba(background);
2839
+ if (rgba === null) return WHITE;
2840
+ const bg = relativeLuminance(rgba);
2841
+ const black = relativeLuminance({ r: 17, g: 17, b: 17});
2842
+ const white = relativeLuminance({ r: 255, g: 255, b: 255});
2843
+ const contrastBlack = contrastRatio(bg, black);
2844
+ const contrastWhite = contrastRatio(bg, white);
2845
+ return contrastWhite >= contrastBlack ? WHITE : NEAR_BLACK;
2846
+ }
2847
+ function relativeLuminance(rgba) {
2848
+ const r = linearize(rgba.r / 255);
2849
+ const g = linearize(rgba.g / 255);
2850
+ const b = linearize(rgba.b / 255);
2851
+ return 0.2126 * r + 0.7152 * g + 0.0722 * b;
2852
+ }
2853
+ function linearize(channel) {
2854
+ return channel <= 0.03928 ? channel / 12.92 : Math.pow((channel + 0.055) / 1.055, 2.4);
2855
+ }
2856
+ function contrastRatio(l1, l2) {
2857
+ const lighter = Math.max(l1, l2);
2858
+ const darker = Math.min(l1, l2);
2859
+ return (lighter + 0.05) / (darker + 0.05);
2860
+ }
2861
+ function hardenHttpsUrl(url) {
2862
+ if (url === null) return null;
2863
+ const trimmed = url.trim();
2864
+ if (trimmed.length === 0) return null;
2865
+ return /^https:\/\/\S+$/i.test(trimmed) ? trimmed : null;
2866
+ }
2867
+ function withServerBranding(base, b) {
2868
+ if (b === null || isEmptyBranding(b)) return base;
2869
+ const palette = b.brightness !== null && b.brightness !== base.brightness ? b.brightness === "dark" ? EVERFUR_DARK : EVERFUR_LIGHT : base;
2870
+ const primary = b.primaryColor ?? palette.color.primary;
2871
+ const accent = b.accentColor ?? palette.color.accent;
2872
+ const pr = b.primaryColor !== null ? toRgba(primary) : null;
2873
+ const lift = (c) => Math.round(c + (255 - c) * 0.4);
2874
+ const brandFamily = pr !== null ? {
2875
+ brand: primary,
2876
+ bubbleUser: primary,
2877
+ text: { ...palette.color.text, secondary: primary },
2878
+ brandSoft: `rgba(${pr.r}, ${pr.g}, ${pr.b}, 0.10)`,
2879
+ brandSofter: `rgba(${pr.r}, ${pr.g}, ${pr.b}, 0.15)`,
2880
+ brandBorder: `rgba(${pr.r}, ${pr.g}, ${pr.b}, 0.20)`,
2881
+ borderHairlineGreen: `rgba(${pr.r}, ${pr.g}, ${pr.b}, 0.28)`,
2882
+ accentEdge: `rgb(${lift(pr.r)}, ${lift(pr.g)}, ${lift(pr.b)})`
2883
+ } : {};
2884
+ const next = {
2885
+ brightness: palette.brightness,
2886
+ meta: {
2887
+ displayName: b.displayName ?? palette.meta.displayName,
2888
+ logoUrl: b.logoUrl ?? palette.meta.logoUrl,
2889
+ placeholder: b.placeholder ?? palette.meta.placeholder,
2890
+ hidePoweredBy: b.hidePoweredBy ?? palette.meta.hidePoweredBy
2891
+ },
2892
+ color: {
2893
+ ...palette.color,
2894
+ ...brandFamily,
2895
+ primary,
2896
+ accent,
2897
+ // onPrimary/onAccent are recomputed by resolveTheme; carry the palette defaults for a standalone call.
2898
+ onPrimary: palette.color.onPrimary,
2899
+ onAccent: palette.color.onAccent
2900
+ },
2901
+ space: palette.space,
2902
+ radius: palette.radius,
2903
+ type: {
2904
+ ...palette.type,
2905
+ family: b.fontFamily ?? palette.type.family,
2906
+ fontUrl: b.fontUrl ?? palette.type.fontUrl
2907
+ },
2908
+ motion: palette.motion
2909
+ };
2910
+ return deepFreeze(next);
2911
+ }
2912
+ var DEFAULT_DISPLAY_NAME = "Everfur";
2913
+ function resolveTheme(input) {
2914
+ const scheme = input?.colorScheme === "dark" ? "dark" : "light";
2915
+ const systemBase = scheme === "dark" ? EVERFUR_DARK : EVERFUR_LIGHT;
2916
+ const withClient = withServerBranding(systemBase, input?.clientOverride ?? null);
2917
+ const merged = withServerBranding(withClient, input?.branding ?? null);
2918
+ return finalize(merged, input?.reducedMotion === true);
2919
+ }
2920
+ function finalize(theme, reducedMotion) {
2921
+ const primary = theme.color.primary;
2922
+ const accent = theme.color.accent;
2923
+ const displayName = theme.meta.displayName.trim().length === 0 ? DEFAULT_DISPLAY_NAME : theme.meta.displayName;
2924
+ const logoUrl = hardenHttpsUrl(theme.meta.logoUrl);
2925
+ const fontUrl = hardenHttpsUrl(theme.type.fontUrl);
2926
+ const motion = reducedMotion ? {
2927
+ duration: { instant: 0, fast: 0, normal: 0, slow: 0 },
2928
+ // Stiffen the spring so it settles immediately with no perceptible bounce.
2929
+ spring: { gentle: { damping: 100, stiffness: 1e3 } },
2930
+ easing: theme.motion.easing,
2931
+ reducedMotion: true
2932
+ } : theme.motion;
2933
+ const finalized = {
2934
+ brightness: theme.brightness,
2935
+ meta: { displayName, logoUrl, placeholder: theme.meta.placeholder, hidePoweredBy: theme.meta.hidePoweredBy },
2936
+ color: {
2937
+ ...theme.color,
2938
+ primary,
2939
+ accent,
2940
+ onPrimary: readableOn(primary),
2941
+ onAccent: readableOn(accent)
2942
+ },
2943
+ space: theme.space,
2944
+ radius: theme.radius,
2945
+ type: { ...theme.type, fontUrl },
2946
+ motion
2947
+ };
2948
+ return deepFreeze(finalized);
2949
+ }
2950
+
2951
+ // src/client/entitlements/entitlementRepository.ts
2952
+ var ENTITLEMENTS_PATH = "/widget/v1/entitlements";
2953
+ var HTTP_NOT_MODIFIED = 304;
2954
+ var NOT_MODIFIED = Object.freeze({ kind: "notModified" });
2955
+ async function fetchEntitlements(auth, args = {}, funnel = createRequestFunnel({ auth })) {
2956
+ const result = await funnel.send(
2957
+ "entitlements.fetch",
2958
+ buildRequest(args)
2959
+ );
2960
+ if (!result.ok) {
2961
+ if (result.error.httpStatus === HTTP_NOT_MODIFIED) return NOT_MODIFIED;
2962
+ return { kind: "failed", error: result.error };
2963
+ }
2964
+ return parseUpdated(result.value);
2965
+ }
2966
+ var REGION_MAX = 64;
2967
+ function buildRequest(args) {
2968
+ const headers = {};
2969
+ if (isFiniteNumber(args.cachedRevision)) {
2970
+ headers["if-none-match"] = `"${args.cachedRevision}"`;
2971
+ }
2972
+ if (args.region && args.region.length <= REGION_MAX) {
2973
+ return { method: "GET", path: ENTITLEMENTS_PATH, headers, query: { region: args.region } };
2974
+ }
2975
+ return { method: "GET", path: ENTITLEMENTS_PATH, headers };
2976
+ }
2977
+ function parseUpdated(body) {
2978
+ if (body === null || typeof body !== "object") return malformed();
2979
+ if (!isFiniteNumber(body.revision)) return malformed();
2980
+ const region = typeof body.region === "string" ? body.region : "";
2981
+ const ttlSeconds = isFiniteNumber(body.ttl_seconds) ? body.ttl_seconds : 0;
2982
+ return Object.freeze({
2983
+ kind: "updated",
2984
+ revision: body.revision,
2985
+ region,
2986
+ ttlSeconds,
2987
+ decisions: mapCapabilities(body.capabilities),
2988
+ // Branding is ADDITIVE and orthogonal to capabilities: a parse fault here NEVER affects the decisions and
2989
+ // fails closed to null (the compiled default theme). It cannot make a granted capability un-render.
2990
+ branding: parseBranding(body)
2991
+ });
2992
+ }
2993
+ function parseBranding(body) {
2994
+ const direct = parseClientBranding(body.branding);
2995
+ if (direct !== null) return direct;
2996
+ const hints = body.render_hints;
2997
+ if (hints !== null && typeof hints === "object") {
2998
+ const nested = parseClientBranding(hints.branding);
2999
+ if (nested !== null) return nested;
3000
+ return parseClientBranding(hints);
3001
+ }
3002
+ return null;
3003
+ }
3004
+ function mapCapabilities(capabilities) {
3005
+ if (capabilities === null || typeof capabilities !== "object") return Object.freeze([]);
3006
+ const out = [];
3007
+ for (const [resource, value] of Object.entries(capabilities)) {
3008
+ if (isEnabled(value)) out.push(Object.freeze({ resource, granted: true }));
3009
+ }
3010
+ return Object.freeze(out);
3011
+ }
3012
+ function isEnabled(value) {
3013
+ return typeof value === "object" && value !== null && value.enabled === true;
3014
+ }
3015
+ function malformed() {
3016
+ return {
3017
+ kind: "failed",
3018
+ error: makeEverfurError("internalError", {
3019
+ retryable: true,
3020
+ wireMessage: "malformed entitlements response"
3021
+ })
3022
+ };
3023
+ }
3024
+ function isFiniteNumber(value) {
3025
+ return typeof value === "number" && Number.isFinite(value);
3026
+ }
3027
+
3028
+ // src/core/entitlements/entitlementPoller.ts
3029
+ var MIN_POLL_INTERVAL_SECONDS = 30;
3030
+ function createEntitlementPoller(deps) {
3031
+ const scheduler = deps.scheduler ?? defaultScheduler;
3032
+ const resolve = deps.resolve ?? fetchEntitlements;
3033
+ const floorSeconds = Math.max(1, deps.floorSeconds ?? MIN_POLL_INTERVAL_SECONDS);
3034
+ const rng = deps.rng ?? Math.random;
3035
+ const jitteredFloorSeconds = () => floorSeconds + rng() * floorSeconds;
3036
+ let started = false;
3037
+ let stopped = false;
3038
+ let timer = null;
3039
+ let cachedRevision = null;
3040
+ let lastCadenceSeconds = floorSeconds;
3041
+ let generation = 0;
3042
+ const clearTimer = () => {
3043
+ if (timer !== null) {
3044
+ scheduler.clear(timer);
3045
+ timer = null;
3046
+ }
3047
+ };
3048
+ const schedule = (seconds) => {
3049
+ if (stopped) return;
3050
+ lastCadenceSeconds = Math.max(floorSeconds, seconds);
3051
+ timer = scheduler.set(() => {
3052
+ timer = null;
3053
+ void tick();
3054
+ }, lastCadenceSeconds * 1e3);
3055
+ };
3056
+ const tick = async () => {
3057
+ if (stopped) return;
3058
+ const myGen = generation;
3059
+ const args = deps.region ? { cachedRevision, region: deps.region } : { cachedRevision };
3060
+ let resolution;
3061
+ try {
3062
+ resolution = await resolve(deps.authFor(), args);
3063
+ } catch (cause) {
3064
+ deps.telemetry?.track("sdk.entitlements.poll_error", { reason: describe(cause) });
3065
+ if (!stopped && myGen === generation) schedule(jitteredFloorSeconds());
3066
+ return;
3067
+ }
3068
+ if (stopped || myGen !== generation) return;
3069
+ switch (resolution.kind) {
3070
+ case "updated":
3071
+ cachedRevision = resolution.revision;
3072
+ deps.update(resolution.decisions, resolution.branding ?? null);
3073
+ schedule(resolution.ttlSeconds);
3074
+ return;
3075
+ case "notModified":
3076
+ schedule(lastCadenceSeconds);
3077
+ return;
3078
+ case "failed":
3079
+ deps.telemetry?.track("sdk.entitlements.poll_failed", { code: resolution.error.code });
3080
+ schedule(jitteredFloorSeconds());
3081
+ return;
3082
+ default:
3083
+ schedule(jitteredFloorSeconds());
3084
+ }
3085
+ };
3086
+ return {
3087
+ start() {
3088
+ if (started || stopped) return;
3089
+ started = true;
3090
+ void tick();
3091
+ },
3092
+ stop() {
3093
+ if (stopped) return;
3094
+ stopped = true;
3095
+ generation++;
3096
+ clearTimer();
3097
+ },
3098
+ refresh() {
3099
+ if (stopped || !started) return;
3100
+ generation++;
3101
+ cachedRevision = null;
3102
+ clearTimer();
3103
+ void tick();
3104
+ }
3105
+ };
3106
+ }
3107
+ var defaultScheduler = {
3108
+ set(callback, ms) {
3109
+ const handle = setTimeout(callback, ms);
3110
+ handle.unref?.();
3111
+ return handle;
3112
+ },
3113
+ clear(handle) {
3114
+ clearTimeout(handle);
3115
+ }
3116
+ };
3117
+ function describe(cause) {
3118
+ return cause instanceof Error ? cause.message : "poll failed";
3119
+ }
3120
+
3121
+ // src/core/runtime.ts
3122
+ function compiledDefaultDecisions() {
3123
+ return Object.freeze([Object.freeze({ resource: "chat.message.create", granted: true })]);
3124
+ }
3125
+ function createEntitlementStore(floorDecisions = compiledDefaultDecisions) {
3126
+ const listeners = /* @__PURE__ */ new Set();
3127
+ let snapshot = Object.freeze({
3128
+ decisions: floorDecisions(),
3129
+ isPending: false,
3130
+ branding: null
3131
+ });
3132
+ const emit = () => {
3133
+ for (const listener of listeners) listener();
3134
+ };
3135
+ return {
3136
+ subscribe(listener) {
3137
+ listeners.add(listener);
3138
+ return () => {
3139
+ listeners.delete(listener);
3140
+ };
3141
+ },
3142
+ getSnapshot() {
3143
+ return snapshot;
3144
+ },
3145
+ set(next) {
3146
+ snapshot = Object.freeze({
3147
+ decisions: Object.freeze([...next.decisions]),
3148
+ isPending: next.isPending,
3149
+ // Branding is additive; default to null (the compiled Everfur theme) when a caller omits it.
3150
+ branding: next.branding ?? null
3151
+ });
3152
+ emit();
3153
+ },
3154
+ reset() {
3155
+ snapshot = Object.freeze({
3156
+ decisions: floorDecisions(),
3157
+ isPending: false,
3158
+ branding: null
3159
+ });
3160
+ emit();
3161
+ }
3162
+ };
3163
+ }
3164
+ function createEverfurRuntime(input, opts) {
3165
+ return new EverfurRuntimeImpl(input, opts);
3166
+ }
3167
+ var PER_USER_KV_KEYS = Object.freeze([]);
3168
+ var EverfurRuntimeImpl = class {
3169
+ constructor(input, opts) {
3170
+ /**
3171
+ * One `x-everfur-session-id` for the life of this runtime. It MUST be stable across requests: the server
3172
+ * derives the anonymous identity from it, so a per-request value makes every call a different user and the
3173
+ * create/send pair can never agree. Minted here, never persisted, never a credential.
3174
+ */
3175
+ /**
3176
+ * Rotated on sign-out. The server derives the ANONYMOUS identity from this
3177
+ * (`user_ref = f"anon-{session_id}"`), so keeping it across a logout would leave the next anonymous
3178
+ * session inheriting the previous user's server-side conversation history.
3179
+ */
3180
+ this.sessionId = newSessionId();
3181
+ // ONE ref-counted controller table keyed by `${epoch}|${kind}|${scopeKey}`, plus each controller's
3182
+ // destroyer, so a re-scope / dispose can tear every open controller down without naming its type.
3183
+ this.entries = /* @__PURE__ */ new Map();
3184
+ this.destroyers = /* @__PURE__ */ new Map();
3185
+ this.epoch = 0;
3186
+ this.disposed = false;
3187
+ const cfg = input.config;
3188
+ if (cfg.secureStore !== void 0 && cfg.secureStore.isAvailable === true) {
3189
+ throw new EverfurConfigError(
3190
+ "invalid-argument",
3191
+ "config.secureStore is not yet consumable: SDK token persistence is unimplemented. Omit secureStore to keep memory-only tokens (SPEC-10 \xA75.3)."
3192
+ );
3193
+ }
3194
+ this.telemetry = cfg.telemetry ?? noopTelemetry;
3195
+ const publishableKey = typeof cfg?.publishableKey === "string" ? cfg.publishableKey.trim() : "";
3196
+ let failure = checkPublishableKey(cfg?.publishableKey);
3197
+ const transportInjected = cfg.transport !== void 0;
3198
+ let resolvedTransport;
3199
+ if (failure !== null) {
3200
+ resolvedTransport = refusingTransport(failure);
3201
+ } else if (cfg.transport !== void 0) {
3202
+ resolvedTransport = cfg.transport;
3203
+ } else {
3204
+ const resolved = tryResolveClient(cfg);
3205
+ if (resolved.ok) {
3206
+ resolvedTransport = createHttpTransport({
3207
+ config: resolved.config,
3208
+ ...opts?.eventSourceFactory ? { eventSourceFactory: opts.eventSourceFactory } : {}
3209
+ });
3210
+ } else {
3211
+ failure = resolved.failure;
3212
+ resolvedTransport = refusingTransport(resolved.failure);
3213
+ }
3214
+ }
3215
+ this.configFailure = failure;
3216
+ this.publishableKey = failure === null ? publishableKey : "";
3217
+ this.transport = resolvedTransport;
3218
+ if (failure !== null) {
3219
+ reportConfigFailure(failure, this.telemetry);
3220
+ }
3221
+ this.errorPolicy = cfg.errorPolicy;
3222
+ this.camera = cfg.camera ?? unavailableCamera;
3223
+ this.upload = cfg.upload ?? unavailableUpload;
3224
+ this.uploadTransport = cfg.uploadTransport ?? unavailableUploadTransport;
3225
+ this.imageCache = cfg.imageCache ?? noopImageCache;
3226
+ this.kv = cfg.storage ?? createInMemoryKv();
3227
+ this.currentUser = input.user;
3228
+ this.identity = input.user ? createIdentityProvider(input.user.userRef, input.user.getToken) : null;
3229
+ this.activePet = input.activePet;
3230
+ this.store = failure === null ? createEntitlementStore() : createEntitlementStore(() => deniedDecisionsFor("sdk_config", userFacingError("accessDenied")));
3231
+ this.services = {
3232
+ authFor: (userRef2) => this.buildAuth(userRef2),
3233
+ telemetry: this.telemetry,
3234
+ errorPolicy: this.errorPolicy,
3235
+ camera: this.camera,
3236
+ upload: this.upload,
3237
+ uploadTransport: this.uploadTransport,
3238
+ imageCache: this.imageCache,
3239
+ kv: this.kv
3240
+ };
3241
+ this.registry = {
3242
+ services: this.services,
3243
+ acquireChat: (scope) => this.acquireInternal(
3244
+ "chat",
3245
+ `${scope.userRef ?? ""}|${scope.petRef ?? ""}|${scope.conversationId ?? ""}`,
3246
+ () => this.buildChatController(scope),
3247
+ (controller) => controller.dispose()
3248
+ ),
3249
+ releaseChat: (controller) => this.releaseInternal(controller),
3250
+ acquire: (kind, scopeKey, create, destroy) => this.acquireInternal(kind, scopeKey, create, destroy),
3251
+ release: (controller) => this.releaseInternal(controller)
3252
+ };
3253
+ this.entitlements = this.store;
3254
+ const shouldPoll = failure === null && (opts?.startEntitlementPolling ?? !transportInjected);
3255
+ this.poller = shouldPoll ? this.buildPoller(opts?.pollScheduler) : null;
3256
+ this.poller?.start();
3257
+ }
3258
+ get isDisposed() {
3259
+ return this.disposed;
3260
+ }
3261
+ /**
3262
+ * Build the entitlement poller. `authFor` re-derives the device AuthContext each poll (so a token refresh /
3263
+ * re-scope is reflected), and `update` feeds the resolved decisions into the render store. The SERVER stays
3264
+ * authoritative; this only populates what the SDK renders.
3265
+ */
3266
+ buildPoller(scheduler) {
3267
+ return createEntitlementPoller({
3268
+ authFor: () => this.buildAuth(this.currentUser?.userRef ?? null),
3269
+ update: (decisions, branding) => this.updateEntitlements({ decisions, isPending: false, branding }),
3270
+ telemetry: this.telemetry,
3271
+ ...scheduler ? { scheduler } : {}
3272
+ });
3273
+ }
3274
+ // ---- ref-counted acquire / release (epoch-keyed) -----------------------
3275
+ acquireInternal(kind, scopeKey, create, destroy) {
3276
+ const key = `${this.epoch}|${kind}|${scopeKey}`;
3277
+ const existing = this.entries.get(key);
3278
+ if (existing) {
3279
+ existing.refCount += 1;
3280
+ return existing.controller;
3281
+ }
3282
+ const controller = create();
3283
+ this.entries.set(key, { controller, refCount: 1 });
3284
+ this.destroyers.set(controller, destroy);
3285
+ return controller;
3286
+ }
3287
+ releaseInternal(controller) {
3288
+ for (const [key, entry] of this.entries) {
3289
+ if (entry.controller !== controller) continue;
3290
+ entry.refCount -= 1;
3291
+ if (entry.refCount <= 0) {
3292
+ this.runDestroyer(controller);
3293
+ this.entries.delete(key);
3294
+ }
3295
+ return;
3296
+ }
3297
+ }
3298
+ runDestroyer(controller) {
3299
+ const destroy = this.destroyers.get(controller);
3300
+ this.destroyers.delete(controller);
3301
+ if (destroy) destroy(controller);
3302
+ }
3303
+ // ---- controller construction (only the spine capability is built here) -
3304
+ buildChatController(scope) {
3305
+ const controller = createChatController({
3306
+ auth: this.buildAuth(scope.userRef),
3307
+ telemetry: this.telemetry,
3308
+ ...this.errorPolicy ? { errorPolicy: this.errorPolicy } : {},
3309
+ initialConversationId: scope.conversationId
3310
+ });
3311
+ const input = {};
3312
+ if (scope.petRef !== null) input.petRef = scope.petRef;
3313
+ if (scope.conversationId !== null) input.resumeConversationId = scope.conversationId;
3314
+ void bootstrapChat(input, { controller }).then((result) => controller.adoptPrompts(result.suggestedPrompts)).catch(() => {
3315
+ });
3316
+ return controller;
3317
+ }
3318
+ buildAuth(scopeUserRef) {
3319
+ if (this.identity !== null && this.currentUser !== null) {
3320
+ return {
3321
+ mode: "personalized",
3322
+ transport: this.transport,
3323
+ identity: this.identity,
3324
+ userRef: this.currentUser.userRef,
3325
+ sessionId: this.sessionId
3326
+ };
3327
+ }
3328
+ return {
3329
+ mode: "anonymous",
3330
+ transport: this.transport,
3331
+ publishableKey: this.publishableKey,
3332
+ // Only name a user while one is actually signed in. `scopeUserRef` is the REGISTRY scope key,
3333
+ // taken from the host's `user` prop, which a `logout()` call does not touch — so carrying it here
3334
+ // meant that after sign-out the SDK kept sending `x-everfur-user-ref` for the signed-out user
3335
+ // alongside the publishable key, and the widget plane resolves identity from exactly that pair.
3336
+ userRef: this.currentUser === null ? null : scopeUserRef,
3337
+ sessionId: this.sessionId
3338
+ };
3339
+ }
3340
+ // ---- imperative verbs (re-scope in one commit; SPEC-10 §3) -------------
3341
+ setUser(user) {
3342
+ if (this.disposed) return;
3343
+ const nextRef = user?.userRef ?? null;
3344
+ const currentRef = this.currentUser?.userRef ?? null;
3345
+ if (nextRef === currentRef) {
3346
+ this.currentUser = user;
3347
+ if (user && this.identity === null) {
3348
+ this.identity = createIdentityProvider(user.userRef, user.getToken);
3349
+ }
3350
+ return;
3351
+ }
3352
+ this.identity?.clear();
3353
+ this.currentUser = user;
3354
+ this.identity = user ? createIdentityProvider(user.userRef, user.getToken) : null;
3355
+ this.rescopeAll();
3356
+ }
3357
+ async logout() {
3358
+ if (this.disposed) return;
3359
+ const wasAnonymous = this.currentUser === null;
3360
+ this.sessionId = newSessionId();
3361
+ this.setUser(null);
3362
+ if (wasAnonymous) this.rescopeAll();
3363
+ await this.sweepPerUserKv();
3364
+ }
3365
+ async sweepPerUserKv() {
3366
+ if (PER_USER_KV_KEYS.length === 0) return;
3367
+ const results = await Promise.allSettled(
3368
+ PER_USER_KV_KEYS.map((key) => this.kv.removeItem(key))
3369
+ );
3370
+ const failedCount = results.filter((result) => result.status === "rejected").length;
3371
+ if (failedCount > 0) {
3372
+ this.telemetry.track("sdk.logout.sweepPartialFailure", {
3373
+ failedCount,
3374
+ totalCount: results.length
3375
+ });
3376
+ }
3377
+ }
3378
+ async registerPet(pet, profile) {
3379
+ if (this.disposed) {
3380
+ return err(
3381
+ makeEverfurError("validationFailed", {
3382
+ retryable: false,
3383
+ wireMessage: "the Everfur runtime is disposed; registerPet was called after unmount"
3384
+ })
3385
+ );
3386
+ }
3387
+ const repo = createPetsRepository(this.buildAuth(this.currentUser?.userRef ?? null));
3388
+ return profile === void 0 ? repo.registerPet(pet) : repo.registerPet(pet, profile);
3389
+ }
3390
+ setActivePet(pet) {
3391
+ if (this.disposed) return;
3392
+ const next = pet ?? null;
3393
+ if (next === this.activePet) return;
3394
+ this.activePet = next;
3395
+ this.rescopeAll();
3396
+ }
3397
+ updateEntitlements(next) {
3398
+ if (this.disposed) return;
3399
+ if (this.configFailure !== null) return;
3400
+ this.store.set(next);
3401
+ }
3402
+ open(capability) {
3403
+ this.telemetry.track("sdk.open", { capability });
3404
+ }
3405
+ dispose() {
3406
+ if (this.disposed) return;
3407
+ this.disposed = true;
3408
+ this.epoch += 1;
3409
+ this.poller?.stop();
3410
+ this.identity?.clear();
3411
+ this.disposeAllControllers();
3412
+ }
3413
+ rescopeAll() {
3414
+ this.epoch += 1;
3415
+ this.disposeAllControllers();
3416
+ this.store.reset();
3417
+ this.poller?.refresh();
3418
+ }
3419
+ disposeAllControllers() {
3420
+ for (const entry of this.entries.values()) this.runDestroyer(entry.controller);
3421
+ this.entries.clear();
3422
+ this.destroyers.clear();
3423
+ }
3424
+ };
3425
+ function tryResolveClient(cfg) {
3426
+ const clientCfg = {
3427
+ publishableKey: cfg.publishableKey,
3428
+ ...cfg.apiBaseUrl !== void 0 ? { apiBaseUrl: cfg.apiBaseUrl } : {},
3429
+ ...cfg.contractVersion !== void 0 ? { contractVersion: cfg.contractVersion } : {},
3430
+ ...cfg.debug !== void 0 ? { debug: cfg.debug } : {}
3431
+ };
3432
+ return tryResolveClientConfig(clientCfg);
3433
+ }
3434
+ function reportConfigFailure(failure, telemetry) {
3435
+ try {
3436
+ telemetry.trackExpectedFailure("sdk.config.invalid", { reason: failure.reason });
3437
+ } catch {
3438
+ }
3439
+ const globalConsole = globalThis.console;
3440
+ globalConsole?.error?.(
3441
+ `[everfur] SDK disabled: ${failure.message}
3442
+ [everfur] Every Everfur capability will render its off-state until this is fixed. If the value is set in your environment, note that babel-preset-expo inlines only EXPO_PUBLIC_* variables into a release bundle.`
3443
+ );
3444
+ }
3445
+ function refusingTransport(failure) {
3446
+ const build = () => (
3447
+ // NOT `internalError`: the funnel's `decideRetry` keys on `isAutoRetryable(code)` and deliberately
3448
+ // ignores `error.retryable`, so `internalError` would be retried with backoff on every call even though
3449
+ // it can never succeed; and `categoryFor('internalError')` is `server`, i.e. "the server admits fault",
3450
+ // which would blame Everfur's backend for the partner's own config defect on their dashboards. The
3451
+ // whole point of the `sdk_config` level is to attribute this correctly. `validationFailed` is terminal
3452
+ // (`invalidRequest`: "retrying it unchanged can never succeed"), which is exactly true here.
3453
+ makeEverfurError("validationFailed", {
3454
+ retryable: false,
3455
+ // Developer-facing only: `wireMessage` is NON-ENUMERABLE and never rendered (EverfurError.ts).
3456
+ wireMessage: `Everfur SDK is not configured: ${failure.message}`
3457
+ })
3458
+ );
3459
+ return Object.freeze({
3460
+ request() {
3461
+ return Promise.resolve(err(build()));
3462
+ },
3463
+ stream(_req, signal) {
3464
+ const frame = errorFrame({
3465
+ code: "sdk_not_configured",
3466
+ retryable: false,
3467
+ wireMessage: `Everfur SDK is not configured: ${failure.message}`,
3468
+ synthesized: true,
3469
+ lastEventId: null
3470
+ });
3471
+ return {
3472
+ async *[Symbol.asyncIterator]() {
3473
+ if (signal.aborted) return;
3474
+ yield frame;
3475
+ }
3476
+ };
3477
+ }
3478
+ });
3479
+ }
3480
+ function createInMemoryKv() {
3481
+ const map = /* @__PURE__ */ new Map();
3482
+ return {
3483
+ async getItem(key) {
3484
+ return map.get(key) ?? null;
3485
+ },
3486
+ async setItem(key, value) {
3487
+ map.set(key, value);
3488
+ },
3489
+ async removeItem(key) {
3490
+ map.delete(key);
3491
+ },
3492
+ async keys(prefix) {
3493
+ return [...map.keys()].filter((k) => k.startsWith(prefix));
3494
+ }
3495
+ };
3496
+ }
3497
+ var unavailableUploadTransport = Object.freeze({
3498
+ postMultipart() {
3499
+ return Promise.reject(
3500
+ new Error("UploadTransport is unavailable; no records upload adapter was injected")
3501
+ );
3502
+ }
3503
+ });
3504
+ var noopImageCache = Object.freeze({
3505
+ clearMemoryCache() {
3506
+ },
3507
+ clearDiskCache() {
3508
+ }
3509
+ });
3510
+ var HEADERS_RECEIVED = 2;
3511
+ function readEventSourceResponseHeader(instance, name) {
3512
+ const xhr = instance?._xhr;
3513
+ if (!xhr || typeof xhr.getResponseHeader !== "function") return null;
3514
+ if (typeof xhr.readyState === "number" && xhr.readyState < HEADERS_RECEIVED) return null;
3515
+ let value;
3516
+ try {
3517
+ value = xhr.getResponseHeader(name);
3518
+ } catch {
3519
+ return null;
3520
+ }
3521
+ return typeof value === "string" && value.length > 0 ? value : null;
3522
+ }
3523
+ function createRnEventSourceFactory() {
3524
+ const Ctor = EventSource;
3525
+ return (url, init) => {
3526
+ const instance = new Ctor(url, {
3527
+ method: init.method,
3528
+ headers: init.headers,
3529
+ pollingInterval: init.pollingInterval ?? 0,
3530
+ ...init.body !== void 0 ? { body: init.body } : {}
3531
+ });
3532
+ return Object.assign(instance, {
3533
+ getResponseHeader: (name) => readEventSourceResponseHeader(instance, name)
3534
+ });
3535
+ };
3536
+ }
3537
+ var EVERFUR_THEME_CONTEXT_SYMBOL = /* @__PURE__ */ Symbol.for("@everfur/sdk#EverfurThemeContext@v1");
3538
+ var globalThemeHost = globalThis;
3539
+ var EverfurThemeContext = globalThemeHost[EVERFUR_THEME_CONTEXT_SYMBOL] ?? (globalThemeHost[EVERFUR_THEME_CONTEXT_SYMBOL] = createContext(EVERFUR_LIGHT));
3540
+ EverfurThemeContext.displayName ??= "EverfurThemeContext";
3541
+ function useEverfurTheme() {
3542
+ return useContext(EverfurThemeContext);
3543
+ }
3544
+
3545
+ // src/rn/theme/EverfurThemeProvider.tsx
3546
+ function EverfurThemeProvider(props) {
3547
+ const { runtime } = useEverfurContext();
3548
+ const store = runtime.entitlements;
3549
+ const snapshot = useSyncExternalStore(store.subscribe, store.getSnapshot, store.getSnapshot);
3550
+ const colorScheme = useColorScheme();
3551
+ const reducedMotion = useReducedMotion();
3552
+ const clientKey = props.clientTheme ? stableKey(props.clientTheme) : "";
3553
+ const clientOverride = useMemo(
3554
+ () => props.clientTheme ? parseClientBranding(props.clientTheme) : null,
3555
+ [clientKey]
3556
+ );
3557
+ const serverBranding = snapshot.branding ?? null;
3558
+ const scheme = colorScheme === "dark" ? "dark" : colorScheme === "light" ? "light" : null;
3559
+ const theme = useMemo(
3560
+ () => resolveTheme({
3561
+ branding: serverBranding,
3562
+ clientOverride,
3563
+ colorScheme: scheme,
3564
+ reducedMotion
3565
+ }),
3566
+ [serverBranding, clientOverride, scheme, reducedMotion]
3567
+ );
3568
+ return createElement(EverfurThemeContext.Provider, { value: theme }, props.children);
3569
+ }
3570
+ function useReducedMotion() {
3571
+ const [reduced, setReduced] = useState(false);
3572
+ useEffect(() => {
3573
+ let mounted = true;
3574
+ const query = AccessibilityInfo?.isReduceMotionEnabled;
3575
+ if (typeof query === "function") {
3576
+ const result = query.call(AccessibilityInfo);
3577
+ if (result != null && typeof result.then === "function") {
3578
+ result.then(
3579
+ (value) => {
3580
+ if (mounted) setReduced(value === true);
3581
+ },
3582
+ () => {
3583
+ }
3584
+ );
3585
+ }
3586
+ }
3587
+ const subscription = AccessibilityInfo?.addEventListener?.(
3588
+ "reduceMotionChanged",
3589
+ (value) => setReduced(value === true)
3590
+ );
3591
+ return () => {
3592
+ mounted = false;
3593
+ subscription?.remove?.();
3594
+ };
3595
+ }, []);
3596
+ return reduced;
3597
+ }
3598
+ function stableKey(input) {
3599
+ const keys = Object.keys(input).sort();
3600
+ return keys.map((k) => `${k}=${String(input[k])}`).join("&");
3601
+ }
3602
+
3603
+ // src/rn/facade.ts
3604
+ var EVERFUR_CONTEXT_SYMBOL = /* @__PURE__ */ Symbol.for("@everfur/sdk#EverfurContext@v1");
3605
+ var globalContextHost = globalThis;
3606
+ var EverfurContext = globalContextHost[EVERFUR_CONTEXT_SYMBOL] ?? (globalContextHost[EVERFUR_CONTEXT_SYMBOL] = createContext(null));
3607
+ EverfurContext.displayName ??= "EverfurContext";
3608
+ function useEverfurContext() {
3609
+ const ctx = useContext(EverfurContext);
3610
+ if (ctx === null) {
3611
+ throw new EverfurConfigError(
3612
+ "not-initialized",
3613
+ "Everfur hooks must be called inside <EverfurProvider>. Wrap your tree once, high."
3614
+ );
3615
+ }
3616
+ return ctx;
3617
+ }
3618
+ function EverfurProvider(props) {
3619
+ const { config, user, activePet, theme, children } = props;
3620
+ const configKey = `${config?.publishableKey ?? ""}|${config?.apiBaseUrl ?? ""}|${config?.contractVersion ?? ""}`;
3621
+ const runtimeRef = useRef(null);
3622
+ const supersededRef = useRef(null);
3623
+ const [, scheduleRender] = useReducer((n) => n + 1, 0);
3624
+ const imperativeUserRef = useRef(null);
3625
+ const lastPropUserRef = useRef(void 0);
3626
+ const propUserRefKey = user?.userRef ?? null;
3627
+ if (lastPropUserRef.current !== propUserRefKey) {
3628
+ if (lastPropUserRef.current !== void 0) imperativeUserRef.current = null;
3629
+ lastPropUserRef.current = propUserRefKey;
3630
+ }
3631
+ const effectiveUser = imperativeUserRef.current !== null ? imperativeUserRef.current.user : user ?? null;
3632
+ const imperativePetRef = useRef(null);
3633
+ const lastPropPetRef = useRef(void 0);
3634
+ const propPetRef = activePet ?? null;
3635
+ if (lastPropPetRef.current !== propPetRef) {
3636
+ if (lastPropPetRef.current !== void 0) imperativePetRef.current = null;
3637
+ lastPropPetRef.current = propPetRef;
3638
+ }
3639
+ const effectivePet = imperativePetRef.current !== null ? imperativePetRef.current.pet : activePet ?? null;
3640
+ if (runtimeRef.current === null || runtimeRef.current.key !== configKey || runtimeRef.current.runtime.isDisposed) {
3641
+ if (runtimeRef.current !== null && !runtimeRef.current.runtime.isDisposed) {
3642
+ supersededRef.current = runtimeRef.current.runtime;
3643
+ }
3644
+ runtimeRef.current = {
3645
+ key: configKey,
3646
+ runtime: createEverfurRuntime(
3647
+ {
3648
+ config,
3649
+ user: effectiveUser,
3650
+ activePet: effectivePet,
3651
+ theme: theme ?? null
3652
+ },
3653
+ // Inject the RN EventSource factory as the streaming fallback for the built HTTP transport. Ignored
3654
+ // when the host injects its own transport (the test seam); harmless on web/expo where fetch streams
3655
+ // res.body.
3656
+ { eventSourceFactory: createRnEventSourceFactory() }
3657
+ )
3658
+ };
3659
+ }
3660
+ const runtime = runtimeRef.current.runtime;
3661
+ const bumpedForRef = useRef(null);
3662
+ useEffect(() => {
3663
+ const current = runtimeRef.current?.runtime;
3664
+ if (current === void 0 || !current.isDisposed) return;
3665
+ if (bumpedForRef.current === current) return;
3666
+ bumpedForRef.current = current;
3667
+ scheduleRender();
3668
+ });
3669
+ useEffect(() => {
3670
+ const superseded = supersededRef.current;
3671
+ if (superseded === null) return;
3672
+ supersededRef.current = null;
3673
+ superseded.dispose();
3674
+ });
3675
+ const userRefKey = effectiveUser?.userRef ?? null;
3676
+ useLayoutEffect(() => {
3677
+ runtime.setUser(effectiveUser);
3678
+ }, [runtime, userRefKey]);
3679
+ useLayoutEffect(() => {
3680
+ runtime.setActivePet(effectivePet);
3681
+ }, [runtime, effectivePet]);
3682
+ useEffect(() => () => runtime.dispose(), [runtime]);
3683
+ const handle = useMemo(
3684
+ () => ({
3685
+ // Each re-scoping verb records the imperative intent, mutates the runtime, THEN schedules a render.
3686
+ // The render is not cosmetic: rescopeAll() has just disposed every controller the mounted hooks hold,
3687
+ // and only a re-render lets them re-acquire under the new epoch.
3688
+ setUser: (u) => {
3689
+ imperativeUserRef.current = { user: u };
3690
+ runtime.setUser(u);
3691
+ scheduleRender();
3692
+ },
3693
+ setActivePet: (p) => {
3694
+ imperativePetRef.current = { pet: p };
3695
+ runtime.setActivePet(p);
3696
+ scheduleRender();
3697
+ },
3698
+ open: (c) => runtime.open(c),
3699
+ registerPet: (pet, profile) => runtime.registerPet(pet, profile),
3700
+ logout: () => {
3701
+ imperativeUserRef.current = { user: null };
3702
+ const settled = runtime.logout();
3703
+ scheduleRender();
3704
+ return settled;
3705
+ }
3706
+ // logout returns the runtime's Promise<void> so a host can await the KV sweep before setUser(next).
3707
+ }),
3708
+ [runtime, scheduleRender]
3709
+ );
3710
+ const value = useMemo(
3711
+ () => ({
3712
+ runtime,
3713
+ handle,
3714
+ userRef: userRefKey,
3715
+ activePet: effectivePet
3716
+ }),
3717
+ [runtime, handle, userRefKey, effectivePet]
3718
+ );
3719
+ return createElement(
3720
+ EverfurContext.Provider,
3721
+ { value },
3722
+ /*
3723
+ * SafeAreaProvider, supplied by the SDK rather than demanded from the host.
3724
+ *
3725
+ * Without it the chat surface had no device insets and used a fixed paddingTop, so on any notched
3726
+ * iPhone the newest message rendered UNDER the Dynamic Island and could not be scrolled clear.
3727
+ * Observed on a simulator following the quickstart verbatim: the message the user had just sent was
3728
+ * the unreadable one.
3729
+ *
3730
+ * Providing it here rather than telling partners to wrap the tree keeps the promise the surface
3731
+ * already makes, that it renders its own complete chrome. Nesting is supported by the library, so a
3732
+ * host that already has its own provider is unaffected: the inner one reads the same window insets.
3733
+ */
3734
+ createElement(
3735
+ SafeAreaProvider,
3736
+ null,
3737
+ createElement(EverfurThemeProvider, { clientTheme: theme ?? null, children })
3738
+ )
3739
+ );
3740
+ }
3741
+ function useEverfur() {
3742
+ return useEverfurContext().handle;
3743
+ }
3744
+ function useCapability(name) {
3745
+ const { runtime } = useEverfurContext();
3746
+ const store = runtime.entitlements;
3747
+ const snapshot = useSyncExternalStore(
3748
+ store.subscribe,
3749
+ store.getSnapshot,
3750
+ store.getSnapshot
3751
+ );
3752
+ return useMemo(
3753
+ () => decideCapability(name, snapshot.decisions, { isPending: snapshot.isPending }),
3754
+ [name, snapshot]
3755
+ );
3756
+ }
3757
+ var MIN_OFFSTATE_HEIGHT = 48;
3758
+ function selectView(decision) {
3759
+ if (decision.isPending) return "pending";
3760
+ return decision.enabled ? "enabled" : "disabled";
3761
+ }
3762
+ function CapabilityGate(props) {
3763
+ const { capability, children, renderDisabled, renderPending, style } = props;
3764
+ const decision = useCapability(capability);
3765
+ const view = useMemo(() => selectView(decision), [decision]);
3766
+ switch (view) {
3767
+ case "enabled":
3768
+ return children;
3769
+ case "pending":
3770
+ return renderPending ? renderPending() : /* @__PURE__ */ jsx(PendingSkeleton, { capability, style });
3771
+ case "disabled":
3772
+ return renderDisabled ? renderDisabled(decision) : /* @__PURE__ */ jsx(OffState, { decision, style });
3773
+ default:
3774
+ return assertNever(view);
3775
+ }
3776
+ }
3777
+ function PendingSkeleton({
3778
+ capability,
3779
+ style
3780
+ }) {
3781
+ const theme = useEverfurTheme();
3782
+ const styles = useMemo(() => makeStyles(theme), [theme]);
3783
+ return /* @__PURE__ */ jsx(
3784
+ View,
3785
+ {
3786
+ style: [styles.offstate, style],
3787
+ accessible: true,
3788
+ accessibilityState: { busy: true },
3789
+ accessibilityLabel: `Loading ${capability}`,
3790
+ children: /* @__PURE__ */ jsx(View, { style: styles.skeletonBar })
3791
+ }
3792
+ );
3793
+ }
3794
+ function OffState({
3795
+ decision,
3796
+ style
3797
+ }) {
3798
+ const theme = useEverfurTheme();
3799
+ const styles = useMemo(() => makeStyles(theme), [theme]);
3800
+ const message = decision.disabled?.reason ?? "";
3801
+ return /* @__PURE__ */ jsx(
3802
+ View,
3803
+ {
3804
+ style: [styles.offstate, style],
3805
+ accessible: true,
3806
+ accessibilityRole: "text",
3807
+ accessibilityLabel: message,
3808
+ children: message.length > 0 ? /* @__PURE__ */ jsx(Text, { style: styles.offstateText, children: message }) : null
3809
+ }
3810
+ );
3811
+ }
3812
+ function makeStyles(theme) {
3813
+ const { color, space, radius, type } = theme;
3814
+ return StyleSheet.create({
3815
+ // A deliberate cream card with a soft brand hairline, never a bare grey slab.
3816
+ offstate: {
3817
+ minHeight: MIN_OFFSTATE_HEIGHT,
3818
+ justifyContent: "center",
3819
+ paddingHorizontal: space.lg,
3820
+ paddingVertical: space.md,
3821
+ backgroundColor: color.surfaceCream,
3822
+ borderRadius: radius.md,
3823
+ borderWidth: StyleSheet.hairlineWidth,
3824
+ borderColor: color.brandBorder
3825
+ },
3826
+ offstateText: {
3827
+ fontFamily: type.family,
3828
+ fontSize: type.size.body,
3829
+ lineHeight: Math.round(type.size.body * type.lineHeight.normal),
3830
+ color: color.text.muted
3831
+ },
3832
+ // A soft green shimmer bar (brand wash) that stays legible on the cream card in both light and dark,
3833
+ // where the neutral `skeleton` token would collide with the dark cream surface.
3834
+ skeletonBar: {
3835
+ height: space.md,
3836
+ borderRadius: radius.xs,
3837
+ backgroundColor: color.brandSofter
3838
+ }
3839
+ });
3840
+ }
3841
+ var BOOTSTRAP_SNAPSHOT = Object.freeze({
3842
+ status: "idle",
3843
+ messages: Object.freeze([]),
3844
+ conversationId: null,
3845
+ error: null,
3846
+ isStreaming: false,
3847
+ isBootstrapping: true,
3848
+ suggestedPrompts: Object.freeze([])
3849
+ });
3850
+ function useEverfurChat(opts) {
3851
+ const { runtime, userRef: userRef2, activePet } = useEverfurContext();
3852
+ const petRef2 = opts?.petRef ?? activePet ?? null;
3853
+ const conversationId2 = opts?.conversationId ?? null;
3854
+ const [controller, setController] = useState(null);
3855
+ useEffect(() => {
3856
+ const acquired = runtime.registry.acquireChat({ userRef: userRef2, petRef: petRef2, conversationId: conversationId2 });
3857
+ setController(acquired);
3858
+ return () => {
3859
+ setController((current) => current === acquired ? null : current);
3860
+ runtime.registry.releaseChat(acquired);
3861
+ };
3862
+ }, [runtime, userRef2, petRef2, conversationId2]);
3863
+ const subscribe = useCallback(
3864
+ (onChange) => controller ? controller.subscribe(onChange) : NOOP_UNSUBSCRIBE,
3865
+ [controller]
3866
+ );
3867
+ const getSnapshot = useCallback(
3868
+ () => controller ? controller.getSnapshot() : BOOTSTRAP_SNAPSHOT,
3869
+ [controller]
3870
+ );
3871
+ const snapshot = useSyncExternalStore(subscribe, getSnapshot, getSnapshot);
3872
+ const send = useCallback(
3873
+ (text) => controller ? driveToResult(controller, controller.send(text)) : Promise.resolve(notReadyError()),
3874
+ [controller]
3875
+ );
3876
+ const retryLast = useCallback(
3877
+ () => controller ? driveToResult(controller, controller.retryLast()) : Promise.resolve(notReadyError()),
3878
+ [controller]
3879
+ );
3880
+ const stop = useCallback(() => {
3881
+ controller?.stop();
3882
+ }, [controller]);
3883
+ return useMemo(
3884
+ () => ({
3885
+ status: snapshot.status,
3886
+ messages: snapshot.messages,
3887
+ conversationId: snapshot.conversationId,
3888
+ error: snapshot.error,
3889
+ isStreaming: snapshot.isStreaming,
3890
+ isBootstrapping: snapshot.isBootstrapping,
3891
+ suggestedPrompts: snapshot.suggestedPrompts,
3892
+ send,
3893
+ retryLast,
3894
+ stop
3895
+ }),
3896
+ [snapshot, send, retryLast, stop]
3897
+ );
3898
+ }
3899
+ var NOOP_UNSUBSCRIBE = () => {
3900
+ };
3901
+ async function driveToResult(controller, iterable) {
3902
+ for await (const _frame of iterable) {
3903
+ }
3904
+ const snapshot = controller.getSnapshot();
3905
+ if (snapshot.status === "error" && snapshot.error !== null) return err(snapshot.error);
3906
+ return ok(lastAssistantResponseId(snapshot.messages));
3907
+ }
3908
+ function lastAssistantResponseId(messages) {
3909
+ for (let i = messages.length - 1; i >= 0; i -= 1) {
3910
+ const message = messages[i];
3911
+ if (message && message.role === "assistant" && message.responseId !== void 0) {
3912
+ return message.responseId;
3913
+ }
3914
+ }
3915
+ return null;
3916
+ }
3917
+ function notReadyError() {
3918
+ return err(
3919
+ makeEverfurError("internalError", { retryable: true })
3920
+ );
3921
+ }
3922
+ var CLINICAL_DISCLAIMER = Object.freeze({
3923
+ title: "For educational use only",
3924
+ body: "Everfur is for educational purposes only. It helps you track visible changes through AI checkups. It does not diagnose, treat, prescribe, or replace veterinary care. For urgent symptoms or emergencies, contact a veterinarian immediately."
3925
+ });
3926
+ function ClinicalDisclaimer(props) {
3927
+ const theme = useEverfurTheme();
3928
+ const styles = useMemo(() => makeStyles2(theme), [theme]);
3929
+ return /* @__PURE__ */ jsxs(
3930
+ View,
3931
+ {
3932
+ style: [styles.container, props.style],
3933
+ accessible: true,
3934
+ accessibilityRole: "text",
3935
+ accessibilityLabel: `${CLINICAL_DISCLAIMER.title}. ${CLINICAL_DISCLAIMER.body}`,
3936
+ children: [
3937
+ /* @__PURE__ */ jsx(Text, { style: styles.title, children: CLINICAL_DISCLAIMER.title }),
3938
+ /* @__PURE__ */ jsx(Text, { style: styles.body, children: CLINICAL_DISCLAIMER.body })
3939
+ ]
3940
+ }
3941
+ );
3942
+ }
3943
+ function makeStyles2(theme) {
3944
+ const { color, space, type } = theme;
3945
+ return StyleSheet.create({
3946
+ container: {
3947
+ paddingHorizontal: space.lg,
3948
+ paddingVertical: space.md,
3949
+ borderTopWidth: StyleSheet.hairlineWidth,
3950
+ borderTopColor: color.borderHairlineGreen,
3951
+ backgroundColor: color.surfaceCream,
3952
+ gap: space.xs
3953
+ },
3954
+ title: {
3955
+ fontFamily: type.family,
3956
+ fontSize: type.size.caption,
3957
+ lineHeight: Math.round(type.size.caption * type.lineHeight.snug),
3958
+ color: color.text.secondary,
3959
+ fontWeight: type.weight.bold,
3960
+ letterSpacing: type.letterSpacing.eyebrow
3961
+ },
3962
+ body: {
3963
+ fontFamily: type.family,
3964
+ fontSize: type.size.caption,
3965
+ lineHeight: Math.round(type.size.caption * type.lineHeight.snug),
3966
+ color: color.text.muted,
3967
+ fontWeight: type.weight.regular
3968
+ }
3969
+ });
3970
+ }
3971
+ var INLINE_TOKEN = /\*\*([^*]+?)\*\*|\*([^*]+?)\*|`([^`]+?)`/g;
3972
+ function renderInlineMarkdown(text, styles) {
3973
+ if (!text.includes("*") && !text.includes("`")) return text;
3974
+ const nodes = [];
3975
+ let cursor = 0;
3976
+ let key = 0;
3977
+ INLINE_TOKEN.lastIndex = 0;
3978
+ for (let match = INLINE_TOKEN.exec(text); match !== null; match = INLINE_TOKEN.exec(text)) {
3979
+ if (match.index > cursor) nodes.push(text.slice(cursor, match.index));
3980
+ const bold = match[1];
3981
+ const italic = match[2];
3982
+ const code = match[3];
3983
+ if (bold !== void 0) {
3984
+ nodes.push(/* @__PURE__ */ jsx(Text, { style: styles.bold, children: bold }, key++));
3985
+ } else if (italic !== void 0) {
3986
+ nodes.push(styles.italic ? /* @__PURE__ */ jsx(Text, { style: styles.italic, children: italic }, key++) : italic);
3987
+ } else if (code !== void 0) {
3988
+ nodes.push(styles.code ? /* @__PURE__ */ jsx(Text, { style: styles.code, children: code }, key++) : code);
3989
+ }
3990
+ cursor = match.index + match[0].length;
3991
+ }
3992
+ if (cursor < text.length) nodes.push(text.slice(cursor));
3993
+ return nodes;
3994
+ }
3995
+ var DOT_SIZE = 6;
3996
+ var LOOP_MS = 520;
3997
+ var STAGGER_MS = Math.round(LOOP_MS * 0.18);
3998
+ var OPACITY_REST = 0.44;
3999
+ var OPACITY_STATIC = 0.5;
4000
+ var TRI_IN = [0, 0.5, 1];
4001
+ var DOT_INDICES = [0, 1, 2];
4002
+ function TypingIndicator() {
4003
+ const theme = useEverfurTheme();
4004
+ const styles = useMemo(() => makeStyles3(theme), [theme]);
4005
+ const animate = !theme.motion.reducedMotion;
4006
+ return /* @__PURE__ */ jsx(
4007
+ View,
4008
+ {
4009
+ style: styles.card,
4010
+ accessible: true,
4011
+ accessibilityRole: "text",
4012
+ accessibilityLabel: "Assistant is typing",
4013
+ accessibilityLiveRegion: "polite",
4014
+ accessibilityState: { busy: true },
4015
+ children: DOT_INDICES.map(
4016
+ (index) => animate ? /* @__PURE__ */ jsx(AnimatedDot, { index, style: styles.dot }, index) : /* @__PURE__ */ jsx(View, { style: [styles.dot, styles.dotStatic] }, index)
4017
+ )
4018
+ }
4019
+ );
4020
+ }
4021
+ function AnimatedDot({ index, style }) {
4022
+ const t = useRef(new Animated.Value(0)).current;
4023
+ useEffect(() => {
4024
+ const anim = Animated.sequence([
4025
+ Animated.delay(index * STAGGER_MS),
4026
+ Animated.loop(Animated.timing(t, { toValue: 1, duration: LOOP_MS, useNativeDriver: true }))
4027
+ ]);
4028
+ anim.start();
4029
+ return () => anim.stop();
4030
+ }, [t, index]);
4031
+ const opacity = t.interpolate({ inputRange: TRI_IN, outputRange: [OPACITY_REST, 1, OPACITY_REST] });
4032
+ const translateY = t.interpolate({ inputRange: TRI_IN, outputRange: [0, -3.5, 0] });
4033
+ return /* @__PURE__ */ jsx(Animated.View, { style: [style, { opacity, transform: [{ translateY }] }] });
4034
+ }
4035
+ function makeStyles3(theme) {
4036
+ const c = theme.color;
4037
+ const s = theme.space;
4038
+ const r = theme.radius;
4039
+ return StyleSheet.create({
4040
+ card: {
4041
+ alignSelf: "flex-start",
4042
+ flexDirection: "row",
4043
+ alignItems: "center",
4044
+ gap: s.xs,
4045
+ paddingHorizontal: s.md,
4046
+ paddingVertical: s.sm,
4047
+ backgroundColor: c.surfaceCream,
4048
+ borderRadius: r.md,
4049
+ borderWidth: StyleSheet.hairlineWidth,
4050
+ borderColor: c.brandBorder
4051
+ },
4052
+ dot: { width: DOT_SIZE, height: DOT_SIZE, borderRadius: r.pill, backgroundColor: c.brand },
4053
+ dotStatic: { opacity: OPACITY_STATIC }
4054
+ });
4055
+ }
4056
+ var SPINNER_DELAY_MS = 300;
4057
+ var DEFAULT_PLACEHOLDER = "Message";
4058
+ var DEFAULT_SEND_LABEL = "Send";
4059
+ var DEFAULT_STOP_LABEL = "Stop";
4060
+ var FOLLOW_UPS_LABEL = "Follow up questions";
4061
+ var POWERED_BY_LABEL = "powered by everfur";
4062
+ var MIN_SURFACE_HEIGHT = 120;
4063
+ var MIN_TOUCH_TARGET = 44;
4064
+ var INPUT_MAX_HEIGHT = 120;
4065
+ var EMPTY_GLYPH_SIZE = 40;
4066
+ var BUBBLE_MAX_WIDTH = "82%";
4067
+ var COMPOSER_BORDER_WIDTH = 1.25;
4068
+ var BUBBLE_EDGE_WIDTH = 0.5;
4069
+ var PENDING_OPACITY = 0.6;
4070
+ var COMPOSER_SHADOW_OPACITY = 0.1;
4071
+ var COMPOSER_SHADOW_OFFSET_Y = 2;
4072
+ var COMPOSER_SHADOW_ELEVATION = 2;
4073
+ function EverfurChat(props) {
4074
+ const { petRef: petRef2, conversationId: conversationId2, style } = props;
4075
+ return /* @__PURE__ */ jsx(CapabilityGate, { capability: "chat", style, children: /* @__PURE__ */ jsx(ChatBody, { petRef: petRef2, conversationId: conversationId2, style }) });
4076
+ }
4077
+ function selectView2(state) {
4078
+ if (state.isBootstrapping) return "loading";
4079
+ if (state.status === "error" && state.error) return "error";
4080
+ if (state.messages.length === 0) return "empty";
4081
+ return "populated";
4082
+ }
4083
+ function ChatBody({
4084
+ petRef: petRef2,
4085
+ conversationId: conversationId2,
4086
+ style
4087
+ }) {
4088
+ const { theme, styles } = useChatTheme();
4089
+ const chatOpts = useMemo(
4090
+ () => buildChatOpts(petRef2, conversationId2),
4091
+ [petRef2, conversationId2]
4092
+ );
4093
+ const chat = useEverfurChat(chatOpts);
4094
+ const view = selectView2(chat);
4095
+ const insets = useSafeAreaInsets();
4096
+ const onSelectPrompt = useCallback(
4097
+ (prompt) => {
4098
+ void chat.send(prompt);
4099
+ },
4100
+ [chat.send]
4101
+ );
4102
+ return (
4103
+ // KeyboardAvoidingView so the composer + disclaimer lift above the software keyboard while the user types.
4104
+ /* @__PURE__ */ jsxs(
4105
+ KeyboardAvoidingView,
4106
+ {
4107
+ style: [styles.container, { paddingTop: insets.top }, style],
4108
+ behavior: Platform.OS === "ios" ? "padding" : void 0,
4109
+ children: [
4110
+ /* @__PURE__ */ jsx(View, { style: styles.body, children: renderView(view, chat, onSelectPrompt) }),
4111
+ /* @__PURE__ */ jsx(Composer, { send: chat.send, stop: chat.stop, isStreaming: chat.isStreaming }),
4112
+ /* @__PURE__ */ jsx(ClinicalDisclaimer, {}),
4113
+ theme.meta.hidePoweredBy ? null : /* @__PURE__ */ jsx(Text, { style: styles.poweredBy, accessibilityRole: "text", accessibilityLabel: POWERED_BY_LABEL, children: POWERED_BY_LABEL })
4114
+ ]
4115
+ }
4116
+ )
4117
+ );
4118
+ }
4119
+ function Composer({
4120
+ send,
4121
+ stop,
4122
+ isStreaming
4123
+ }) {
4124
+ const { theme, styles } = useChatTheme();
4125
+ const [draft, setDraft] = useState("");
4126
+ const placeholder = theme.meta.placeholder ?? DEFAULT_PLACEHOLDER;
4127
+ const onSend = useCallback(() => {
4128
+ if (draft.trim().length === 0) return;
4129
+ if ([...draft].length > MESSAGE_MAX_CHARS) return;
4130
+ void send(draft);
4131
+ setDraft("");
4132
+ }, [draft, send]);
4133
+ const onStop = useCallback(() => {
4134
+ stop();
4135
+ }, [stop]);
4136
+ const isOverLimit = useMemo(() => [...draft].length > MESSAGE_MAX_CHARS, [draft]);
4137
+ return /* @__PURE__ */ jsxs(View, { style: styles.composer, children: [
4138
+ /* @__PURE__ */ jsx(
4139
+ TextInput,
4140
+ {
4141
+ style: styles.input,
4142
+ value: draft,
4143
+ onChangeText: setDraft,
4144
+ placeholder,
4145
+ placeholderTextColor: theme.color.text.placeholder,
4146
+ accessibilityLabel: placeholder,
4147
+ onSubmitEditing: onSend,
4148
+ returnKeyType: "send",
4149
+ blurOnSubmit: false,
4150
+ multiline: true,
4151
+ editable: true
4152
+ }
4153
+ ),
4154
+ isStreaming ? /* @__PURE__ */ jsx(
4155
+ Pressable,
4156
+ {
4157
+ onPress: onStop,
4158
+ accessibilityRole: "button",
4159
+ accessibilityLabel: DEFAULT_STOP_LABEL,
4160
+ style: styles.actionButton,
4161
+ children: /* @__PURE__ */ jsx(Text, { style: styles.actionLabel, children: DEFAULT_STOP_LABEL })
4162
+ }
4163
+ ) : /* @__PURE__ */ jsx(
4164
+ Pressable,
4165
+ {
4166
+ onPress: onSend,
4167
+ disabled: isOverLimit,
4168
+ accessibilityRole: "button",
4169
+ accessibilityLabel: DEFAULT_SEND_LABEL,
4170
+ accessibilityState: { disabled: isOverLimit },
4171
+ style: [styles.actionButton, isOverLimit ? styles.actionButtonDisabled : null],
4172
+ children: /* @__PURE__ */ jsx(Text, { style: [styles.actionLabel, isOverLimit ? styles.actionLabelDisabled : null], children: DEFAULT_SEND_LABEL })
4173
+ }
4174
+ )
4175
+ ] });
4176
+ }
4177
+ function renderView(view, chat, onSelectPrompt) {
4178
+ switch (view) {
4179
+ case "loading":
4180
+ return /* @__PURE__ */ jsx(LoadingState, {});
4181
+ case "empty":
4182
+ return /* @__PURE__ */ jsx(EmptyState, { prompts: chat.suggestedPrompts, onSelectPrompt });
4183
+ case "error":
4184
+ return /* @__PURE__ */ jsx(ErrorState, { error: chat.error, onRetry: chat.retryLast });
4185
+ case "populated":
4186
+ return /* @__PURE__ */ jsx(
4187
+ PopulatedState,
4188
+ {
4189
+ messages: chat.messages,
4190
+ prompts: chat.suggestedPrompts,
4191
+ onSelectPrompt,
4192
+ isStreaming: chat.isStreaming
4193
+ }
4194
+ );
4195
+ default:
4196
+ return assertNever(view);
4197
+ }
4198
+ }
4199
+ function buildChatOpts(petRef2, conversationId2) {
4200
+ const opts = {};
4201
+ if (petRef2 !== void 0) opts.petRef = petRef2;
4202
+ if (conversationId2 !== void 0) opts.conversationId = conversationId2;
4203
+ return opts;
4204
+ }
4205
+ function LoadingState() {
4206
+ const { theme, styles } = useChatTheme();
4207
+ const [visible, setVisible] = useState(false);
4208
+ useEffect(() => {
4209
+ const id = setTimeout(() => setVisible(true), SPINNER_DELAY_MS);
4210
+ return () => clearTimeout(id);
4211
+ }, []);
4212
+ return /* @__PURE__ */ jsx(View, { style: styles.centered, accessible: true, accessibilityState: { busy: true }, accessibilityLabel: "Loading", children: visible ? /* @__PURE__ */ jsx(ActivityIndicator, { color: theme.color.brand }) : null });
4213
+ }
4214
+ function EmptyState({
4215
+ prompts,
4216
+ onSelectPrompt
4217
+ }) {
4218
+ const { styles } = useChatTheme();
4219
+ return /* @__PURE__ */ jsxs(ScrollView, { contentContainerStyle: styles.emptyContent, keyboardShouldPersistTaps: "handled", children: [
4220
+ /* @__PURE__ */ jsx(View, { style: styles.emptyGlyphWrap, accessible: true, accessibilityRole: "summary", accessibilityLabel: "No messages yet", children: /* @__PURE__ */ jsx(View, { style: styles.emptyGlyph }) }),
4221
+ /* @__PURE__ */ jsx(FollowUps, { prompts, onSelectPrompt })
4222
+ ] });
4223
+ }
4224
+ function FollowUps({
4225
+ prompts,
4226
+ onSelectPrompt
4227
+ }) {
4228
+ const { styles } = useChatTheme();
4229
+ if (prompts.length === 0) return null;
4230
+ return /* @__PURE__ */ jsxs(View, { style: styles.followUps, children: [
4231
+ /* @__PURE__ */ jsx(Text, { style: styles.followUpsLabel, accessibilityRole: "header", children: FOLLOW_UPS_LABEL }),
4232
+ prompts.map((prompt, index) => /* @__PURE__ */ jsx(
4233
+ Pressable,
4234
+ {
4235
+ onPress: () => onSelectPrompt(prompt),
4236
+ accessibilityRole: "button",
4237
+ accessibilityLabel: prompt,
4238
+ style: [styles.followUpRow, index > 0 ? styles.followUpDivider : null],
4239
+ children: /* @__PURE__ */ jsx(Text, { style: styles.followUpText, children: prompt })
4240
+ },
4241
+ prompt
4242
+ ))
4243
+ ] });
4244
+ }
4245
+ function ErrorState({ error, onRetry }) {
4246
+ const { styles } = useChatTheme();
4247
+ return /* @__PURE__ */ jsxs(View, { style: styles.centered, accessible: true, accessibilityRole: "alert", children: [
4248
+ /* @__PURE__ */ jsx(Text, { style: styles.errorText, children: error.displayMessage }),
4249
+ error.retryable ? /* @__PURE__ */ jsx(
4250
+ Pressable,
4251
+ {
4252
+ onPress: onRetry,
4253
+ accessibilityRole: "button",
4254
+ accessibilityLabel: "Try again",
4255
+ style: styles.retryButton,
4256
+ children: /* @__PURE__ */ jsx(Text, { style: styles.retryLabel, children: "Try again" })
4257
+ }
4258
+ ) : null
4259
+ ] });
4260
+ }
4261
+ function PopulatedState({
4262
+ messages,
4263
+ prompts,
4264
+ onSelectPrompt,
4265
+ isStreaming
4266
+ }) {
4267
+ const { styles } = useChatTheme();
4268
+ const lastMessage = messages[messages.length - 1];
4269
+ const awaitingAssistant = isStreaming && (lastMessage === void 0 || lastMessage.role === "user");
4270
+ return /* @__PURE__ */ jsxs(
4271
+ ScrollView,
4272
+ {
4273
+ style: styles.list,
4274
+ contentContainerStyle: styles.listContent,
4275
+ accessibilityLabel: "Conversation",
4276
+ keyboardShouldPersistTaps: "handled",
4277
+ children: [
4278
+ messages.map((message) => /* @__PURE__ */ jsx(MessageRow, { message }, message.id)),
4279
+ awaitingAssistant ? /* @__PURE__ */ jsx(TypingIndicator, {}) : null,
4280
+ !isStreaming ? /* @__PURE__ */ jsx(FollowUps, { prompts, onSelectPrompt }) : null
4281
+ ]
4282
+ }
4283
+ );
4284
+ }
4285
+ function MessageRow({ message }) {
4286
+ const { styles } = useChatTheme();
4287
+ const isUser = message.role === "user";
4288
+ const sender = isUser ? "You" : "Assistant";
4289
+ return /* @__PURE__ */ jsx(
4290
+ View,
4291
+ {
4292
+ style: [styles.row, isUser ? styles.rowUser : styles.rowAssistant],
4293
+ accessible: true,
4294
+ accessibilityRole: "text",
4295
+ accessibilityLabel: `${sender}: ${message.text}`,
4296
+ accessibilityState: message.pending === true ? { busy: true } : void 0,
4297
+ children: /* @__PURE__ */ jsx(View, { style: [styles.bubble, isUser ? styles.bubbleUser : styles.bubbleAssistant, message.pending ? styles.bubblePending : null], children: /* @__PURE__ */ jsx(Text, { style: isUser ? styles.bubbleTextUser : styles.bubbleTextAssistant, children: isUser ? message.text : renderInlineMarkdown(message.text, {
4298
+ bold: styles.bubbleBold,
4299
+ italic: styles.bubbleItalic,
4300
+ code: styles.bubbleCode
4301
+ }) }) })
4302
+ }
4303
+ );
4304
+ }
4305
+ function useChatTheme() {
4306
+ const theme = useEverfurTheme();
4307
+ const styles = useMemo(() => makeStyles4(theme), [theme]);
4308
+ return { theme, styles };
4309
+ }
4310
+ function makeStyles4(theme) {
4311
+ const c = theme.color;
4312
+ const s = theme.space;
4313
+ const r = theme.radius;
4314
+ const t = theme.type;
4315
+ const weightLabel = t.weight.medium;
4316
+ return StyleSheet.create({
4317
+ // Cream ground so the branded bubbles / bare assistant text sit on an Everfur surface (host `style` still wins).
4318
+ container: { flex: 1, minHeight: MIN_SURFACE_HEIGHT, backgroundColor: c.surfaceCream },
4319
+ body: { flex: 1 },
4320
+ centered: { minHeight: MIN_SURFACE_HEIGHT, flexGrow: 1, alignItems: "center", justifyContent: "center", padding: s.xl },
4321
+ // Deliberate empty-state placeholder: a soft brand-wash disc (never a blank region).
4322
+ emptyGlyph: {
4323
+ width: EMPTY_GLYPH_SIZE,
4324
+ height: EMPTY_GLYPH_SIZE,
4325
+ borderRadius: r.pill,
4326
+ backgroundColor: c.brandSoft,
4327
+ borderWidth: StyleSheet.hairlineWidth,
4328
+ borderColor: c.brandBorder
4329
+ },
4330
+ // Empty state scrolls (glyph centered, then the follow-up list) so nothing overflows a short surface.
4331
+ emptyContent: { flexGrow: 1, justifyContent: "center", padding: s.lg, gap: s.lg },
4332
+ emptyGlyphWrap: { alignItems: "center", justifyContent: "center", paddingVertical: s.xl },
4333
+ errorText: {
4334
+ fontFamily: t.family,
4335
+ fontSize: t.size.subtitle,
4336
+ lineHeight: t.size.subtitle * t.lineHeight.snug,
4337
+ color: c.danger,
4338
+ textAlign: "center",
4339
+ marginBottom: s.md
4340
+ },
4341
+ // Brand-green pill retry CTA with the WCAG-legible on-brand foreground.
4342
+ retryButton: {
4343
+ minHeight: MIN_TOUCH_TARGET,
4344
+ minWidth: MIN_TOUCH_TARGET,
4345
+ alignItems: "center",
4346
+ justifyContent: "center",
4347
+ paddingHorizontal: s.xl,
4348
+ paddingVertical: s.sm,
4349
+ borderRadius: r.pill,
4350
+ backgroundColor: c.brand
4351
+ },
4352
+ retryLabel: { fontFamily: t.family, color: c.onPrimary, fontSize: t.size.body, fontWeight: weightLabel },
4353
+ list: { flex: 1 },
4354
+ listContent: { padding: s.lg, gap: s.md },
4355
+ row: { flexDirection: "row" },
4356
+ rowUser: { justifyContent: "flex-end" },
4357
+ rowAssistant: { justifyContent: "flex-start" },
4358
+ bubble: { maxWidth: BUBBLE_MAX_WIDTH, paddingHorizontal: s.md, paddingVertical: s.sm, borderRadius: r.lg },
4359
+ // User = brand accent fill + 0.5px accent edge, tail corner tightened (the mobile asymmetry).
4360
+ bubbleUser: {
4361
+ backgroundColor: c.bubbleUser,
4362
+ borderBottomRightRadius: r.tile,
4363
+ borderWidth: BUBBLE_EDGE_WIDTH,
4364
+ borderColor: c.accentEdge
4365
+ },
4366
+ // Assistant = bare text block (no fill, flush-left) so the reply reads as plain, on-surface prose.
4367
+ bubbleAssistant: { paddingHorizontal: 0 },
4368
+ bubblePending: { opacity: PENDING_OPACITY },
4369
+ bubbleTextUser: {
4370
+ fontFamily: t.family,
4371
+ color: c.onAccent,
4372
+ fontSize: t.size.body,
4373
+ lineHeight: t.size.body * t.lineHeight.normal
4374
+ },
4375
+ bubbleTextAssistant: {
4376
+ fontFamily: t.family,
4377
+ color: c.text.primary,
4378
+ fontSize: t.size.body,
4379
+ lineHeight: t.size.body * t.lineHeight.normal
4380
+ },
4381
+ // Inline-markdown runs inside the assistant reply (nested <Text>): bold entities + optional italic / code.
4382
+ bubbleBold: { fontWeight: t.weight.bold },
4383
+ bubbleItalic: { fontStyle: "italic" },
4384
+ bubbleCode: { fontFamily: t.mono },
4385
+ // "Follow up questions": a labeled, list-with-dividers block of tappable, ready-to-send backend prompts.
4386
+ followUps: { marginTop: s.sm, borderRadius: r.md, backgroundColor: c.brandSoft, borderWidth: StyleSheet.hairlineWidth, borderColor: c.brandBorder },
4387
+ followUpsLabel: {
4388
+ fontFamily: t.family,
4389
+ color: c.text.secondary,
4390
+ fontSize: t.size.caption,
4391
+ fontWeight: weightLabel,
4392
+ letterSpacing: t.letterSpacing.eyebrow,
4393
+ textTransform: "uppercase",
4394
+ paddingHorizontal: s.md,
4395
+ paddingTop: s.md,
4396
+ paddingBottom: s.sm
4397
+ },
4398
+ followUpRow: { minHeight: MIN_TOUCH_TARGET, justifyContent: "center", paddingHorizontal: s.md, paddingVertical: s.sm },
4399
+ followUpDivider: { borderTopWidth: StyleSheet.hairlineWidth, borderTopColor: c.brandBorder },
4400
+ followUpText: {
4401
+ fontFamily: t.family,
4402
+ color: c.text.primary,
4403
+ fontSize: t.size.body,
4404
+ lineHeight: t.size.body * t.lineHeight.snug
4405
+ },
4406
+ // Composer = inset cream pill with a brand border and a soft brand-tinted lift.
4407
+ composer: {
4408
+ flexDirection: "row",
4409
+ alignItems: "flex-end",
4410
+ gap: s.sm,
4411
+ marginHorizontal: s.md,
4412
+ marginTop: s.xs,
4413
+ marginBottom: s.sm,
4414
+ paddingHorizontal: s.md,
4415
+ paddingVertical: s.sm,
4416
+ backgroundColor: c.surfaceCream,
4417
+ borderWidth: COMPOSER_BORDER_WIDTH,
4418
+ borderColor: c.brandBorder,
4419
+ borderRadius: r.pill,
4420
+ shadowColor: c.brand,
4421
+ shadowOpacity: COMPOSER_SHADOW_OPACITY,
4422
+ shadowRadius: s.sm,
4423
+ shadowOffset: { width: 0, height: COMPOSER_SHADOW_OFFSET_Y },
4424
+ elevation: COMPOSER_SHADOW_ELEVATION
4425
+ },
4426
+ // Bare input inside the pill (the composer owns the border / fill); placeholder color set on the element.
4427
+ input: {
4428
+ flex: 1,
4429
+ minHeight: MIN_TOUCH_TARGET,
4430
+ maxHeight: INPUT_MAX_HEIGHT,
4431
+ paddingHorizontal: s.md,
4432
+ paddingVertical: s.sm,
4433
+ fontFamily: t.family,
4434
+ fontSize: t.size.body,
4435
+ lineHeight: t.size.body * t.lineHeight.normal,
4436
+ color: c.text.primary
4437
+ },
4438
+ // Brand-green pill send / stop control.
4439
+ actionButton: {
4440
+ minHeight: MIN_TOUCH_TARGET,
4441
+ minWidth: MIN_TOUCH_TARGET,
4442
+ alignItems: "center",
4443
+ justifyContent: "center",
4444
+ paddingHorizontal: s.lg,
4445
+ borderRadius: r.pill,
4446
+ backgroundColor: c.brand
4447
+ },
4448
+ actionLabel: { fontFamily: t.family, color: c.onPrimary, fontSize: t.size.body, fontWeight: weightLabel },
4449
+ // The over-length state. Opacity alone would carry the meaning by appearance only, so the control also
4450
+ // sets `disabled` and `accessibilityState.disabled`, which is what a screen reader announces.
4451
+ actionButtonDisabled: { opacity: 0.45 },
4452
+ actionLabelDisabled: { color: c.onPrimary },
4453
+ // Everfur's own attribution: small, muted, centered under the disclaimer.
4454
+ poweredBy: {
4455
+ fontFamily: t.family,
4456
+ color: c.text.muted,
4457
+ fontSize: t.size.micro,
4458
+ textAlign: "center",
4459
+ paddingBottom: s.xs
4460
+ }
4461
+ });
4462
+ }
4463
+
4464
+ export { CapabilityGate, EverfurChat, EverfurConfigError, EverfurProvider, EverfurThemeProvider, EverfurThrownError, categoryFor, conversationId, isErr, isOk, isRetryableCode, petRef, unwrap, useCapability, useEverfur, useEverfurChat, useEverfurTheme, userFacingError, userRef };