@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
@@ -0,0 +1,2217 @@
1
+ import { z } from 'zod';
2
+
3
+ // src/client/contract/contract.generated.ts
4
+ var CONTRACT_RETRYABILITY = Object.freeze([
5
+ Object.freeze({ wireCode: "AccessDeniedException", envelope: "http_envelope", httpStatus: 403, retryable: false }),
6
+ Object.freeze({ wireCode: "AuthorizationException", envelope: "http_envelope", httpStatus: 401, retryable: false }),
7
+ Object.freeze({ wireCode: "ConflictException", envelope: "http_envelope", httpStatus: 409, retryable: true }),
8
+ Object.freeze({ wireCode: "DAILY_QUOTA_EXCEEDED", envelope: "http_envelope", httpStatus: 429, retryable: true }),
9
+ Object.freeze({ wireCode: "IDEMPOTENCY_KEY_IN_FLIGHT", envelope: "http_envelope", httpStatus: 409, retryable: true }),
10
+ Object.freeze({ wireCode: "IDEMPOTENCY_KEY_REUSED_DIFFERENT_REQUEST", envelope: "http_envelope", httpStatus: 409, retryable: false }),
11
+ Object.freeze({ wireCode: "InternalFailureException", envelope: "http_envelope", httpStatus: 500, retryable: true }),
12
+ Object.freeze({ wireCode: "NotImplementedException", envelope: "http_envelope", httpStatus: 501, retryable: false }),
13
+ Object.freeze({ wireCode: "PaymentRequiredException", envelope: "http_envelope", httpStatus: 402, retryable: false }),
14
+ Object.freeze({ wireCode: "ResourceNotFoundException", envelope: "http_envelope", httpStatus: 404, retryable: false }),
15
+ Object.freeze({ wireCode: "ServiceUnavailableException", envelope: "http_envelope", httpStatus: 503, retryable: true }),
16
+ Object.freeze({ wireCode: "TIER_UPGRADE_REQUIRED", envelope: "http_envelope", httpStatus: 402, retryable: false }),
17
+ Object.freeze({ wireCode: "ThrottlingException", envelope: "http_envelope", httpStatus: 429, retryable: true }),
18
+ Object.freeze({ wireCode: "ValidationException", envelope: "http_envelope", httpStatus: 400, retryable: false }),
19
+ Object.freeze({ wireCode: "accessDenied", envelope: "http_envelope", httpStatus: 403, retryable: false }),
20
+ Object.freeze({ wireCode: "authExpired", envelope: "http_envelope", httpStatus: 401, retryable: true }),
21
+ Object.freeze({ wireCode: "internal_error", envelope: "sse_frame", httpStatus: 200, retryable: false }),
22
+ Object.freeze({ wireCode: "invalidRequest", envelope: "http_envelope", httpStatus: 400, retryable: false }),
23
+ Object.freeze({ wireCode: "not_found", envelope: "sse_frame", httpStatus: 200, retryable: false }),
24
+ Object.freeze({ wireCode: "session_required", envelope: "http_envelope", httpStatus: 403, retryable: false }),
25
+ Object.freeze({ wireCode: "timeout", envelope: "sse_frame", httpStatus: 200, retryable: true }),
26
+ Object.freeze({ wireCode: "unavailable", envelope: "http_envelope", httpStatus: 503, retryable: true })
27
+ ]);
28
+ Object.freeze(
29
+ CONTRACT_RETRYABILITY.map((row) => row.wireCode)
30
+ );
31
+
32
+ // src/client/errors/contract.ts
33
+ var NORMALIZED_FOLD = Object.freeze({
34
+ // the default status-mapped envelope
35
+ ValidationException: "validationFailed",
36
+ AuthorizationException: "authRejected",
37
+ PaymentRequiredException: "paymentRequired",
38
+ AccessDeniedException: "accessDenied",
39
+ ResourceNotFoundException: "resourceNotFound",
40
+ ConflictException: "conflict",
41
+ ThrottlingException: "rateLimited",
42
+ InternalFailureException: "internalError",
43
+ NotImplementedException: "notImplemented",
44
+ ServiceUnavailableException: "serviceUnavailable",
45
+ // dict-detail codes on the widget surface
46
+ authExpired: "authExpired",
47
+ unavailable: "serviceUnavailable",
48
+ session_required: "sessionRequired",
49
+ accessDenied: "accessDenied",
50
+ invalidRequest: "sdkUpdateRequired",
51
+ // typed codes
52
+ IDEMPOTENCY_KEY_IN_FLIGHT: "idempotencyInFlight",
53
+ IDEMPOTENCY_KEY_REUSED_DIFFERENT_REQUEST: "idempotencyConflict",
54
+ DAILY_QUOTA_EXCEEDED: "quotaExceeded",
55
+ TIER_UPGRADE_REQUIRED: "paymentRequired",
56
+ // SSE error frames
57
+ not_found: "conversationNotFound",
58
+ timeout: "streamTimeout",
59
+ internal_error: "internalError"
60
+ });
61
+ var CONTRACT_ERROR_ROWS = Object.freeze(
62
+ CONTRACT_RETRYABILITY.map(
63
+ (generated) => Object.freeze({
64
+ wireCode: generated.wireCode,
65
+ envelope: generated.envelope,
66
+ retryable: generated.retryable,
67
+ normalized: NORMALIZED_FOLD[generated.wireCode]
68
+ })
69
+ )
70
+ );
71
+ var BY_UPPER = new Map(
72
+ CONTRACT_ERROR_ROWS.map((r) => [r.wireCode.toUpperCase(), r])
73
+ );
74
+ function contractErrorFor(wireCode) {
75
+ if (typeof wireCode !== "string") return void 0;
76
+ const key = wireCode.trim().toUpperCase();
77
+ return key.length > 0 ? BY_UPPER.get(key) : void 0;
78
+ }
79
+ function contractDocUrl(entry) {
80
+ return entry.envelope === "sse_frame" ? `/errors#sse-${entry.wireCode}` : `/errors#${entry.wireCode}`;
81
+ }
82
+ var DOC_SITE_ORIGIN = null;
83
+ function publishedDocUrl(entry) {
84
+ return null ;
85
+ }
86
+
87
+ // src/client/errors/codes.ts
88
+ var EVERFUR_ERROR_CODES = Object.freeze([
89
+ "authExpired",
90
+ "authRejected",
91
+ "sessionRequired",
92
+ "accessDenied",
93
+ "paymentRequired",
94
+ "quotaExceeded",
95
+ "rateLimited",
96
+ "validationFailed",
97
+ "sdkUpdateRequired",
98
+ "conflict",
99
+ "idempotencyConflict",
100
+ "idempotencyInFlight",
101
+ "conversationNotFound",
102
+ "petNotFound",
103
+ "resourceNotFound",
104
+ "streamTimeout",
105
+ "mediaUploadFailed",
106
+ "moderationBlocked",
107
+ "upstreamLlmTimeout",
108
+ "internalError",
109
+ "notImplemented",
110
+ "serviceUnavailable",
111
+ "streamIncomplete",
112
+ "unknown"
113
+ ]);
114
+ var EVERFUR_ERROR_CATEGORIES = Object.freeze([
115
+ "authentication",
116
+ "authorization",
117
+ "entitlement",
118
+ "rateLimit",
119
+ "invalidRequest",
120
+ "notFound",
121
+ "conflict",
122
+ "connection",
123
+ "server",
124
+ "media",
125
+ "policy",
126
+ "unknown"
127
+ ]);
128
+ var CATEGORY_OF = Object.freeze({
129
+ // the caller's sign-in state is wrong and a credential change is the remedy
130
+ authExpired: "authentication",
131
+ authRejected: "authentication",
132
+ sessionRequired: "authentication",
133
+ // signed in, correctly identified, and still not allowed
134
+ accessDenied: "authorization",
135
+ // a plan gate, not a permission failure: the remedy is commercial
136
+ paymentRequired: "entitlement",
137
+ // slow down / come back later
138
+ quotaExceeded: "rateLimit",
139
+ rateLimited: "rateLimit",
140
+ // the request itself was wrong; retrying it unchanged can never succeed
141
+ validationFailed: "invalidRequest",
142
+ sdkUpdateRequired: "invalidRequest",
143
+ // the target is gone, hidden, or was never visible to this caller
144
+ conversationNotFound: "notFound",
145
+ petNotFound: "notFound",
146
+ resourceNotFound: "notFound",
147
+ // something else already holds the thing
148
+ conflict: "conflict",
149
+ idempotencyConflict: "conflict",
150
+ idempotencyInFlight: "conflict",
151
+ // the pipe, not the request: timeouts, drops, a briefly unreachable dependency
152
+ streamTimeout: "connection",
153
+ streamIncomplete: "connection",
154
+ upstreamLlmTimeout: "connection",
155
+ serviceUnavailable: "connection",
156
+ // the server admits fault
157
+ internalError: "server",
158
+ notImplemented: "server",
159
+ mediaUploadFailed: "media",
160
+ moderationBlocked: "policy",
161
+ unknown: "unknown"
162
+ });
163
+ function categoryFor(code) {
164
+ return CATEGORY_OF[code];
165
+ }
166
+ function fromWire(wire) {
167
+ const contractRow = contractErrorFor(wire);
168
+ if (contractRow) return contractRow.normalized;
169
+ const upper = (wire ?? "").trim().toUpperCase();
170
+ const canonical = upper.replace(/[^A-Z0-9]/g, "");
171
+ if (canonical === "AUTHREJECTED") return "authRejected";
172
+ if (upper.startsWith("AUTH")) return "authExpired";
173
+ switch (canonical) {
174
+ case "DAILYQUOTAEXCEEDED":
175
+ case "QUOTAEXCEEDED":
176
+ return "quotaExceeded";
177
+ case "RATELIMITED":
178
+ case "TOOMANYREQUESTS":
179
+ return "rateLimited";
180
+ case "IDEMPOTENCYKEYCONFLICT":
181
+ case "IDEMPOTENCYCONFLICT":
182
+ return "idempotencyConflict";
183
+ case "ACCESSDENIED":
184
+ case "FORBIDDEN":
185
+ return "accessDenied";
186
+ case "NOTFOUND":
187
+ case "CONVERSATIONNOTFOUND":
188
+ return "conversationNotFound";
189
+ case "PETNOTFOUND":
190
+ return "petNotFound";
191
+ case "TIMEOUT":
192
+ case "STREAMTIMEOUT":
193
+ return "streamTimeout";
194
+ // Analysis-domain deterministic 400s (NON-retryable). Additive per SPEC-00 §3.1 / SPEC-11b §2.6:
195
+ // fold to a NON-retried target so the SDK never retries a permanently-failing bad-input request.
196
+ // (Comment above the group so the empty fall-through cases stay lint-clean under no-fallthrough.)
197
+ case "MEDIAUPLOADFAILED":
198
+ case "UNRECOGNIZEDVIDEOFORMAT":
199
+ case "FILETOOSMALL":
200
+ return "mediaUploadFailed";
201
+ case "MODERATIONBLOCKED":
202
+ return "moderationBlocked";
203
+ case "UPSTREAMLLMTIMEOUT":
204
+ return "upstreamLlmTimeout";
205
+ case "INTERNALERROR":
206
+ case "INTERNALSERVERERROR":
207
+ return "internalError";
208
+ case "STREAMINCOMPLETE":
209
+ case "CHATSTREAMINCOMPLETE":
210
+ return "streamIncomplete";
211
+ // Deterministic 400s that can only come from an SDK bug -> unknown (NON-retryable). NEVER internalError
212
+ // (which IS auto-retried): mapping a bad-input 400 to a retryable code retries a request that never succeeds.
213
+ case "INVALIDANALYSISTYPE":
214
+ case "INVALIDUPLOADPURPOSE":
215
+ return "unknown";
216
+ default:
217
+ return "unknown";
218
+ }
219
+ }
220
+ function fromHttpStatus(status) {
221
+ if (status === 401) return "authExpired";
222
+ if (status === 403) return "accessDenied";
223
+ if (status === 404) return "conversationNotFound";
224
+ if (status === 409) return "idempotencyConflict";
225
+ if (status === 421) return "unknown";
226
+ if (status === 429) return "rateLimited";
227
+ if (status === 400 || status === 422) return "unknown";
228
+ if (status >= 500) return "internalError";
229
+ return "unknown";
230
+ }
231
+ var AUTO_RETRYABLE_CODES = /* @__PURE__ */ new Set([
232
+ "streamTimeout",
233
+ "rateLimited",
234
+ "internalError",
235
+ "upstreamLlmTimeout",
236
+ "streamIncomplete"
237
+ ]);
238
+ function isAutoRetryable(code) {
239
+ return AUTO_RETRYABLE_CODES.has(code);
240
+ }
241
+ var RETRYABLE_CONTRACT_CODES = /* @__PURE__ */ new Set([
242
+ "serviceUnavailable",
243
+ "conflict",
244
+ "idempotencyInFlight"
245
+ ]);
246
+ function isRetryableCode(code) {
247
+ return isAutoRetryable(code) || RETRYABLE_CONTRACT_CODES.has(code);
248
+ }
249
+ function shouldRetry(code, frameRetryable = false) {
250
+ return frameRetryable || isAutoRetryable(code);
251
+ }
252
+ var BACKOFF_BASE_MS = 500;
253
+ var BACKOFF_CAP_MS = 8e3;
254
+ var MAX_RETRY_ATTEMPTS = 4;
255
+ function backoffDelayMs(attempt, rng = Math.random) {
256
+ const bounded = Math.max(0, attempt);
257
+ const ceiling = Math.min(BACKOFF_BASE_MS * 2 ** bounded, BACKOFF_CAP_MS);
258
+ return Math.floor(rng() * ceiling);
259
+ }
260
+ function canRecreateOnNotFound(code) {
261
+ return code === "conversationNotFound";
262
+ }
263
+
264
+ // src/client/errors/EverfurError.ts
265
+ var USER_FACING_COPY = Object.freeze({
266
+ authExpired: "Please sign in again to continue.",
267
+ authRejected: "Please sign in again to continue.",
268
+ sessionRequired: "This app needs to be updated to keep using Everfur.",
269
+ accessDenied: "This feature isn't available on your account right now.",
270
+ paymentRequired: "This is part of a paid plan.",
271
+ quotaExceeded: "You have used today's messages. This resets tomorrow.",
272
+ rateLimited: "You are sending messages quickly. Try again in a few seconds.",
273
+ validationFailed: "Something in that request was not right. Check the details and try again.",
274
+ sdkUpdateRequired: "This app needs to be updated to keep using Everfur.",
275
+ conflict: "That is already running. Wait for it to finish, then try again.",
276
+ idempotencyConflict: "That message was already delivered.",
277
+ idempotencyInFlight: "That is still processing. Give it a moment.",
278
+ conversationNotFound: "This conversation is no longer available.",
279
+ petNotFound: "We could not find that pet. Please pick a pet and try again.",
280
+ resourceNotFound: "We could not find that.",
281
+ streamTimeout: "The response timed out. Tap retry to try again.",
282
+ mediaUploadFailed: "We could not upload that photo. Please attach it again.",
283
+ moderationBlocked: "This request cannot be answered here.",
284
+ upstreamLlmTimeout: "The response timed out. Tap retry to try again.",
285
+ internalError: "We hit a snag on our end. Please try again.",
286
+ notImplemented: "That is not available yet.",
287
+ serviceUnavailable: "That service is briefly unavailable. Try again shortly.",
288
+ streamIncomplete: "The connection dropped mid-answer. Tap retry to continue.",
289
+ unknown: "Something went wrong. Please try again."
290
+ });
291
+ function userFacingError(code) {
292
+ return USER_FACING_COPY[code];
293
+ }
294
+ function defineHidden(target, key, value) {
295
+ Object.defineProperty(target, key, {
296
+ value,
297
+ enumerable: false,
298
+ writable: false,
299
+ configurable: false
300
+ });
301
+ }
302
+ function makeEverfurError(code, opts) {
303
+ contractErrorFor(opts?.wireCode);
304
+ const error = {
305
+ code,
306
+ category: categoryFor(code),
307
+ retryable: opts?.retryable ?? isRetryableCode(code),
308
+ displayMessage: userFacingError(code)
309
+ };
310
+ if (opts?.httpStatus !== void 0) error.httpStatus = opts.httpStatus;
311
+ if (opts?.requestId) error.requestId = opts.requestId;
312
+ if (opts?.wireMessage) defineHidden(error, "wireMessage", opts.wireMessage);
313
+ if (opts?.raw !== void 0 && opts.raw !== null) defineHidden(error, "raw", opts.raw);
314
+ return Object.freeze(error);
315
+ }
316
+
317
+ // src/client/errors/EverfurResult.ts
318
+ function ok(value, warning) {
319
+ return Object.freeze(
320
+ warning === void 0 ? { ok: true, value } : { ok: true, value, warning }
321
+ );
322
+ }
323
+ function err(error) {
324
+ return Object.freeze({ ok: false, error });
325
+ }
326
+ function isOk(r) {
327
+ return r.ok;
328
+ }
329
+ function isErr(r) {
330
+ return !r.ok;
331
+ }
332
+ var EverfurThrownError = class _EverfurThrownError extends Error {
333
+ constructor(error) {
334
+ super(`${error.code}: ${error.displayMessage}`);
335
+ this.name = "EverfurThrownError";
336
+ this.error = error;
337
+ this.code = error.code;
338
+ this.category = error.category;
339
+ Object.setPrototypeOf(this, _EverfurThrownError.prototype);
340
+ }
341
+ };
342
+ function unwrap(r) {
343
+ if (r.ok) return r.value;
344
+ throw new EverfurThrownError(r.error);
345
+ }
346
+ var EverfurConfigError = class _EverfurConfigError extends Error {
347
+ constructor(kind, message) {
348
+ super(message);
349
+ this.name = "EverfurConfigError";
350
+ this.kind = kind;
351
+ Object.setPrototypeOf(this, _EverfurConfigError.prototype);
352
+ }
353
+ };
354
+
355
+ // src/client/config.ts
356
+ var SDK_VERSION = "0.1.0";
357
+ var SDK_PLATFORM = "react-native";
358
+ var DEFAULT_CONTRACT_VERSION = "2026-08-01";
359
+ var ENV_API_BASE_URL = "EVERFUR_API_BASE_URL";
360
+ function configFailure(reason, message) {
361
+ return Object.freeze({ ok: false, failure: Object.freeze({ reason, message }) });
362
+ }
363
+ function checkPublishableKey(raw) {
364
+ const publishableKey = typeof raw === "string" ? raw.trim() : "";
365
+ if (publishableKey.length === 0) {
366
+ return { reason: "missing-publishable-key", message: "publishableKey is required" };
367
+ }
368
+ if (/^sk[_-]/i.test(publishableKey)) {
369
+ return {
370
+ reason: "secret-key-as-publishable-key",
371
+ 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."
372
+ };
373
+ }
374
+ return null;
375
+ }
376
+ function tryResolveClientConfig(config) {
377
+ const keyFailure = checkPublishableKey(config?.publishableKey);
378
+ if (keyFailure !== null) {
379
+ return Object.freeze({ ok: false, failure: keyFailure });
380
+ }
381
+ const publishableKey = config.publishableKey.trim();
382
+ const baseUrl = tryResolveApiBaseUrl(config.apiBaseUrl);
383
+ if (!baseUrl.ok) {
384
+ return baseUrl;
385
+ }
386
+ const contractVersion = config.contractVersion?.trim() || DEFAULT_CONTRACT_VERSION;
387
+ return Object.freeze({
388
+ ok: true,
389
+ config: Object.freeze({
390
+ publishableKey,
391
+ apiBaseUrl: baseUrl.value,
392
+ contractVersion,
393
+ sdkVersion: SDK_VERSION,
394
+ platform: SDK_PLATFORM,
395
+ debug: config.debug === true
396
+ })
397
+ });
398
+ }
399
+ function resolveClientConfig(config) {
400
+ const outcome = tryResolveClientConfig(config);
401
+ if (!outcome.ok) {
402
+ throw new EverfurConfigError("invalid-argument", outcome.failure.message);
403
+ }
404
+ return outcome.config;
405
+ }
406
+ function tryResolveApiBaseUrl(apiBaseUrl) {
407
+ const explicit = apiBaseUrl?.trim();
408
+ const candidate = explicit && explicit.length > 0 ? explicit : readEnv(ENV_API_BASE_URL);
409
+ if (!candidate) {
410
+ return configFailure(
411
+ "missing-api-base-url",
412
+ `apiBaseUrl is required: pass config.apiBaseUrl or set ${ENV_API_BASE_URL}. The SDK never ships a hardcoded host.`
413
+ );
414
+ }
415
+ return normalizeBaseUrl(candidate);
416
+ }
417
+ function resolveApiBaseUrl(apiBaseUrl) {
418
+ const outcome = tryResolveApiBaseUrl(apiBaseUrl);
419
+ if (!outcome.ok) {
420
+ throw new EverfurConfigError("invalid-argument", outcome.failure.message);
421
+ }
422
+ return outcome.value;
423
+ }
424
+ function buildBaseHeaders(cfg) {
425
+ return {
426
+ "X-Everfur-SDK-Version": cfg.sdkVersion,
427
+ "X-Everfur-SDK-Platform": cfg.platform,
428
+ "X-Everfur-Contract": cfg.contractVersion
429
+ };
430
+ }
431
+ var ABSOLUTE_URL = /^([A-Za-z][A-Za-z0-9+.-]*):\/\/([^/?#]*)/;
432
+ function hostOf(authority) {
433
+ const afterUserinfo = authority.slice(authority.lastIndexOf("@") + 1);
434
+ return afterUserinfo.replace(/:\d+$/, "").toLowerCase();
435
+ }
436
+ function isPrintableHost(host) {
437
+ if (host.length === 0) return false;
438
+ if (host.includes("@")) return false;
439
+ if (host.startsWith("[") && host.endsWith("]")) return true;
440
+ return !host.includes(":");
441
+ }
442
+ function canEchoOrigin(rawTrimmed, host) {
443
+ const schemeEnd = rawTrimmed.indexOf("://");
444
+ if (schemeEnd < 0) return false;
445
+ if (rawTrimmed.slice(schemeEnd + 3).includes("@")) return false;
446
+ return isPrintableHost(host);
447
+ }
448
+ function safeOrigin(scheme, host) {
449
+ return `${scheme}://${host}`;
450
+ }
451
+ function normalizeBaseUrl(raw) {
452
+ const trimmed = raw.trim();
453
+ const match = ABSOLUTE_URL.exec(trimmed);
454
+ if (match === null || match[2] === void 0 || match[2].length === 0) {
455
+ return configFailure("malformed-api-base-url", "apiBaseUrl is not a valid absolute URL");
456
+ }
457
+ const scheme = (match[1] ?? "").toLowerCase();
458
+ const host = hostOf(match[2]);
459
+ if (host.length === 0) {
460
+ return configFailure("malformed-api-base-url", "apiBaseUrl is not a valid absolute URL");
461
+ }
462
+ const shown = canEchoOrigin(trimmed, host) ? `: ${safeOrigin(scheme, host)}` : "";
463
+ if (scheme === "https") ; else if (scheme === "http" && isLoopbackHost(host)) ; else if (scheme === "http") {
464
+ return configFailure(
465
+ "insecure-api-base-url",
466
+ `apiBaseUrl must use https (cleartext http is only allowed for localhost)${shown}`
467
+ );
468
+ } else {
469
+ return configFailure("unsupported-api-base-url-scheme", `apiBaseUrl must be http(s)${shown}`);
470
+ }
471
+ const value = trimmed.endsWith("/") ? trimmed.slice(0, -1) : trimmed;
472
+ return Object.freeze({ ok: true, value });
473
+ }
474
+ function isLoopbackHost(hostname) {
475
+ const host = hostname.toLowerCase();
476
+ return host === "localhost" || host === "127.0.0.1" || host === "[::1]" || host === "::1";
477
+ }
478
+ function readEnv(name) {
479
+ const g = globalThis;
480
+ const value = g.process?.env?.[name];
481
+ return typeof value === "string" && value.trim().length > 0 ? value.trim() : void 0;
482
+ }
483
+
484
+ // src/client/text.ts
485
+ function hasLoneSurrogate(value) {
486
+ for (let i = 0; i < value.length; i += 1) {
487
+ const code = value.charCodeAt(i);
488
+ if (code >= 55296 && code <= 56319) {
489
+ const low = value.charCodeAt(i + 1);
490
+ if (!(low >= 56320 && low <= 57343)) return true;
491
+ i += 1;
492
+ } else if (code >= 56320 && code <= 57343) {
493
+ return true;
494
+ }
495
+ }
496
+ return false;
497
+ }
498
+ function serverLength(value) {
499
+ return [...value].length;
500
+ }
501
+
502
+ // src/client/ids.ts
503
+ var MAX_USER_REF_LEN = 128;
504
+ var MAX_PET_REF_LEN = 128;
505
+ var CONTROL_CHAR = /[\u0000-\u001F\u007F]/;
506
+ var UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
507
+ function petRef(raw) {
508
+ const v = raw;
509
+ const length = serverLength(v);
510
+ if (length === 0 || length > MAX_PET_REF_LEN) {
511
+ throw new EverfurConfigError(
512
+ "invalid-argument",
513
+ `petRef must be 1..${MAX_PET_REF_LEN} characters`
514
+ );
515
+ }
516
+ if (CONTROL_CHAR.test(v)) {
517
+ throw new EverfurConfigError("invalid-argument", "petRef must be printable (no control characters)");
518
+ }
519
+ return v;
520
+ }
521
+ function userRef(raw) {
522
+ const v = raw;
523
+ const length = serverLength(v);
524
+ if (length === 0 || length > MAX_USER_REF_LEN) {
525
+ throw new EverfurConfigError(
526
+ "invalid-argument",
527
+ `userRef must be 1..${MAX_USER_REF_LEN} characters`
528
+ );
529
+ }
530
+ if (v.includes("@")) {
531
+ throw new EverfurConfigError("invalid-argument", "userRef must not contain '@'");
532
+ }
533
+ if (CONTROL_CHAR.test(v)) {
534
+ throw new EverfurConfigError("invalid-argument", "userRef must be printable (no control characters)");
535
+ }
536
+ return v;
537
+ }
538
+ function conversationId(raw) {
539
+ if (!UUID_RE.test(raw)) {
540
+ throw new EverfurConfigError("invalid-argument", "conversationId must be a UUID");
541
+ }
542
+ return raw;
543
+ }
544
+ function unsafePetRef(raw) {
545
+ return raw;
546
+ }
547
+ function unsafeUserRef(raw) {
548
+ return raw;
549
+ }
550
+ function unsafeConversationId(raw) {
551
+ return raw;
552
+ }
553
+ function unsafeResponseId(raw) {
554
+ return raw;
555
+ }
556
+ function unsafeClientId(raw) {
557
+ return raw;
558
+ }
559
+ function unsafeDocumentId(raw) {
560
+ return raw;
561
+ }
562
+ function unsafeJobId(raw) {
563
+ return raw;
564
+ }
565
+ function unsafeRecordsRequestId(raw) {
566
+ return raw;
567
+ }
568
+
569
+ // src/client/identity.ts
570
+ function createIdentityProvider(userRef2, getToken) {
571
+ let cached = null;
572
+ let inFlight = null;
573
+ let revoked = false;
574
+ const load = () => {
575
+ if (inFlight) return inFlight;
576
+ inFlight = (async () => {
577
+ try {
578
+ const token = await getToken();
579
+ if (typeof token !== "string" || token.length === 0) {
580
+ throw new EverfurConfigError("invalid-argument", "TokenProvider returned an empty token");
581
+ }
582
+ cached = token;
583
+ return token;
584
+ } finally {
585
+ inFlight = null;
586
+ }
587
+ })();
588
+ return inFlight;
589
+ };
590
+ return {
591
+ userRef: userRef2,
592
+ async currentToken(opts) {
593
+ if (revoked) {
594
+ throw new EverfurConfigError("not-initialized", "This identity was cleared (sign-out); mint a new one.");
595
+ }
596
+ if (opts?.forceRefresh) cached = null;
597
+ if (cached !== null) return cached;
598
+ return load();
599
+ },
600
+ hasToken() {
601
+ return !revoked && cached !== null;
602
+ },
603
+ clear() {
604
+ revoked = true;
605
+ cached = null;
606
+ }
607
+ };
608
+ }
609
+ function newSessionId() {
610
+ const bytes = new Uint8Array(16);
611
+ const cryptoObj = globalThis.crypto;
612
+ if (typeof cryptoObj?.getRandomValues === "function") {
613
+ cryptoObj.getRandomValues(bytes);
614
+ } else {
615
+ for (let i = 0; i < bytes.length; i += 1) bytes[i] = Math.floor(Math.random() * 256);
616
+ }
617
+ bytes[6] = bytes[6] & 15 | 64;
618
+ bytes[8] = bytes[8] & 63 | 128;
619
+ const hex = [];
620
+ for (let i = 0; i < bytes.length; i += 1) hex.push(bytes[i].toString(16).padStart(2, "0"));
621
+ 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("");
622
+ }
623
+ function authHeaders(auth) {
624
+ const headers = {};
625
+ if (auth.mode === "personalized") {
626
+ headers.authorization = `Bearer ${auth.token}`;
627
+ } else {
628
+ headers["x-everfur-partner-key"] = auth.publishableKey;
629
+ }
630
+ if (auth.userRef) headers["x-everfur-user-ref"] = auth.userRef;
631
+ if (auth.sessionId) headers["x-everfur-session-id"] = auth.sessionId;
632
+ return headers;
633
+ }
634
+ function withAuthHeaders(req, auth) {
635
+ return { ...req, headers: { ...stripAuthHeaders(req.headers), ...authHeaders(auth) } };
636
+ }
637
+ function stripAuthHeaders(headers) {
638
+ if (!headers) return {};
639
+ const out = {};
640
+ for (const [key, value] of Object.entries(headers)) {
641
+ const lower = key.toLowerCase();
642
+ if (lower === "authorization" || lower === "x-everfur-partner-key") continue;
643
+ out[key] = value;
644
+ }
645
+ return out;
646
+ }
647
+ async function authedSend(req, ctx) {
648
+ if (ctx.mode === "anonymous") {
649
+ return ctx.transport.request(
650
+ withAuthHeaders(req, {
651
+ mode: "anonymous",
652
+ publishableKey: ctx.publishableKey,
653
+ userRef: ctx.userRef,
654
+ ...ctx.sessionId ? { sessionId: ctx.sessionId } : {}
655
+ })
656
+ );
657
+ }
658
+ let token;
659
+ try {
660
+ token = await ctx.identity.currentToken();
661
+ } catch {
662
+ return err(authRejectedError());
663
+ }
664
+ const first = await ctx.transport.request(
665
+ withAuthHeaders(req, {
666
+ mode: "personalized",
667
+ token,
668
+ userRef: ctx.userRef,
669
+ ...ctx.sessionId ? { sessionId: ctx.sessionId } : {}
670
+ })
671
+ );
672
+ if (first.ok || first.error.httpStatus !== 401) return first;
673
+ let refreshed;
674
+ try {
675
+ refreshed = await ctx.identity.currentToken({ forceRefresh: true });
676
+ } catch {
677
+ return err(authRejectedError());
678
+ }
679
+ const retry = await ctx.transport.request(
680
+ withAuthHeaders(req, {
681
+ mode: "personalized",
682
+ token: refreshed,
683
+ userRef: ctx.userRef,
684
+ ...ctx.sessionId ? { sessionId: ctx.sessionId } : {}
685
+ })
686
+ );
687
+ if (!retry.ok && retry.error.httpStatus === 401) {
688
+ return err(authRejectedError(retry.error.httpStatus));
689
+ }
690
+ return retry;
691
+ }
692
+ function authRejectedError(httpStatus) {
693
+ return makeEverfurError("authRejected", {
694
+ retryable: false,
695
+ ...httpStatus !== void 0 ? { httpStatus } : {}
696
+ });
697
+ }
698
+
699
+ // src/client/protocol/frames.ts
700
+ function assertNever(x) {
701
+ throw new Error(
702
+ `assertNever: unhandled discriminated-union member ${JSON.stringify(x)}`
703
+ );
704
+ }
705
+ var EMPTY_STRINGS = Object.freeze([]);
706
+ var EMPTY_MAPS = Object.freeze([]);
707
+ function acceptedFrame(streamId, lastEventId, serverRequestId = null) {
708
+ return Object.freeze({ kind: "accepted", streamId, lastEventId, serverRequestId, terminal: false });
709
+ }
710
+ function heartbeatFrame(lastEventId, serverRequestId = null) {
711
+ return Object.freeze({ kind: "heartbeat", lastEventId, serverRequestId, terminal: false });
712
+ }
713
+ function deltaFrame(delta, lastEventId, serverRequestId = null) {
714
+ return Object.freeze({ kind: "delta", delta, lastEventId, serverRequestId, terminal: false });
715
+ }
716
+ function doneFrame(fields, serverRequestId = null) {
717
+ return Object.freeze({
718
+ kind: "done",
719
+ terminal: true,
720
+ conversationId: fields.conversationId,
721
+ messageId: fields.messageId,
722
+ title: fields.title,
723
+ followUpQuestions: Object.freeze([...fields.followUpQuestions]),
724
+ citations: Object.freeze([...fields.citations]),
725
+ citationStatus: fields.citationStatus,
726
+ urgencyLevel: fields.urgencyLevel,
727
+ urgencyReason: fields.urgencyReason,
728
+ resultId: fields.resultId,
729
+ lastEventId: fields.lastEventId,
730
+ serverRequestId
731
+ });
732
+ }
733
+ function errorFrame(fields) {
734
+ return Object.freeze({
735
+ kind: "error",
736
+ terminal: true,
737
+ code: fields.code,
738
+ retryable: fields.retryable,
739
+ wireMessage: fields.wireMessage,
740
+ synthesized: fields.synthesized,
741
+ lastEventId: fields.lastEventId,
742
+ serverRequestId: fields.serverRequestId ?? null
743
+ });
744
+ }
745
+ function analysisStartedFrame(requestId, lastEventId, serverRequestId = null) {
746
+ return Object.freeze({
747
+ kind: "analysisStarted",
748
+ requestId,
749
+ lastEventId,
750
+ serverRequestId,
751
+ terminal: false
752
+ });
753
+ }
754
+ function analysisCompleteFrame(fields, serverRequestId = null) {
755
+ return Object.freeze({
756
+ kind: "analysisComplete",
757
+ terminal: false,
758
+ resultId: fields.resultId,
759
+ analysisType: fields.analysisType,
760
+ modelVersion: fields.modelVersion,
761
+ confidence: fields.confidence,
762
+ detections: Object.freeze([...fields.detections]),
763
+ interpretation: fields.interpretation,
764
+ lastEventId: fields.lastEventId,
765
+ serverRequestId
766
+ });
767
+ }
768
+ function unknownFrame(raw, lastEventId, serverRequestId = null) {
769
+ return Object.freeze({
770
+ kind: "unknown",
771
+ raw: { ...raw },
772
+ lastEventId,
773
+ serverRequestId,
774
+ terminal: false
775
+ });
776
+ }
777
+ var EMPTY_FRAME_ARRAYS = Object.freeze({
778
+ strings: EMPTY_STRINGS,
779
+ maps: EMPTY_MAPS
780
+ });
781
+ var BLOCK_SEPARATOR = "\n\n";
782
+ var MAX_PENDING_BLOCK_CHARS = 1048576;
783
+ var wireObjectSchema = z.record(z.string(), z.unknown());
784
+ var URGENCY_LEVELS = ["emergency", "schedule_soon", "home_care"];
785
+ async function* parseSse(bytes, serverRequestId = null) {
786
+ let resolvedRequestId = null;
787
+ const requestIdNow = () => {
788
+ if (resolvedRequestId !== null) return resolvedRequestId;
789
+ resolvedRequestId = typeof serverRequestId === "function" ? serverRequestId() : serverRequestId;
790
+ return resolvedRequestId;
791
+ };
792
+ const decoder = new TextDecoder("utf-8");
793
+ let buffer = "";
794
+ let scanFrom = 0;
795
+ let sawDelta = false;
796
+ for await (const chunk of bytes) {
797
+ buffer += decoder.decode(chunk, { stream: true });
798
+ for (; ; ) {
799
+ const sep = buffer.indexOf(BLOCK_SEPARATOR, scanFrom);
800
+ if (sep === -1) break;
801
+ const block = buffer.slice(0, sep);
802
+ buffer = buffer.slice(sep + BLOCK_SEPARATOR.length);
803
+ scanFrom = 0;
804
+ const frame = parseBlock(block, requestIdNow());
805
+ if (frame === null) continue;
806
+ if (frame.kind === "delta") sawDelta = true;
807
+ yield frame;
808
+ if (frame.terminal) return;
809
+ }
810
+ scanFrom = buffer.length > 0 ? buffer.length - 1 : 0;
811
+ if (buffer.length > MAX_PENDING_BLOCK_CHARS) {
812
+ yield errorFrame({
813
+ code: sawDelta ? "CHAT_STREAM_INCOMPLETE" : "internal_error",
814
+ retryable: true,
815
+ wireMessage: null,
816
+ synthesized: true,
817
+ lastEventId: null,
818
+ serverRequestId: requestIdNow()
819
+ });
820
+ return;
821
+ }
822
+ }
823
+ buffer += decoder.decode();
824
+ if (buffer.trim().length > 0) {
825
+ const frame = parseBlock(buffer, requestIdNow());
826
+ if (frame !== null) {
827
+ if (frame.kind === "delta") sawDelta = true;
828
+ yield frame;
829
+ if (frame.terminal) return;
830
+ }
831
+ }
832
+ yield errorFrame({
833
+ code: sawDelta ? "CHAT_STREAM_INCOMPLETE" : "internal_error",
834
+ retryable: true,
835
+ wireMessage: null,
836
+ synthesized: true,
837
+ lastEventId: null,
838
+ serverRequestId: requestIdNow()
839
+ });
840
+ }
841
+ function parseBlock(block, serverRequestId) {
842
+ let id = null;
843
+ const dataLines = [];
844
+ for (const rawLine of block.split("\n")) {
845
+ const line = rawLine.replace(/\s+$/, "");
846
+ if (line.length === 0 || line.startsWith(":")) continue;
847
+ if (line.startsWith("id:")) {
848
+ id = line.slice(3).trim();
849
+ } else if (line.startsWith("data:")) {
850
+ dataLines.push(line.slice(5).replace(/^ /, ""));
851
+ }
852
+ }
853
+ if (dataLines.length === 0) return null;
854
+ let decoded;
855
+ try {
856
+ decoded = JSON.parse(dataLines.join("\n"));
857
+ } catch {
858
+ return null;
859
+ }
860
+ if (typeof decoded !== "object" || decoded === null || Array.isArray(decoded)) return null;
861
+ const parsed = wireObjectSchema.safeParse(decoded);
862
+ if (!parsed.success) return null;
863
+ return frameFromWire(parsed.data, id, serverRequestId);
864
+ }
865
+ function frameFromWire(json, lastEventId, serverRequestId) {
866
+ const type = json["type"];
867
+ const event = json["event"];
868
+ if (type === "error" || "error" in json) {
869
+ return errorFrame({
870
+ code: asString(json["code"]) ?? "unknown",
871
+ retryable: json["retryable"] === true,
872
+ wireMessage: asString(json["error"]),
873
+ synthesized: false,
874
+ lastEventId,
875
+ serverRequestId
876
+ });
877
+ }
878
+ if (type === "done" || json["done"] === true) {
879
+ return doneFrame({
880
+ conversationId: asString(json["conversation_id"]) ?? "",
881
+ messageId: asString(json["message_id"]),
882
+ title: asString(json["title"]),
883
+ followUpQuestions: asStringList(json["follow_up_questions"]),
884
+ citations: asMapList(json["citations"]),
885
+ citationStatus: asString(json["citation_status"]),
886
+ urgencyLevel: asUrgency(json["urgency_level"]),
887
+ urgencyReason: asString(json["urgency_reason"]),
888
+ resultId: asString(json["result_id"]),
889
+ lastEventId
890
+ }, serverRequestId);
891
+ }
892
+ if (type === "accepted" || json["status"] === "reasoning") {
893
+ return acceptedFrame(asString(json["stream_id"]), lastEventId, serverRequestId);
894
+ }
895
+ if (type === "heartbeat" || json["heartbeat"] === true) {
896
+ return heartbeatFrame(lastEventId, serverRequestId);
897
+ }
898
+ if (type === "text.delta" || "delta" in json || "token" in json) {
899
+ const delta = asString(json["delta"]) ?? asString(json["token"]) ?? "";
900
+ return deltaFrame(delta, lastEventId, serverRequestId);
901
+ }
902
+ if (event === "analysis_started") {
903
+ return analysisStartedFrame(asString(json["request_id"]), lastEventId, serverRequestId);
904
+ }
905
+ if (event === "analysis_complete") {
906
+ return analysisCompleteFrame({
907
+ resultId: asString(json["result_id"]),
908
+ analysisType: asString(json["analysis_type"]),
909
+ modelVersion: asString(json["model_version"]),
910
+ confidence: asNumber(json["confidence"]),
911
+ detections: asMapList(json["detections"]),
912
+ interpretation: asString(json["interpretation"]),
913
+ lastEventId
914
+ }, serverRequestId);
915
+ }
916
+ return unknownFrame(json, lastEventId, serverRequestId);
917
+ }
918
+ function asString(v) {
919
+ return typeof v === "string" ? v : null;
920
+ }
921
+ function asNumber(v) {
922
+ return typeof v === "number" && Number.isFinite(v) ? v : null;
923
+ }
924
+ function asUrgency(v) {
925
+ return typeof v === "string" && URGENCY_LEVELS.includes(v) ? v : null;
926
+ }
927
+ function asStringList(v) {
928
+ if (!Array.isArray(v)) return [];
929
+ return v.map((e) => typeof e === "string" ? e : String(e));
930
+ }
931
+ function isPlainObject(v) {
932
+ return typeof v === "object" && v !== null && !Array.isArray(v);
933
+ }
934
+ function asMapList(v) {
935
+ if (!Array.isArray(v)) return [];
936
+ return v.filter(isPlainObject);
937
+ }
938
+
939
+ // src/client/transport.ts
940
+ var UNARY_TIMEOUT_MS = 3e4;
941
+ var REQUEST_ID_HEADER = "x-request-id";
942
+ async function* fetchByteSource(body) {
943
+ if (!body) return;
944
+ const reader = body.getReader();
945
+ try {
946
+ for (; ; ) {
947
+ const { done, value } = await reader.read();
948
+ if (done) break;
949
+ if (value && value.length > 0) yield value;
950
+ }
951
+ } finally {
952
+ await reader.cancel?.();
953
+ }
954
+ }
955
+ async function* bufferedTextByteSource(text, splitAt = []) {
956
+ const bytes = new TextEncoder().encode(text);
957
+ const points = [...new Set(splitAt)].filter((n) => n > 0 && n < bytes.length).sort((a, b) => a - b);
958
+ let start = 0;
959
+ for (const point of points) {
960
+ yield bytes.subarray(start, point);
961
+ start = point;
962
+ }
963
+ yield bytes.subarray(start);
964
+ }
965
+ function eventSourceByteSource(es) {
966
+ const enc = new TextEncoder();
967
+ const queue = createByteQueue();
968
+ let cleaned = false;
969
+ const onMessage = (ev) => {
970
+ let block = "";
971
+ if (ev.lastEventId) block += `id: ${ev.lastEventId}
972
+ `;
973
+ const data = ev.data ?? "";
974
+ for (const line of data.split("\n")) block += `data: ${line}
975
+ `;
976
+ block += "\n";
977
+ queue.push(enc.encode(block));
978
+ };
979
+ const onDone = () => {
980
+ cleanup();
981
+ queue.end();
982
+ };
983
+ const onError = (ev) => {
984
+ const status = typeof ev.xhrStatus === "number" ? ev.xhrStatus : 0;
985
+ if (status >= 400) {
986
+ const wireCode = statusToWireCode(status);
987
+ const retryable = isAutoRetryable(fromWire(wireCode));
988
+ queue.push(enc.encode(`data: ${JSON.stringify({ type: "error", code: wireCode, retryable })}
989
+
990
+ `));
991
+ }
992
+ cleanup();
993
+ queue.end();
994
+ };
995
+ es.addEventListener("message", onMessage);
996
+ es.addEventListener("done", onDone);
997
+ es.addEventListener("error", onError);
998
+ function cleanup() {
999
+ if (cleaned) return;
1000
+ cleaned = true;
1001
+ es.removeEventListener("message", onMessage);
1002
+ es.removeEventListener("done", onDone);
1003
+ es.removeEventListener("error", onError);
1004
+ try {
1005
+ es.close();
1006
+ } catch {
1007
+ }
1008
+ }
1009
+ return sourceWithCleanup(queue.source, cleanup);
1010
+ }
1011
+ async function* sourceWithCleanup(source, cleanup) {
1012
+ try {
1013
+ yield* source;
1014
+ } finally {
1015
+ cleanup();
1016
+ }
1017
+ }
1018
+ function createByteQueue() {
1019
+ const buffer = [];
1020
+ let done = false;
1021
+ let wake = null;
1022
+ const signal = () => {
1023
+ if (wake) {
1024
+ const fn = wake;
1025
+ wake = null;
1026
+ fn();
1027
+ }
1028
+ };
1029
+ async function* gen() {
1030
+ for (; ; ) {
1031
+ const next = buffer.shift();
1032
+ if (next !== void 0) {
1033
+ yield next;
1034
+ continue;
1035
+ }
1036
+ if (done) return;
1037
+ await new Promise((resolve) => {
1038
+ wake = resolve;
1039
+ });
1040
+ }
1041
+ }
1042
+ return {
1043
+ source: gen(),
1044
+ push: (u) => {
1045
+ buffer.push(u);
1046
+ signal();
1047
+ },
1048
+ end: () => {
1049
+ done = true;
1050
+ signal();
1051
+ }
1052
+ };
1053
+ }
1054
+ async function requestJson(req, deps) {
1055
+ const fetchImpl = deps.fetchImpl ?? getGlobalFetch();
1056
+ const url = buildUrl(deps.config.apiBaseUrl, req.path, req.query);
1057
+ const headers = mergeHeaders(deps.config, req.headers, "application/json", req.body !== void 0 && req.multipart === void 0);
1058
+ const deadline = timeoutSignal(UNARY_TIMEOUT_MS);
1059
+ const signal = mergeAbortSignals(deadline.signal, req.signal);
1060
+ let res;
1061
+ try {
1062
+ res = await fetchImpl(url, buildInit({ ...req, signal }, headers));
1063
+ } catch (cause) {
1064
+ return err(networkError(cause));
1065
+ } finally {
1066
+ deadline.cancel();
1067
+ }
1068
+ const bodyJson = await safeJson(res);
1069
+ if (!res.ok) return err(errorFromResponse(res.status, bodyJson, requestIdOf(res)));
1070
+ return ok(bodyJson);
1071
+ }
1072
+ async function requestRaw(req, deps, byteSourceFor) {
1073
+ const fetchImpl = deps.fetchImpl ?? getGlobalFetch();
1074
+ const url = buildUrl(deps.config.apiBaseUrl, req.path, req.query);
1075
+ const headers = mergeHeaders(deps.config, req.headers, "text/event-stream", req.body !== void 0 && req.multipart === void 0);
1076
+ let res;
1077
+ try {
1078
+ res = await fetchImpl(url, buildInit(req, headers));
1079
+ } catch (cause) {
1080
+ return err(networkError(cause));
1081
+ }
1082
+ if (!res.ok) return err(errorFromResponse(res.status, await safeJson(res), requestIdOf(res)));
1083
+ const bytes = byteSourceFor ? byteSourceFor(res) : fetchByteSource(res.body);
1084
+ return ok({ ok: res.ok, status: res.status, headers: collectHeaders(res), bytes });
1085
+ }
1086
+ function createHttpTransport(deps) {
1087
+ return {
1088
+ request: (req) => requestJson(req, deps),
1089
+ stream: (req, signal) => streamFrames(withSignal(req, signal), deps)
1090
+ };
1091
+ }
1092
+ async function* streamFrames(req, deps) {
1093
+ const url = buildUrl(deps.config.apiBaseUrl, req.path, req.query);
1094
+ const headers = mergeHeaders(deps.config, req.headers, "text/event-stream", req.body !== void 0 && req.multipart === void 0);
1095
+ if (deps.eventSourceFactory) {
1096
+ const es = deps.eventSourceFactory(url, buildEventSourceInit(req, headers));
1097
+ yield* parseSse(eventSourceByteSource(es), () => eventSourceRequestId(es));
1098
+ return;
1099
+ }
1100
+ const fetchImpl = deps.fetchImpl ?? getGlobalFetch();
1101
+ let res;
1102
+ try {
1103
+ res = await fetchImpl(url, buildInit(req, headers));
1104
+ } catch (cause) {
1105
+ yield syntheticErrorFrame("", true, describeCause(cause));
1106
+ return;
1107
+ }
1108
+ const requestId = requestIdOf(res);
1109
+ if (!res.ok) {
1110
+ const body = await safeJson(res);
1111
+ const wireCode = extractWireCode(body) ?? statusToWireCode(res.status);
1112
+ const retryable = extractRetryable(body) || isAutoRetryable(fromWire(wireCode));
1113
+ yield syntheticErrorFrame(wireCode, retryable, extractWireMessage(body), requestId);
1114
+ return;
1115
+ }
1116
+ if (res.body) {
1117
+ yield* parseSse(fetchByteSource(res.body), requestId);
1118
+ return;
1119
+ }
1120
+ yield* parseSse(fetchByteSource(null), requestId);
1121
+ }
1122
+ function buildEventSourceInit(req, headers) {
1123
+ return {
1124
+ method: req.method,
1125
+ headers,
1126
+ pollingInterval: 0,
1127
+ ...req.body !== void 0 ? { body: JSON.stringify(req.body) } : {}
1128
+ };
1129
+ }
1130
+ function errorFromResponse(status, body, requestId) {
1131
+ const wireCode = extractWireCode(body);
1132
+ const code = wireCode ? fromWire(wireCode) : fromHttpStatus(status);
1133
+ const wireMessage = extractWireMessage(body);
1134
+ return makeEverfurError(code, {
1135
+ httpStatus: status,
1136
+ ...extractRetryable(body) ? { retryable: true } : {},
1137
+ ...requestId ? { requestId } : {},
1138
+ ...wireCode ? { wireCode } : {},
1139
+ ...wireMessage ? { wireMessage } : {},
1140
+ ...body !== null && body !== void 0 ? { raw: body } : {}
1141
+ });
1142
+ }
1143
+ function networkError(cause) {
1144
+ return makeEverfurError("internalError", { retryable: true, wireMessage: describeCause(cause) });
1145
+ }
1146
+ function requestIdOf(res) {
1147
+ const value = res.headers.get(REQUEST_ID_HEADER);
1148
+ return typeof value === "string" && value.length > 0 ? value : null;
1149
+ }
1150
+ function eventSourceRequestId(es) {
1151
+ if (typeof es.getResponseHeader !== "function") return null;
1152
+ let value;
1153
+ try {
1154
+ value = es.getResponseHeader(REQUEST_ID_HEADER);
1155
+ } catch {
1156
+ return null;
1157
+ }
1158
+ return typeof value === "string" && value.length > 0 ? value : null;
1159
+ }
1160
+ function statusToWireCode(status) {
1161
+ if (status === 401) return "AUTH_EXPIRED";
1162
+ if (status === 403) return "ACCESS_DENIED";
1163
+ if (status === 404) return "NOT_FOUND";
1164
+ if (status === 409) return "IDEMPOTENCY_CONFLICT";
1165
+ if (status === 421) return "MISDIRECTED_REQUEST";
1166
+ if (status === 429) return "RATE_LIMITED";
1167
+ if (status === 400 || status === 422) return "INVALID_REQUEST";
1168
+ if (status === 503) return "INTERNAL_ERROR";
1169
+ if (status >= 500) return "INTERNAL_ERROR";
1170
+ return "";
1171
+ }
1172
+ function syntheticErrorFrame(code, retryable, wireMessage, serverRequestId = null) {
1173
+ return errorFrame({ code, retryable, wireMessage, synthesized: true, lastEventId: null, serverRequestId });
1174
+ }
1175
+ function getGlobalFetch() {
1176
+ const candidate = globalThis.fetch;
1177
+ if (typeof candidate !== "function") {
1178
+ throw new EverfurConfigError(
1179
+ "missing-peer-dependency",
1180
+ "global fetch is unavailable; provide config.transport or an injected fetch implementation"
1181
+ );
1182
+ }
1183
+ return candidate;
1184
+ }
1185
+ function buildUrl(base, path, query) {
1186
+ const rel = path.startsWith("/") ? path : `/${path}`;
1187
+ let url = `${base}${rel}`;
1188
+ if (query) {
1189
+ const qs = Object.entries(query).filter((entry) => entry[1] !== void 0).map(([k, v]) => `${encodeURIComponent(k)}=${encodeURIComponent(String(v))}`).join("&");
1190
+ if (qs) url += `?${qs}`;
1191
+ }
1192
+ return url;
1193
+ }
1194
+ function mergeHeaders(config, reqHeaders, accept, hasJsonBody) {
1195
+ const headers = { ...buildBaseHeaders(config), accept };
1196
+ if (hasJsonBody) headers["content-type"] = "application/json";
1197
+ if (reqHeaders) Object.assign(headers, reqHeaders);
1198
+ return headers;
1199
+ }
1200
+ function buildInit(req, headers) {
1201
+ const init = { method: req.method, headers };
1202
+ if (req.multipart !== void 0) init.body = req.multipart;
1203
+ else if (req.body !== void 0) init.body = JSON.stringify(req.body);
1204
+ if (req.signal) init.signal = req.signal;
1205
+ return init;
1206
+ }
1207
+ function withSignal(req, signal) {
1208
+ return req.signal ? req : { ...req, signal };
1209
+ }
1210
+ function timeoutSignal(ms) {
1211
+ const ctrl = new AbortController();
1212
+ const handle = setTimeout(() => ctrl.abort(), ms);
1213
+ return {
1214
+ signal: ctrl.signal,
1215
+ cancel: () => clearTimeout(handle)
1216
+ };
1217
+ }
1218
+ function mergeAbortSignals(deadline, caller) {
1219
+ if (!caller) return deadline;
1220
+ const ctrl = new AbortController();
1221
+ if (deadline.aborted || caller.aborted) {
1222
+ ctrl.abort();
1223
+ return ctrl.signal;
1224
+ }
1225
+ const onAbort = () => ctrl.abort();
1226
+ deadline.addEventListener("abort", onAbort, { once: true });
1227
+ caller.addEventListener("abort", onAbort, { once: true });
1228
+ return ctrl.signal;
1229
+ }
1230
+ async function safeJson(res) {
1231
+ try {
1232
+ return await res.json();
1233
+ } catch {
1234
+ return null;
1235
+ }
1236
+ }
1237
+ function collectHeaders(res) {
1238
+ const out = {};
1239
+ res.headers.forEach?.((value, key) => {
1240
+ out[key.toLowerCase()] = value;
1241
+ });
1242
+ return out;
1243
+ }
1244
+ function extractWireCode(body) {
1245
+ const b = body;
1246
+ const code = b?.error?.code ?? b?.code;
1247
+ return typeof code === "string" && code.length > 0 ? code : null;
1248
+ }
1249
+ function extractWireMessage(body) {
1250
+ const b = body;
1251
+ const message = b?.error?.message ?? b?.message;
1252
+ return typeof message === "string" && message.length > 0 ? message : null;
1253
+ }
1254
+ function extractRetryable(body) {
1255
+ const b = body;
1256
+ return b?.error?.retryable === true || b?.retryable === true;
1257
+ }
1258
+ function describeCause(cause) {
1259
+ if (cause instanceof Error) return cause.message;
1260
+ return typeof cause === "string" ? cause : "network request failed";
1261
+ }
1262
+
1263
+ // src/client/entitlements/resolve.ts
1264
+ function resolveEntitlements(levels) {
1265
+ if (levels.length === 0) {
1266
+ return freezeResolved({ granted: [], asGrant: { allow: [], deny: [] } });
1267
+ }
1268
+ let allowed = null;
1269
+ const denied = /* @__PURE__ */ new Set();
1270
+ for (const level of levels) {
1271
+ const allow = new Set(level.allow);
1272
+ allowed = allowed === null ? allow : intersect(allowed, allow);
1273
+ for (const key of level.deny) denied.add(key);
1274
+ }
1275
+ const granted = [...allowed ?? /* @__PURE__ */ new Set()].filter((key) => !denied.has(key)).sort();
1276
+ return freezeResolved({ granted, asGrant: { allow: granted, deny: [] } });
1277
+ }
1278
+ function intersect(a, b) {
1279
+ const out = /* @__PURE__ */ new Set();
1280
+ for (const key of a) if (b.has(key)) out.add(key);
1281
+ return out;
1282
+ }
1283
+ function freezeResolved(r) {
1284
+ return Object.freeze({
1285
+ granted: Object.freeze([...r.granted]),
1286
+ asGrant: Object.freeze({
1287
+ allow: Object.freeze([...r.asGrant.allow]),
1288
+ deny: Object.freeze([...r.asGrant.deny])
1289
+ })
1290
+ });
1291
+ }
1292
+ var REQUIRES = Object.freeze({
1293
+ chat: Object.freeze(["chat.message.create"]),
1294
+ records: Object.freeze(["records.upload.create", "records.record.read"]),
1295
+ video: Object.freeze(["video.gait.execute"]),
1296
+ photo: Object.freeze(["photo.checkup.execute"]),
1297
+ animations: Object.freeze(["animations.state.read"])
1298
+ });
1299
+ function requires(name) {
1300
+ return REQUIRES[name];
1301
+ }
1302
+ function deniedDecisionsFor(level, reason) {
1303
+ const disabled = Object.freeze({ reason, level, recoverable: false });
1304
+ const rows = [];
1305
+ const seen = /* @__PURE__ */ new Set();
1306
+ for (const name of Object.keys(REQUIRES)) {
1307
+ for (const resource of REQUIRES[name]) {
1308
+ if (seen.has(resource)) continue;
1309
+ seen.add(resource);
1310
+ rows.push(Object.freeze({ resource, granted: false, disabled }));
1311
+ }
1312
+ }
1313
+ return Object.freeze(rows);
1314
+ }
1315
+ function decideCapability(name, decisions, opts) {
1316
+ if (opts?.isPending === true) {
1317
+ return freezeDecision({ name, enabled: false, isPending: true, limits: {} });
1318
+ }
1319
+ const keys = requires(name);
1320
+ const byResource = /* @__PURE__ */ new Map();
1321
+ for (const decision of decisions) byResource.set(decision.resource, decision);
1322
+ const limits = mergeLimits(keys, byResource);
1323
+ const missing = keys.filter((key) => byResource.get(key)?.granted !== true);
1324
+ if (missing.length === 0) {
1325
+ return freezeDecision({ name, enabled: true, isPending: false, limits });
1326
+ }
1327
+ return freezeDecision({
1328
+ name,
1329
+ enabled: false,
1330
+ isPending: false,
1331
+ limits,
1332
+ disabled: disabledFor(keys, byResource)
1333
+ });
1334
+ }
1335
+ function mergeLimits(keys, byResource) {
1336
+ const out = {};
1337
+ for (const key of keys) {
1338
+ const decisionLimits = byResource.get(key)?.limits;
1339
+ if (!decisionLimits) continue;
1340
+ for (const [limitKey, limitValue] of Object.entries(decisionLimits)) {
1341
+ const existing = out[limitKey];
1342
+ out[limitKey] = existing === void 0 ? limitValue : Math.min(existing, limitValue);
1343
+ }
1344
+ }
1345
+ return out;
1346
+ }
1347
+ function disabledFor(keys, byResource) {
1348
+ for (const key of keys) {
1349
+ const explicit = byResource.get(key)?.disabled;
1350
+ if (explicit) {
1351
+ return Object.freeze({
1352
+ reason: explicit.reason,
1353
+ level: explicit.level,
1354
+ recoverable: explicit.recoverable
1355
+ });
1356
+ }
1357
+ }
1358
+ return Object.freeze({
1359
+ reason: userFacingError("accessDenied"),
1360
+ level: "user_entitlement",
1361
+ recoverable: false
1362
+ });
1363
+ }
1364
+ function freezeDecision(d) {
1365
+ const base = {
1366
+ name: d.name,
1367
+ enabled: d.enabled,
1368
+ isPending: d.isPending,
1369
+ limits: Object.freeze({ ...d.limits })
1370
+ };
1371
+ if (d.disabled !== void 0) base.disabled = d.disabled;
1372
+ return Object.freeze(base);
1373
+ }
1374
+
1375
+ // src/client/funnel/requestFunnel.ts
1376
+ var FUNNEL_UNARY_TIMEOUT_MS = 3e4;
1377
+ var RETRY_OVERRIDE_MAX_MS = BACKOFF_CAP_MS * 2;
1378
+ var IDEMPOTENCY_HEADER = "idempotency-key";
1379
+ var MUTATING_METHODS = /* @__PURE__ */ new Set(["POST", "PUT", "PATCH", "DELETE"]);
1380
+ var NOOP_OBSERVER = Object.freeze({
1381
+ onEvent() {
1382
+ }
1383
+ });
1384
+ var defaultFunnelTimers = Object.freeze({
1385
+ setTimeout: (handler, ms) => setTimeout(handler, ms),
1386
+ clearTimeout: (handle) => clearTimeout(handle),
1387
+ now: () => Date.now()
1388
+ });
1389
+ function createRequestFunnel(deps) {
1390
+ const observer = deps.observer ?? NOOP_OBSERVER;
1391
+ const timers = deps.timers ?? defaultFunnelTimers;
1392
+ const rng = deps.rng ?? Math.random;
1393
+ const sleep = deps.sleep ?? ((ms, signal) => delayAbortable(ms, timers, signal));
1394
+ const ceiling = deps.maxAttempts ?? MAX_RETRY_ATTEMPTS;
1395
+ const timeoutMs = deps.unaryTimeoutMs ?? FUNNEL_UNARY_TIMEOUT_MS;
1396
+ const mintKey = deps.newIdempotencyKey ?? defaultIdempotencyKeyFactory();
1397
+ const emit = (event) => {
1398
+ try {
1399
+ observer.onEvent(event);
1400
+ } catch {
1401
+ }
1402
+ };
1403
+ async function send(call, req, opts) {
1404
+ const perCallMaxAttempts = opts?.maxAttempts;
1405
+ const maxAttempts = Math.max(1, perCallMaxAttempts ?? ceiling);
1406
+ const idempotent = opts?.idempotent ?? MUTATING_METHODS.has(req.method);
1407
+ const idempotencyKey = idempotent ? mintKey() : null;
1408
+ const base = assembleHeaders(req, idempotencyKey);
1409
+ let attempt = 0;
1410
+ for (; ; ) {
1411
+ const stamp = (extra) => Object.freeze({
1412
+ call,
1413
+ method: req.method,
1414
+ path: req.path,
1415
+ attempt,
1416
+ ...idempotencyKey ? { idempotencyKey } : {},
1417
+ ...extra
1418
+ });
1419
+ emit(stamp({ phase: "attempt" }));
1420
+ const deadline = boundedSignal(timeoutMs, timers);
1421
+ const merged = mergeSignals(deadline.signal, req.signal);
1422
+ let settled;
1423
+ try {
1424
+ settled = await authedSend({ ...base, signal: merged.signal }, deps.auth);
1425
+ } catch (cause) {
1426
+ settled = err(networkError(cause));
1427
+ } finally {
1428
+ merged.dispose();
1429
+ deadline.cancel();
1430
+ }
1431
+ if (settled.ok) {
1432
+ emit(stamp({ phase: "settled", ok: true, reason: "ok" }));
1433
+ return settled;
1434
+ }
1435
+ const error = settled.error;
1436
+ const decision = decideRetry(error, attempt, {
1437
+ maxAttempts,
1438
+ rng,
1439
+ now: timers.now(),
1440
+ aborted: req.signal?.aborted === true,
1441
+ ...perCallMaxAttempts !== void 0 ? { perCallMaxAttempts } : {},
1442
+ ...deps.errorPolicy !== void 0 ? { policy: deps.errorPolicy } : {}
1443
+ });
1444
+ const settledEvent = {
1445
+ ok: false,
1446
+ code: error.code,
1447
+ reason: decision.reason,
1448
+ ...error.httpStatus !== void 0 ? { httpStatus: error.httpStatus } : {},
1449
+ ...error.requestId !== void 0 ? { requestId: error.requestId } : {}
1450
+ };
1451
+ if (!decision.retry) {
1452
+ emit(stamp({ phase: "settled", ...settledEvent }));
1453
+ return err(error);
1454
+ }
1455
+ emit(stamp({ phase: "retry", ...settledEvent, delayMs: decision.delayMs }));
1456
+ await sleep(decision.delayMs, req.signal);
1457
+ if (req.signal?.aborted === true) {
1458
+ emit(stamp({ phase: "settled", ...settledEvent, reason: "aborted" }));
1459
+ return err(error);
1460
+ }
1461
+ attempt += 1;
1462
+ }
1463
+ }
1464
+ async function authorize(req) {
1465
+ return withAuthHeaders(req, await resolveDeviceAuth(deps.auth));
1466
+ }
1467
+ async function* stream(call, req, signal) {
1468
+ emit(
1469
+ Object.freeze({
1470
+ call,
1471
+ phase: "stream.open",
1472
+ method: req.method,
1473
+ path: req.path,
1474
+ attempt: 0
1475
+ })
1476
+ );
1477
+ try {
1478
+ yield* deps.auth.transport.stream(req, signal);
1479
+ } catch {
1480
+ yield errorFrame({
1481
+ // The same wire spelling sse.ts synthesizes, so `fromWire` folds it to the retryable `internalError`
1482
+ // like any other transport failure. wireMessage stays null: it is the SERVER's text, and a thrown
1483
+ // host exception's `.message` is not that.
1484
+ code: "internal_error",
1485
+ retryable: true,
1486
+ wireMessage: null,
1487
+ synthesized: true,
1488
+ lastEventId: null,
1489
+ serverRequestId: null
1490
+ });
1491
+ }
1492
+ }
1493
+ return Object.freeze({ send, authorize, stream });
1494
+ }
1495
+ function assembleHeaders(req, idempotencyKey) {
1496
+ const headers = {};
1497
+ for (const [key, value] of Object.entries(req.headers ?? {})) {
1498
+ if (key.toLowerCase() === IDEMPOTENCY_HEADER) continue;
1499
+ headers[key] = value;
1500
+ }
1501
+ if (idempotencyKey !== null) headers["Idempotency-Key"] = idempotencyKey;
1502
+ return { ...req, headers };
1503
+ }
1504
+ function defaultIdempotencyKeyFactory() {
1505
+ let counter = 0;
1506
+ return () => `efk_${Date.now().toString(36)}_${(counter++).toString(36)}_${Math.random().toString(36).slice(2, 12)}`;
1507
+ }
1508
+ var POLICY_MAX_ATTEMPTS_CAP = 10;
1509
+ function decideRetry(error, attempt, ctx) {
1510
+ if (ctx.aborted) return { retry: false, reason: "aborted" };
1511
+ const throttle = throttleKind(error);
1512
+ if (throttle === "quota") {
1513
+ return { retry: false, reason: "daily-quota-exhausted" };
1514
+ }
1515
+ if (throttle !== "burst" && !isAutoRetryable(error.code)) {
1516
+ return { retry: false, reason: "terminal-code" };
1517
+ }
1518
+ const reason = throttle === "burst" ? "burst-throttle" : "retryable-code";
1519
+ const policyVetoedRetry = () => {
1520
+ if (ctx.policy === void 0) return false;
1521
+ try {
1522
+ return !ctx.policy.shouldRetry(error.code, attempt);
1523
+ } catch {
1524
+ return false;
1525
+ }
1526
+ };
1527
+ if (policyVetoedRetry()) return { retry: false, reason: "terminal-code" };
1528
+ const policyCeiling = () => {
1529
+ if (ctx.policy === void 0) return null;
1530
+ let raw;
1531
+ try {
1532
+ raw = ctx.policy.maxAttempts(error.code);
1533
+ } catch {
1534
+ return null;
1535
+ }
1536
+ if (typeof raw !== "number" || !Number.isFinite(raw)) return null;
1537
+ return Math.max(1, Math.min(POLICY_MAX_ATTEMPTS_CAP, Math.floor(raw)));
1538
+ };
1539
+ const ceiling = ctx.perCallMaxAttempts ?? policyCeiling() ?? ctx.maxAttempts;
1540
+ if (attempt + 1 >= ceiling) return { retry: false, reason: "attempts-exhausted" };
1541
+ const override = retryOverrideMs(error, ctx.now);
1542
+ if (override !== null) {
1543
+ if (override > RETRY_OVERRIDE_MAX_MS) {
1544
+ return { retry: false, reason: "server-reset-beyond-budget" };
1545
+ }
1546
+ return { retry: true, reason, delayMs: override };
1547
+ }
1548
+ return { retry: true, reason, delayMs: backoffDelayMs(attempt, ctx.rng) };
1549
+ }
1550
+ function throttleKind(error) {
1551
+ const code = error.code === "unknown" ? fromWire(rawWireCode(error.raw)) : error.code;
1552
+ if (code === "quotaExceeded") return "quota";
1553
+ if (code === "rateLimited") return "burst";
1554
+ if (error.httpStatus === 429) {
1555
+ return "burst";
1556
+ }
1557
+ return null;
1558
+ }
1559
+ function retryOverrideMs(error, now) {
1560
+ const at = findResetsAt(error.raw);
1561
+ if (at === null) return null;
1562
+ const delta = at - now;
1563
+ return delta > 0 ? delta : 0;
1564
+ }
1565
+ function findResetsAt(raw) {
1566
+ for (const scope of candidateScopes(raw)) {
1567
+ const value = scope["resets_at"];
1568
+ const parsed = parseInstantMs(value);
1569
+ if (parsed !== null) return parsed;
1570
+ }
1571
+ return null;
1572
+ }
1573
+ function candidateScopes(raw) {
1574
+ if (!isRecord(raw)) return [];
1575
+ const out = [raw];
1576
+ for (const nested of ["error", "detail"]) {
1577
+ const value = raw[nested];
1578
+ if (isRecord(value)) out.push(value);
1579
+ }
1580
+ return out;
1581
+ }
1582
+ function parseInstantMs(value) {
1583
+ if (typeof value === "number" && Number.isFinite(value)) {
1584
+ return value < 1e11 ? Math.round(value * 1e3) : Math.round(value);
1585
+ }
1586
+ if (typeof value === "string" && value.trim().length > 0) {
1587
+ const parsed = Date.parse(value);
1588
+ return Number.isFinite(parsed) ? parsed : null;
1589
+ }
1590
+ return null;
1591
+ }
1592
+ function rawWireCode(raw) {
1593
+ for (const scope of candidateScopes(raw)) {
1594
+ const code = scope["code"];
1595
+ if (typeof code === "string" && code.length > 0) return code;
1596
+ }
1597
+ return null;
1598
+ }
1599
+ function isRecord(value) {
1600
+ return typeof value === "object" && value !== null;
1601
+ }
1602
+ async function resolveDeviceAuth(auth) {
1603
+ if (auth.mode === "anonymous") {
1604
+ return {
1605
+ mode: "anonymous",
1606
+ publishableKey: auth.publishableKey,
1607
+ userRef: auth.userRef,
1608
+ ...auth.sessionId ? { sessionId: auth.sessionId } : {}
1609
+ };
1610
+ }
1611
+ return {
1612
+ mode: "personalized",
1613
+ token: await auth.identity.currentToken(),
1614
+ userRef: auth.userRef,
1615
+ ...auth.sessionId ? { sessionId: auth.sessionId } : {}
1616
+ };
1617
+ }
1618
+ function boundedSignal(ms, timers) {
1619
+ const ctrl = new AbortController();
1620
+ const handle = timers.setTimeout(() => ctrl.abort(), ms);
1621
+ return { signal: ctrl.signal, cancel: () => timers.clearTimeout(handle) };
1622
+ }
1623
+ function mergeSignals(deadline, caller) {
1624
+ const noop = () => void 0;
1625
+ if (!caller) return { signal: deadline, dispose: noop };
1626
+ const ctrl = new AbortController();
1627
+ if (deadline.aborted || caller.aborted) {
1628
+ ctrl.abort();
1629
+ return { signal: ctrl.signal, dispose: noop };
1630
+ }
1631
+ const onAbort = () => ctrl.abort();
1632
+ deadline.addEventListener("abort", onAbort, { once: true });
1633
+ caller.addEventListener("abort", onAbort, { once: true });
1634
+ return {
1635
+ signal: ctrl.signal,
1636
+ dispose: () => {
1637
+ deadline.removeEventListener("abort", onAbort);
1638
+ caller.removeEventListener("abort", onAbort);
1639
+ }
1640
+ };
1641
+ }
1642
+ function delayAbortable(ms, timers, signal) {
1643
+ if (ms <= 0 || signal?.aborted === true) return Promise.resolve();
1644
+ return new Promise((resolve) => {
1645
+ const handle = timers.setTimeout(() => {
1646
+ signal?.removeEventListener("abort", onAbort);
1647
+ resolve();
1648
+ }, ms);
1649
+ const onAbort = () => {
1650
+ timers.clearTimeout(handle);
1651
+ resolve();
1652
+ };
1653
+ signal?.addEventListener("abort", onAbort, { once: true });
1654
+ });
1655
+ }
1656
+
1657
+ // src/client/theme/tokens.ts
1658
+ function deepFreeze(value) {
1659
+ if (value !== null && typeof value === "object" && !Object.isFrozen(value)) {
1660
+ Object.freeze(value);
1661
+ for (const key of Object.keys(value)) {
1662
+ deepFreeze(value[key]);
1663
+ }
1664
+ }
1665
+ return value;
1666
+ }
1667
+ var SPACE = { xs: 4, sm: 8, md: 12, lg: 16, xl: 24, xxl: 32 };
1668
+ var RADIUS = { tile: 5, xs: 6, sm: 10, md: 14, lg: 20, xl: 28, pill: 500 };
1669
+ var TYPE_SIZE = {
1670
+ nano: 8,
1671
+ small: 9,
1672
+ micro: 10,
1673
+ tiny: 11,
1674
+ caption: 12,
1675
+ bodyTight: 13,
1676
+ body: 14,
1677
+ subtitle: 16,
1678
+ heading: 18,
1679
+ verdict: 24
1680
+ };
1681
+ var LINE_HEIGHT = { tight: 1.15, snug: 1.3, normal: 1.4, relaxed: 1.55 };
1682
+ var WEIGHT = { regular: "400", medium: "500", bold: "700" };
1683
+ var LETTER_SPACING = {
1684
+ eyebrow: 1,
1685
+ monoWide: 0.9,
1686
+ headerBrand: -0.42,
1687
+ tight: -0.35
1688
+ };
1689
+ function baseType() {
1690
+ return {
1691
+ family: "System",
1692
+ mono: "monospace",
1693
+ fontUrl: null,
1694
+ size: TYPE_SIZE,
1695
+ lineHeight: LINE_HEIGHT,
1696
+ weight: WEIGHT,
1697
+ letterSpacing: LETTER_SPACING
1698
+ };
1699
+ }
1700
+ var MOTION = {
1701
+ duration: { instant: 80, fast: 140, normal: 220, slow: 320 },
1702
+ spring: { gentle: { damping: 18, stiffness: 200 } },
1703
+ easing: { standard: "cubic-bezier(0.4, 0, 0.2, 1)" },
1704
+ reducedMotion: false
1705
+ };
1706
+ var LIGHT_COLOR = {
1707
+ brand: "#10462E",
1708
+ brandSoft: "rgba(16,70,46,0.10)",
1709
+ brandSofter: "rgba(16,70,46,0.15)",
1710
+ brandBorder: "rgba(16,70,46,0.18)",
1711
+ borderHairlineGreen: "rgba(16,70,46,0.25)",
1712
+ surface: "#FFFFFF",
1713
+ surfaceCream: "#FDFBF8",
1714
+ surfaceSubtle: "#EFE9E3",
1715
+ background: "#FFFFFF",
1716
+ borderRingCream: "#D8D2C8",
1717
+ text: {
1718
+ primary: "#111111",
1719
+ secondary: "#0E462E",
1720
+ muted: "#6E6660",
1721
+ placeholder: "rgba(0,0,0,0.30)",
1722
+ onBrand: "#FFFFFF",
1723
+ metaCool: "#3D3D3D"
1724
+ },
1725
+ primary: "#10462E",
1726
+ onPrimary: "#FFFFFF",
1727
+ accent: "#10462E",
1728
+ onAccent: "#FFFFFF",
1729
+ accentEdge: "#07C168",
1730
+ success: "#07C168",
1731
+ danger: "#B91C1C",
1732
+ errorRed: "#FF1B00",
1733
+ warningStrong: "#A45610",
1734
+ cautionAccent: "#D9821D",
1735
+ riskConcern: "#EFA700",
1736
+ badgeBgPositive: "rgba(7,193,104,0.12)",
1737
+ badgeBgCaution: "rgba(217,130,29,0.14)",
1738
+ badgeBgCritical: "rgba(185,28,28,0.12)",
1739
+ badgeBgNeutral: "rgba(110,102,96,0.12)",
1740
+ bubbleUser: "#10462E",
1741
+ bubbleAssistant: "#FFFFFF",
1742
+ skeleton: "#EFE9E3",
1743
+ scanButtonPink: "#FFC3BC",
1744
+ checkupCardLowRiskBg: "rgba(7,193,104,0.10)",
1745
+ checkupCardConcernBg: "rgba(239,167,0,0.10)"
1746
+ };
1747
+ var EVERFUR_LIGHT = deepFreeze({
1748
+ brightness: "light",
1749
+ meta: { displayName: "Everfur", logoUrl: null, placeholder: null, hidePoweredBy: false },
1750
+ color: LIGHT_COLOR,
1751
+ space: SPACE,
1752
+ radius: RADIUS,
1753
+ type: baseType(),
1754
+ motion: MOTION
1755
+ });
1756
+ var DARK_COLOR = {
1757
+ brand: "#6BD39A",
1758
+ brandSoft: "rgba(107,211,154,0.12)",
1759
+ brandSofter: "rgba(107,211,154,0.18)",
1760
+ brandBorder: "rgba(107,211,154,0.22)",
1761
+ borderHairlineGreen: "rgba(107,211,154,0.28)",
1762
+ surface: "#1C1F23",
1763
+ surfaceCream: "#23272C",
1764
+ surfaceSubtle: "#23272C",
1765
+ background: "#15171A",
1766
+ borderRingCream: "#3A3F45",
1767
+ text: {
1768
+ primary: "#F5F3F0",
1769
+ secondary: "#A9E4C4",
1770
+ muted: "#9A938C",
1771
+ placeholder: "rgba(255,255,255,0.35)",
1772
+ onBrand: "#0E1F17",
1773
+ metaCool: "#C9C9C9"
1774
+ },
1775
+ primary: "#6BD39A",
1776
+ onPrimary: "#0E1F17",
1777
+ accent: "#6BD39A",
1778
+ onAccent: "#0E1F17",
1779
+ accentEdge: "#34D888",
1780
+ success: "#07C168",
1781
+ danger: "#B91C1C",
1782
+ errorRed: "#FF1B00",
1783
+ warningStrong: "#A45610",
1784
+ cautionAccent: "#D9821D",
1785
+ riskConcern: "#EFA700",
1786
+ badgeBgPositive: "rgba(7,193,104,0.18)",
1787
+ badgeBgCaution: "rgba(217,130,29,0.20)",
1788
+ badgeBgCritical: "rgba(185,28,28,0.22)",
1789
+ badgeBgNeutral: "rgba(255,255,255,0.10)",
1790
+ bubbleUser: "#6BD39A",
1791
+ bubbleAssistant: "#1C1F23",
1792
+ skeleton: "#23272C",
1793
+ scanButtonPink: "#FFC3BC",
1794
+ checkupCardLowRiskBg: "rgba(7,193,104,0.16)",
1795
+ checkupCardConcernBg: "rgba(239,167,0,0.16)"
1796
+ };
1797
+ var EVERFUR_DARK = deepFreeze({
1798
+ brightness: "dark",
1799
+ meta: { displayName: "Everfur", logoUrl: null, placeholder: null, hidePoweredBy: false },
1800
+ color: DARK_COLOR,
1801
+ space: SPACE,
1802
+ radius: RADIUS,
1803
+ type: baseType(),
1804
+ motion: MOTION
1805
+ });
1806
+
1807
+ // src/client/theme/resolve.ts
1808
+ function isEmptyBranding(b) {
1809
+ 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;
1810
+ }
1811
+ function parseClientBranding(json) {
1812
+ if (json === null || typeof json !== "object") return null;
1813
+ const raw = json;
1814
+ const branding = {
1815
+ displayName: parseNonEmptyString(pick(raw, "display_name", "displayName")),
1816
+ logoUrl: parseNonEmptyString(pick(raw, "logo_url", "logoUrl")),
1817
+ primaryColor: parseColor(pick(raw, "primary_color", "primaryColor")),
1818
+ accentColor: parseColor(pick(raw, "accent_color", "accentColor")),
1819
+ brightness: parseBrightness(pick(raw, "brightness")),
1820
+ fontFamily: parseNonEmptyString(pick(raw, "font_family", "fontFamily")),
1821
+ fontUrl: parseNonEmptyString(pick(raw, "font_url", "fontUrl")),
1822
+ placeholder: parseNonEmptyString(pick(raw, "chat_placeholder", "placeholder", "chatPlaceholder")),
1823
+ hidePoweredBy: parseBool(pick(raw, "hide_powered_by", "hidePoweredBy"))
1824
+ };
1825
+ return isEmptyBranding(branding) ? null : Object.freeze(branding);
1826
+ }
1827
+ function parseBool(value) {
1828
+ if (typeof value === "boolean") return value;
1829
+ if (typeof value === "string") {
1830
+ const lower = value.trim().toLowerCase();
1831
+ if (lower === "true") return true;
1832
+ if (lower === "false") return false;
1833
+ }
1834
+ return null;
1835
+ }
1836
+ function pick(raw, ...keys) {
1837
+ for (const key of keys) {
1838
+ if (Object.prototype.hasOwnProperty.call(raw, key)) {
1839
+ const value = raw[key];
1840
+ if (value !== void 0) return value;
1841
+ }
1842
+ }
1843
+ return void 0;
1844
+ }
1845
+ function parseNonEmptyString(value) {
1846
+ if (typeof value !== "string") return null;
1847
+ const trimmed = value.trim();
1848
+ return trimmed.length === 0 ? null : trimmed;
1849
+ }
1850
+ function parseBrightness(value) {
1851
+ if (typeof value !== "string") return null;
1852
+ const lower = value.trim().toLowerCase();
1853
+ return lower === "light" || lower === "dark" ? lower : null;
1854
+ }
1855
+ function parseColor(value) {
1856
+ const rgba = toRgba(value);
1857
+ return rgba === null ? null : normalizeRgba(rgba);
1858
+ }
1859
+ function toRgba(value) {
1860
+ if (typeof value === "number") return argbIntToRgba(value);
1861
+ if (typeof value !== "string") return null;
1862
+ const s = value.trim();
1863
+ if (s.length === 0) return null;
1864
+ if (s.startsWith("#")) return fromHex(s.slice(1));
1865
+ if (s.toLowerCase().startsWith("0x")) return fromArgbHex(s.slice(2));
1866
+ if (s.toLowerCase().startsWith("rgb")) return fromRgbFunc(s);
1867
+ if (/^[0-9a-fA-F]+$/.test(s)) {
1868
+ const hex = fromHex(s);
1869
+ if (hex !== null) return hex;
1870
+ }
1871
+ if (/^\d+$/.test(s)) return argbIntToRgba(Number.parseInt(s, 10));
1872
+ return null;
1873
+ }
1874
+ function fromHex(hex) {
1875
+ const h = hex.trim();
1876
+ if (!/^[0-9a-fA-F]+$/.test(h)) return null;
1877
+ if (h.length === 3) {
1878
+ const r = dup(h[0]);
1879
+ const g = dup(h[1]);
1880
+ const b = dup(h[2]);
1881
+ return { r, g, b, a: 1 };
1882
+ }
1883
+ if (h.length === 6) {
1884
+ return { r: byte(h, 0), g: byte(h, 2), b: byte(h, 4), a: 1 };
1885
+ }
1886
+ if (h.length === 8) {
1887
+ const a = byte(h, 0);
1888
+ return { r: byte(h, 2), g: byte(h, 4), b: byte(h, 6), a: a / 255 };
1889
+ }
1890
+ return null;
1891
+ }
1892
+ function fromArgbHex(hex) {
1893
+ return fromHex(hex);
1894
+ }
1895
+ function fromRgbFunc(input) {
1896
+ const open = input.indexOf("(");
1897
+ const close = input.indexOf(")");
1898
+ if (open < 0 || close < 0 || close < open) return null;
1899
+ const parts = input.slice(open + 1, close).split(",").map((p) => p.trim());
1900
+ if (parts.length < 3) return null;
1901
+ const r = clampByte(Number(parts[0]));
1902
+ const g = clampByte(Number(parts[1]));
1903
+ const b = clampByte(Number(parts[2]));
1904
+ if (r === null || g === null || b === null) return null;
1905
+ let a = 1;
1906
+ if (parts.length >= 4) {
1907
+ const alpha = Number(parts[3]);
1908
+ if (!Number.isFinite(alpha)) return null;
1909
+ a = Math.min(1, Math.max(0, alpha));
1910
+ }
1911
+ return { r, g, b, a };
1912
+ }
1913
+ function argbIntToRgba(n) {
1914
+ if (!Number.isFinite(n)) return null;
1915
+ const int = Math.trunc(n) >>> 0;
1916
+ const a = int >>> 24 & 255;
1917
+ return {
1918
+ r: int >>> 16 & 255,
1919
+ g: int >>> 8 & 255,
1920
+ b: int & 255,
1921
+ // A 0x00RRGGBB with no alpha byte reads as fully transparent; treat a zero alpha byte as opaque so a
1922
+ // bare 0xRRGGBB (or small decimal) is not silently invisible.
1923
+ a: a === 0 ? 1 : a / 255
1924
+ };
1925
+ }
1926
+ function byte(hex, at) {
1927
+ return Number.parseInt(hex.slice(at, at + 2), 16);
1928
+ }
1929
+ function dup(nibble) {
1930
+ return Number.parseInt(`${nibble ?? "0"}${nibble ?? "0"}`, 16);
1931
+ }
1932
+ function clampByte(n) {
1933
+ if (!Number.isFinite(n)) return null;
1934
+ return Math.min(255, Math.max(0, Math.round(n)));
1935
+ }
1936
+ function normalizeRgba(rgba) {
1937
+ if (rgba.a >= 1) {
1938
+ return `#${hex2(rgba.r)}${hex2(rgba.g)}${hex2(rgba.b)}`.toUpperCase();
1939
+ }
1940
+ const a = Math.round(rgba.a * 1e3) / 1e3;
1941
+ return `rgba(${rgba.r},${rgba.g},${rgba.b},${a})`;
1942
+ }
1943
+ function hex2(n) {
1944
+ return n.toString(16).padStart(2, "0");
1945
+ }
1946
+ var NEAR_BLACK = "#111111";
1947
+ var WHITE = "#FFFFFF";
1948
+ function readableOn(background) {
1949
+ const rgba = toRgba(background);
1950
+ if (rgba === null) return WHITE;
1951
+ const bg = relativeLuminance(rgba);
1952
+ const black = relativeLuminance({ r: 17, g: 17, b: 17});
1953
+ const white = relativeLuminance({ r: 255, g: 255, b: 255});
1954
+ const contrastBlack = contrastRatio(bg, black);
1955
+ const contrastWhite = contrastRatio(bg, white);
1956
+ return contrastWhite >= contrastBlack ? WHITE : NEAR_BLACK;
1957
+ }
1958
+ function relativeLuminance(rgba) {
1959
+ const r = linearize(rgba.r / 255);
1960
+ const g = linearize(rgba.g / 255);
1961
+ const b = linearize(rgba.b / 255);
1962
+ return 0.2126 * r + 0.7152 * g + 0.0722 * b;
1963
+ }
1964
+ function linearize(channel) {
1965
+ return channel <= 0.03928 ? channel / 12.92 : Math.pow((channel + 0.055) / 1.055, 2.4);
1966
+ }
1967
+ function contrastRatio(l1, l2) {
1968
+ const lighter = Math.max(l1, l2);
1969
+ const darker = Math.min(l1, l2);
1970
+ return (lighter + 0.05) / (darker + 0.05);
1971
+ }
1972
+ function hardenHttpsUrl(url) {
1973
+ if (url === null) return null;
1974
+ const trimmed = url.trim();
1975
+ if (trimmed.length === 0) return null;
1976
+ return /^https:\/\/\S+$/i.test(trimmed) ? trimmed : null;
1977
+ }
1978
+ function withServerBranding(base, b) {
1979
+ if (b === null || isEmptyBranding(b)) return base;
1980
+ const palette = b.brightness !== null && b.brightness !== base.brightness ? b.brightness === "dark" ? EVERFUR_DARK : EVERFUR_LIGHT : base;
1981
+ const primary = b.primaryColor ?? palette.color.primary;
1982
+ const accent = b.accentColor ?? palette.color.accent;
1983
+ const pr = b.primaryColor !== null ? toRgba(primary) : null;
1984
+ const lift = (c) => Math.round(c + (255 - c) * 0.4);
1985
+ const brandFamily = pr !== null ? {
1986
+ brand: primary,
1987
+ bubbleUser: primary,
1988
+ text: { ...palette.color.text, secondary: primary },
1989
+ brandSoft: `rgba(${pr.r}, ${pr.g}, ${pr.b}, 0.10)`,
1990
+ brandSofter: `rgba(${pr.r}, ${pr.g}, ${pr.b}, 0.15)`,
1991
+ brandBorder: `rgba(${pr.r}, ${pr.g}, ${pr.b}, 0.20)`,
1992
+ borderHairlineGreen: `rgba(${pr.r}, ${pr.g}, ${pr.b}, 0.28)`,
1993
+ accentEdge: `rgb(${lift(pr.r)}, ${lift(pr.g)}, ${lift(pr.b)})`
1994
+ } : {};
1995
+ const next = {
1996
+ brightness: palette.brightness,
1997
+ meta: {
1998
+ displayName: b.displayName ?? palette.meta.displayName,
1999
+ logoUrl: b.logoUrl ?? palette.meta.logoUrl,
2000
+ placeholder: b.placeholder ?? palette.meta.placeholder,
2001
+ hidePoweredBy: b.hidePoweredBy ?? palette.meta.hidePoweredBy
2002
+ },
2003
+ color: {
2004
+ ...palette.color,
2005
+ ...brandFamily,
2006
+ primary,
2007
+ accent,
2008
+ // onPrimary/onAccent are recomputed by resolveTheme; carry the palette defaults for a standalone call.
2009
+ onPrimary: palette.color.onPrimary,
2010
+ onAccent: palette.color.onAccent
2011
+ },
2012
+ space: palette.space,
2013
+ radius: palette.radius,
2014
+ type: {
2015
+ ...palette.type,
2016
+ family: b.fontFamily ?? palette.type.family,
2017
+ fontUrl: b.fontUrl ?? palette.type.fontUrl
2018
+ },
2019
+ motion: palette.motion
2020
+ };
2021
+ return deepFreeze(next);
2022
+ }
2023
+ var DEFAULT_DISPLAY_NAME = "Everfur";
2024
+ function resolveTheme(input) {
2025
+ const scheme = input?.colorScheme === "dark" ? "dark" : "light";
2026
+ const systemBase = scheme === "dark" ? EVERFUR_DARK : EVERFUR_LIGHT;
2027
+ const withClient = withServerBranding(systemBase, input?.clientOverride ?? null);
2028
+ const merged = withServerBranding(withClient, input?.branding ?? null);
2029
+ return finalize(merged, input?.reducedMotion === true);
2030
+ }
2031
+ function finalize(theme, reducedMotion) {
2032
+ const primary = theme.color.primary;
2033
+ const accent = theme.color.accent;
2034
+ const displayName = theme.meta.displayName.trim().length === 0 ? DEFAULT_DISPLAY_NAME : theme.meta.displayName;
2035
+ const logoUrl = hardenHttpsUrl(theme.meta.logoUrl);
2036
+ const fontUrl = hardenHttpsUrl(theme.type.fontUrl);
2037
+ const motion = reducedMotion ? {
2038
+ duration: { instant: 0, fast: 0, normal: 0, slow: 0 },
2039
+ // Stiffen the spring so it settles immediately with no perceptible bounce.
2040
+ spring: { gentle: { damping: 100, stiffness: 1e3 } },
2041
+ easing: theme.motion.easing,
2042
+ reducedMotion: true
2043
+ } : theme.motion;
2044
+ const finalized = {
2045
+ brightness: theme.brightness,
2046
+ meta: { displayName, logoUrl, placeholder: theme.meta.placeholder, hidePoweredBy: theme.meta.hidePoweredBy },
2047
+ color: {
2048
+ ...theme.color,
2049
+ primary,
2050
+ accent,
2051
+ onPrimary: readableOn(primary),
2052
+ onAccent: readableOn(accent)
2053
+ },
2054
+ space: theme.space,
2055
+ radius: theme.radius,
2056
+ type: { ...theme.type, fontUrl },
2057
+ motion
2058
+ };
2059
+ return deepFreeze(finalized);
2060
+ }
2061
+
2062
+ // src/client/entitlements/entitlementRepository.ts
2063
+ var ENTITLEMENTS_PATH = "/widget/v1/entitlements";
2064
+ var HTTP_NOT_MODIFIED = 304;
2065
+ var NOT_MODIFIED = Object.freeze({ kind: "notModified" });
2066
+ async function fetchEntitlements(auth, args = {}, funnel = createRequestFunnel({ auth })) {
2067
+ const result = await funnel.send(
2068
+ "entitlements.fetch",
2069
+ buildRequest(args)
2070
+ );
2071
+ if (!result.ok) {
2072
+ if (result.error.httpStatus === HTTP_NOT_MODIFIED) return NOT_MODIFIED;
2073
+ return { kind: "failed", error: result.error };
2074
+ }
2075
+ return parseUpdated(result.value);
2076
+ }
2077
+ var REGION_MAX = 64;
2078
+ function buildRequest(args) {
2079
+ const headers = {};
2080
+ if (isFiniteNumber(args.cachedRevision)) {
2081
+ headers["if-none-match"] = `"${args.cachedRevision}"`;
2082
+ }
2083
+ if (args.region && args.region.length <= REGION_MAX) {
2084
+ return { method: "GET", path: ENTITLEMENTS_PATH, headers, query: { region: args.region } };
2085
+ }
2086
+ return { method: "GET", path: ENTITLEMENTS_PATH, headers };
2087
+ }
2088
+ function parseUpdated(body) {
2089
+ if (body === null || typeof body !== "object") return malformed();
2090
+ if (!isFiniteNumber(body.revision)) return malformed();
2091
+ const region = typeof body.region === "string" ? body.region : "";
2092
+ const ttlSeconds = isFiniteNumber(body.ttl_seconds) ? body.ttl_seconds : 0;
2093
+ return Object.freeze({
2094
+ kind: "updated",
2095
+ revision: body.revision,
2096
+ region,
2097
+ ttlSeconds,
2098
+ decisions: mapCapabilities(body.capabilities),
2099
+ // Branding is ADDITIVE and orthogonal to capabilities: a parse fault here NEVER affects the decisions and
2100
+ // fails closed to null (the compiled default theme). It cannot make a granted capability un-render.
2101
+ branding: parseBranding(body)
2102
+ });
2103
+ }
2104
+ function parseBranding(body) {
2105
+ const direct = parseClientBranding(body.branding);
2106
+ if (direct !== null) return direct;
2107
+ const hints = body.render_hints;
2108
+ if (hints !== null && typeof hints === "object") {
2109
+ const nested = parseClientBranding(hints.branding);
2110
+ if (nested !== null) return nested;
2111
+ return parseClientBranding(hints);
2112
+ }
2113
+ return null;
2114
+ }
2115
+ function mapCapabilities(capabilities) {
2116
+ if (capabilities === null || typeof capabilities !== "object") return Object.freeze([]);
2117
+ const out = [];
2118
+ for (const [resource, value] of Object.entries(capabilities)) {
2119
+ if (isEnabled(value)) out.push(Object.freeze({ resource, granted: true }));
2120
+ }
2121
+ return Object.freeze(out);
2122
+ }
2123
+ function isEnabled(value) {
2124
+ return typeof value === "object" && value !== null && value.enabled === true;
2125
+ }
2126
+ function malformed() {
2127
+ return {
2128
+ kind: "failed",
2129
+ error: makeEverfurError("internalError", {
2130
+ retryable: true,
2131
+ wireMessage: "malformed entitlements response"
2132
+ })
2133
+ };
2134
+ }
2135
+ function isFiniteNumber(value) {
2136
+ return typeof value === "number" && Number.isFinite(value);
2137
+ }
2138
+
2139
+ // src/client/pets/petsRepository.ts
2140
+ var PET_NAME_MAX = 100;
2141
+ var PET_SPECIES_MAX = 50;
2142
+ var PET_BREED_MAX = 100;
2143
+ var PET_AGE_YEARS_MAX = 50;
2144
+ var PET_WEIGHT_KG_MAX = 500;
2145
+ var PET_REF_MAX = 128;
2146
+ function invalid(wireMessage) {
2147
+ return makeEverfurError("validationFailed", { retryable: false, wireMessage });
2148
+ }
2149
+ function checkString(field, value, max) {
2150
+ if (typeof value !== "string") return invalid(`${field} must be a string`);
2151
+ const length = serverLength(value);
2152
+ if (length <= max) return null;
2153
+ return invalid(`${field} is ${length} characters; the server accepts at most ${max}`);
2154
+ }
2155
+ function outOfRange(field, value, max) {
2156
+ if (typeof value === "number" && Number.isFinite(value) && value >= 0 && value <= max) return null;
2157
+ return invalid(`${field} must be a finite number between 0 and ${max}`);
2158
+ }
2159
+ function validate(petRef2, profile) {
2160
+ if (typeof petRef2 !== "string") return invalid("pet_ref must be a string");
2161
+ if (petRef2.trim().length === 0) return invalid("pet_ref must not be blank");
2162
+ if (hasLoneSurrogate(petRef2)) return invalid("pet_ref contains an unpaired surrogate and cannot be encoded");
2163
+ if (profile !== void 0 && profile !== null && typeof profile !== "object") {
2164
+ return invalid("profile must be an object");
2165
+ }
2166
+ const checks = [checkString("pet_ref", petRef2, PET_REF_MAX)];
2167
+ if (profile?.name !== void 0) checks.push(checkString("name", profile.name, PET_NAME_MAX));
2168
+ if (profile?.species !== void 0) checks.push(checkString("species", profile.species, PET_SPECIES_MAX));
2169
+ if (profile?.breed !== void 0) checks.push(checkString("breed", profile.breed, PET_BREED_MAX));
2170
+ if (profile?.ageYears !== void 0) checks.push(outOfRange("age_years", profile.ageYears, PET_AGE_YEARS_MAX));
2171
+ if (profile?.weightKg !== void 0) checks.push(outOfRange("weight_kg", profile.weightKg, PET_WEIGHT_KG_MAX));
2172
+ return checks.find((c) => c !== null) ?? null;
2173
+ }
2174
+ function toWire(profile) {
2175
+ if (profile === void 0 || profile === null) return {};
2176
+ return {
2177
+ ...profile.name !== void 0 ? { name: profile.name } : {},
2178
+ ...profile.species !== void 0 ? { species: profile.species } : {},
2179
+ ...profile.breed !== void 0 ? { breed: profile.breed } : {},
2180
+ ...profile.ageYears !== void 0 ? { age_years: profile.ageYears } : {},
2181
+ ...profile.weightKg !== void 0 ? { weight_kg: profile.weightKg } : {}
2182
+ };
2183
+ }
2184
+ function fromWire2(raw, petRef2) {
2185
+ const o = typeof raw === "object" && raw !== null ? raw : {};
2186
+ const str = (v) => typeof v === "string" ? v : null;
2187
+ const num = (v) => typeof v === "number" && Number.isFinite(v) ? v : null;
2188
+ return Object.freeze({
2189
+ petRef: str(o["pet_ref"]) ?? petRef2,
2190
+ name: str(o["name"]),
2191
+ species: str(o["species"]),
2192
+ breed: str(o["breed"]),
2193
+ ageYears: num(o["age_years"]),
2194
+ weightKg: num(o["weight_kg"])
2195
+ });
2196
+ }
2197
+ function createPetsRepository(auth) {
2198
+ return createPetsRepositoryOver(createRequestFunnel({ auth }));
2199
+ }
2200
+ function createPetsRepositoryOver(funnel) {
2201
+ return {
2202
+ async registerPet(petRef2, profile, opts) {
2203
+ const invalid2 = validate(petRef2, profile);
2204
+ if (invalid2 !== null) return err(invalid2);
2205
+ const path = `/widget/v1/pets/${encodeURIComponent(petRef2)}`;
2206
+ const base = { method: "POST", path, body: toWire(profile) };
2207
+ const res = await funnel.send(
2208
+ "pets.registerPet",
2209
+ opts?.signal ? { ...base, signal: opts.signal } : base
2210
+ );
2211
+ if (!res.ok) return err(res.error);
2212
+ return ok(fromWire2(res.value, petRef2));
2213
+ }
2214
+ };
2215
+ }
2216
+
2217
+ export { AUTO_RETRYABLE_CODES, BACKOFF_BASE_MS, BACKOFF_CAP_MS, CONTRACT_ERROR_ROWS, DEFAULT_CONTRACT_VERSION, DOC_SITE_ORIGIN, EMPTY_FRAME_ARRAYS, ENTITLEMENTS_PATH, ENV_API_BASE_URL, EVERFUR_DARK, EVERFUR_ERROR_CATEGORIES, EVERFUR_ERROR_CODES, EVERFUR_LIGHT, EverfurConfigError, EverfurThrownError, MAX_RETRY_ATTEMPTS, PET_AGE_YEARS_MAX, PET_BREED_MAX, PET_NAME_MAX, PET_SPECIES_MAX, PET_WEIGHT_KG_MAX, RETRYABLE_CONTRACT_CODES, SDK_PLATFORM, SDK_VERSION, acceptedFrame, analysisCompleteFrame, analysisStartedFrame, assertNever, authHeaders, authedSend, backoffDelayMs, bufferedTextByteSource, buildBaseHeaders, canRecreateOnNotFound, categoryFor, checkPublishableKey, contractDocUrl, contractErrorFor, conversationId, createHttpTransport, createIdentityProvider, createPetsRepository, decideCapability, deepFreeze, deltaFrame, deniedDecisionsFor, doneFrame, err, errorFrame, errorFromResponse, eventSourceByteSource, eventSourceRequestId, fetchByteSource, fetchEntitlements, fromHttpStatus, fromWire, getGlobalFetch, hardenHttpsUrl, heartbeatFrame, isAutoRetryable, isEmptyBranding, isErr, isOk, isRetryableCode, makeEverfurError, networkError, newSessionId, ok, parseClientBranding, parseColor, parseSse, petRef, publishedDocUrl, readableOn, requestIdOf, requestJson, requestRaw, requires, resolveApiBaseUrl, resolveClientConfig, resolveEntitlements, resolveTheme, shouldRetry, tryResolveApiBaseUrl, tryResolveClientConfig, unknownFrame, unsafeClientId, unsafeConversationId, unsafeDocumentId, unsafeJobId, unsafePetRef, unsafeRecordsRequestId, unsafeResponseId, unsafeUserRef, unwrap, userFacingError, userRef, withAuthHeaders, withServerBranding };