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