@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,1972 @@
1
+ import { createContext, useState, useEffect, useCallback, useSyncExternalStore, useMemo, useRef, useContext } from 'react';
2
+ import { AccessibilityInfo, View, Image, Text, ActivityIndicator, StyleSheet } from 'react-native';
3
+ import 'react-native-safe-area-context';
4
+ import { jsx, jsxs } from 'react/jsx-runtime';
5
+ import { z } from 'zod';
6
+
7
+ // src/rn/animations/PetStateView.tsx
8
+
9
+ // src/client/protocol/frames.ts
10
+ function assertNever(x) {
11
+ throw new Error(
12
+ `assertNever: unhandled discriminated-union member ${JSON.stringify(x)}`
13
+ );
14
+ }
15
+ function errorFrame(fields) {
16
+ return Object.freeze({
17
+ kind: "error",
18
+ terminal: true,
19
+ code: fields.code,
20
+ retryable: fields.retryable,
21
+ wireMessage: fields.wireMessage,
22
+ synthesized: fields.synthesized,
23
+ lastEventId: fields.lastEventId,
24
+ serverRequestId: null
25
+ });
26
+ }
27
+
28
+ // src/client/theme/tokens.ts
29
+ function deepFreeze(value) {
30
+ if (value !== null && typeof value === "object" && !Object.isFrozen(value)) {
31
+ Object.freeze(value);
32
+ for (const key of Object.keys(value)) {
33
+ deepFreeze(value[key]);
34
+ }
35
+ }
36
+ return value;
37
+ }
38
+ var SPACE = { xs: 4, sm: 8, md: 12, lg: 16, xl: 24, xxl: 32 };
39
+ var RADIUS = { tile: 5, xs: 6, sm: 10, md: 14, lg: 20, xl: 28, pill: 500 };
40
+ var TYPE_SIZE = {
41
+ nano: 8,
42
+ small: 9,
43
+ micro: 10,
44
+ tiny: 11,
45
+ caption: 12,
46
+ bodyTight: 13,
47
+ body: 14,
48
+ subtitle: 16,
49
+ heading: 18,
50
+ verdict: 24
51
+ };
52
+ var LINE_HEIGHT = { tight: 1.15, snug: 1.3, normal: 1.4, relaxed: 1.55 };
53
+ var WEIGHT = { regular: "400", medium: "500", bold: "700" };
54
+ var LETTER_SPACING = {
55
+ eyebrow: 1,
56
+ monoWide: 0.9,
57
+ headerBrand: -0.42,
58
+ tight: -0.35
59
+ };
60
+ function baseType() {
61
+ return {
62
+ family: "System",
63
+ mono: "monospace",
64
+ fontUrl: null,
65
+ size: TYPE_SIZE,
66
+ lineHeight: LINE_HEIGHT,
67
+ weight: WEIGHT,
68
+ letterSpacing: LETTER_SPACING
69
+ };
70
+ }
71
+ var MOTION = {
72
+ duration: { instant: 80, fast: 140, normal: 220, slow: 320 },
73
+ spring: { gentle: { damping: 18, stiffness: 200 } },
74
+ easing: { standard: "cubic-bezier(0.4, 0, 0.2, 1)" },
75
+ reducedMotion: false
76
+ };
77
+ var LIGHT_COLOR = {
78
+ brand: "#10462E",
79
+ brandSoft: "rgba(16,70,46,0.10)",
80
+ brandSofter: "rgba(16,70,46,0.15)",
81
+ brandBorder: "rgba(16,70,46,0.18)",
82
+ borderHairlineGreen: "rgba(16,70,46,0.25)",
83
+ surface: "#FFFFFF",
84
+ surfaceCream: "#FDFBF8",
85
+ surfaceSubtle: "#EFE9E3",
86
+ background: "#FFFFFF",
87
+ borderRingCream: "#D8D2C8",
88
+ text: {
89
+ primary: "#111111",
90
+ secondary: "#0E462E",
91
+ muted: "#6E6660",
92
+ placeholder: "rgba(0,0,0,0.30)",
93
+ onBrand: "#FFFFFF",
94
+ metaCool: "#3D3D3D"
95
+ },
96
+ primary: "#10462E",
97
+ onPrimary: "#FFFFFF",
98
+ accent: "#10462E",
99
+ onAccent: "#FFFFFF",
100
+ accentEdge: "#07C168",
101
+ success: "#07C168",
102
+ danger: "#B91C1C",
103
+ errorRed: "#FF1B00",
104
+ warningStrong: "#A45610",
105
+ cautionAccent: "#D9821D",
106
+ riskConcern: "#EFA700",
107
+ badgeBgPositive: "rgba(7,193,104,0.12)",
108
+ badgeBgCaution: "rgba(217,130,29,0.14)",
109
+ badgeBgCritical: "rgba(185,28,28,0.12)",
110
+ badgeBgNeutral: "rgba(110,102,96,0.12)",
111
+ bubbleUser: "#10462E",
112
+ bubbleAssistant: "#FFFFFF",
113
+ skeleton: "#EFE9E3",
114
+ scanButtonPink: "#FFC3BC",
115
+ checkupCardLowRiskBg: "rgba(7,193,104,0.10)",
116
+ checkupCardConcernBg: "rgba(239,167,0,0.10)"
117
+ };
118
+ var EVERFUR_LIGHT = deepFreeze({
119
+ brightness: "light",
120
+ meta: { displayName: "Everfur", logoUrl: null, placeholder: null, hidePoweredBy: false },
121
+ color: LIGHT_COLOR,
122
+ space: SPACE,
123
+ radius: RADIUS,
124
+ type: baseType(),
125
+ motion: MOTION
126
+ });
127
+ var DARK_COLOR = {
128
+ brand: "#6BD39A",
129
+ brandSoft: "rgba(107,211,154,0.12)",
130
+ brandSofter: "rgba(107,211,154,0.18)",
131
+ brandBorder: "rgba(107,211,154,0.22)",
132
+ borderHairlineGreen: "rgba(107,211,154,0.28)",
133
+ surface: "#1C1F23",
134
+ surfaceCream: "#23272C",
135
+ surfaceSubtle: "#23272C",
136
+ background: "#15171A",
137
+ borderRingCream: "#3A3F45",
138
+ text: {
139
+ primary: "#F5F3F0",
140
+ secondary: "#A9E4C4",
141
+ muted: "#9A938C",
142
+ placeholder: "rgba(255,255,255,0.35)",
143
+ onBrand: "#0E1F17",
144
+ metaCool: "#C9C9C9"
145
+ },
146
+ primary: "#6BD39A",
147
+ onPrimary: "#0E1F17",
148
+ accent: "#6BD39A",
149
+ onAccent: "#0E1F17",
150
+ accentEdge: "#34D888",
151
+ success: "#07C168",
152
+ danger: "#B91C1C",
153
+ errorRed: "#FF1B00",
154
+ warningStrong: "#A45610",
155
+ cautionAccent: "#D9821D",
156
+ riskConcern: "#EFA700",
157
+ badgeBgPositive: "rgba(7,193,104,0.18)",
158
+ badgeBgCaution: "rgba(217,130,29,0.20)",
159
+ badgeBgCritical: "rgba(185,28,28,0.22)",
160
+ badgeBgNeutral: "rgba(255,255,255,0.10)",
161
+ bubbleUser: "#6BD39A",
162
+ bubbleAssistant: "#1C1F23",
163
+ skeleton: "#23272C",
164
+ scanButtonPink: "#FFC3BC",
165
+ checkupCardLowRiskBg: "rgba(7,193,104,0.16)",
166
+ checkupCardConcernBg: "rgba(239,167,0,0.16)"
167
+ };
168
+ deepFreeze({
169
+ brightness: "dark",
170
+ meta: { displayName: "Everfur", logoUrl: null, placeholder: null, hidePoweredBy: false },
171
+ color: DARK_COLOR,
172
+ space: SPACE,
173
+ radius: RADIUS,
174
+ type: baseType(),
175
+ motion: MOTION
176
+ });
177
+
178
+ // src/client/errors/EverfurResult.ts
179
+ function ok(value, warning) {
180
+ return Object.freeze(
181
+ { ok: true, value }
182
+ );
183
+ }
184
+ function err(error) {
185
+ return Object.freeze({ ok: false, error });
186
+ }
187
+ var EverfurConfigError = class _EverfurConfigError extends Error {
188
+ constructor(kind, message) {
189
+ super(message);
190
+ this.name = "EverfurConfigError";
191
+ this.kind = kind;
192
+ Object.setPrototypeOf(this, _EverfurConfigError.prototype);
193
+ }
194
+ };
195
+
196
+ // src/core/ports/TelemetryPort.ts
197
+ var noopTelemetry = Object.freeze({
198
+ track() {
199
+ },
200
+ trackExpectedFailure() {
201
+ }
202
+ });
203
+ var CONTRACT_RETRYABILITY = Object.freeze([
204
+ Object.freeze({ wireCode: "AccessDeniedException", envelope: "http_envelope", httpStatus: 403, retryable: false }),
205
+ Object.freeze({ wireCode: "AuthorizationException", envelope: "http_envelope", httpStatus: 401, retryable: false }),
206
+ Object.freeze({ wireCode: "ConflictException", envelope: "http_envelope", httpStatus: 409, retryable: true }),
207
+ Object.freeze({ wireCode: "DAILY_QUOTA_EXCEEDED", envelope: "http_envelope", httpStatus: 429, retryable: true }),
208
+ Object.freeze({ wireCode: "IDEMPOTENCY_KEY_IN_FLIGHT", envelope: "http_envelope", httpStatus: 409, retryable: true }),
209
+ Object.freeze({ wireCode: "IDEMPOTENCY_KEY_REUSED_DIFFERENT_REQUEST", envelope: "http_envelope", httpStatus: 409, retryable: false }),
210
+ Object.freeze({ wireCode: "InternalFailureException", envelope: "http_envelope", httpStatus: 500, retryable: true }),
211
+ Object.freeze({ wireCode: "NotImplementedException", envelope: "http_envelope", httpStatus: 501, retryable: false }),
212
+ Object.freeze({ wireCode: "PaymentRequiredException", envelope: "http_envelope", httpStatus: 402, retryable: false }),
213
+ Object.freeze({ wireCode: "ResourceNotFoundException", envelope: "http_envelope", httpStatus: 404, retryable: false }),
214
+ Object.freeze({ wireCode: "ServiceUnavailableException", envelope: "http_envelope", httpStatus: 503, retryable: true }),
215
+ Object.freeze({ wireCode: "TIER_UPGRADE_REQUIRED", envelope: "http_envelope", httpStatus: 402, retryable: false }),
216
+ Object.freeze({ wireCode: "ThrottlingException", envelope: "http_envelope", httpStatus: 429, retryable: true }),
217
+ Object.freeze({ wireCode: "ValidationException", envelope: "http_envelope", httpStatus: 400, retryable: false }),
218
+ Object.freeze({ wireCode: "accessDenied", envelope: "http_envelope", httpStatus: 403, retryable: false }),
219
+ Object.freeze({ wireCode: "authExpired", envelope: "http_envelope", httpStatus: 401, retryable: true }),
220
+ Object.freeze({ wireCode: "internal_error", envelope: "sse_frame", httpStatus: 200, retryable: false }),
221
+ Object.freeze({ wireCode: "invalidRequest", envelope: "http_envelope", httpStatus: 400, retryable: false }),
222
+ Object.freeze({ wireCode: "not_found", envelope: "sse_frame", httpStatus: 200, retryable: false }),
223
+ Object.freeze({ wireCode: "session_required", envelope: "http_envelope", httpStatus: 403, retryable: false }),
224
+ Object.freeze({ wireCode: "timeout", envelope: "sse_frame", httpStatus: 200, retryable: true }),
225
+ Object.freeze({ wireCode: "unavailable", envelope: "http_envelope", httpStatus: 503, retryable: true })
226
+ ]);
227
+ Object.freeze(
228
+ CONTRACT_RETRYABILITY.map((row) => row.wireCode)
229
+ );
230
+
231
+ // src/client/errors/contract.ts
232
+ var NORMALIZED_FOLD = Object.freeze({
233
+ // the default status-mapped envelope
234
+ ValidationException: "validationFailed",
235
+ AuthorizationException: "authRejected",
236
+ PaymentRequiredException: "paymentRequired",
237
+ AccessDeniedException: "accessDenied",
238
+ ResourceNotFoundException: "resourceNotFound",
239
+ ConflictException: "conflict",
240
+ ThrottlingException: "rateLimited",
241
+ InternalFailureException: "internalError",
242
+ NotImplementedException: "notImplemented",
243
+ ServiceUnavailableException: "serviceUnavailable",
244
+ // dict-detail codes on the widget surface
245
+ authExpired: "authExpired",
246
+ unavailable: "serviceUnavailable",
247
+ session_required: "sessionRequired",
248
+ accessDenied: "accessDenied",
249
+ invalidRequest: "sdkUpdateRequired",
250
+ // typed codes
251
+ IDEMPOTENCY_KEY_IN_FLIGHT: "idempotencyInFlight",
252
+ IDEMPOTENCY_KEY_REUSED_DIFFERENT_REQUEST: "idempotencyConflict",
253
+ DAILY_QUOTA_EXCEEDED: "quotaExceeded",
254
+ TIER_UPGRADE_REQUIRED: "paymentRequired",
255
+ // SSE error frames
256
+ not_found: "conversationNotFound",
257
+ timeout: "streamTimeout",
258
+ internal_error: "internalError"
259
+ });
260
+ var CONTRACT_ERROR_ROWS = Object.freeze(
261
+ CONTRACT_RETRYABILITY.map(
262
+ (generated) => Object.freeze({
263
+ wireCode: generated.wireCode,
264
+ envelope: generated.envelope,
265
+ retryable: generated.retryable,
266
+ normalized: NORMALIZED_FOLD[generated.wireCode]
267
+ })
268
+ )
269
+ );
270
+ var BY_UPPER = new Map(
271
+ CONTRACT_ERROR_ROWS.map((r) => [r.wireCode.toUpperCase(), r])
272
+ );
273
+ function contractErrorFor(wireCode) {
274
+ if (typeof wireCode !== "string") return void 0;
275
+ const key = wireCode.trim().toUpperCase();
276
+ return key.length > 0 ? BY_UPPER.get(key) : void 0;
277
+ }
278
+ var CATEGORY_OF = Object.freeze({
279
+ // the caller's sign-in state is wrong and a credential change is the remedy
280
+ authExpired: "authentication",
281
+ authRejected: "authentication",
282
+ sessionRequired: "authentication",
283
+ // signed in, correctly identified, and still not allowed
284
+ accessDenied: "authorization",
285
+ // a plan gate, not a permission failure: the remedy is commercial
286
+ paymentRequired: "entitlement",
287
+ // slow down / come back later
288
+ quotaExceeded: "rateLimit",
289
+ rateLimited: "rateLimit",
290
+ // the request itself was wrong; retrying it unchanged can never succeed
291
+ validationFailed: "invalidRequest",
292
+ sdkUpdateRequired: "invalidRequest",
293
+ // the target is gone, hidden, or was never visible to this caller
294
+ conversationNotFound: "notFound",
295
+ petNotFound: "notFound",
296
+ resourceNotFound: "notFound",
297
+ // something else already holds the thing
298
+ conflict: "conflict",
299
+ idempotencyConflict: "conflict",
300
+ idempotencyInFlight: "conflict",
301
+ // the pipe, not the request: timeouts, drops, a briefly unreachable dependency
302
+ streamTimeout: "connection",
303
+ streamIncomplete: "connection",
304
+ upstreamLlmTimeout: "connection",
305
+ serviceUnavailable: "connection",
306
+ // the server admits fault
307
+ internalError: "server",
308
+ notImplemented: "server",
309
+ mediaUploadFailed: "media",
310
+ moderationBlocked: "policy",
311
+ unknown: "unknown"
312
+ });
313
+ function categoryFor(code) {
314
+ return CATEGORY_OF[code];
315
+ }
316
+ function fromWire(wire) {
317
+ const contractRow = contractErrorFor(wire);
318
+ if (contractRow) return contractRow.normalized;
319
+ const upper = (wire ?? "").trim().toUpperCase();
320
+ const canonical = upper.replace(/[^A-Z0-9]/g, "");
321
+ if (canonical === "AUTHREJECTED") return "authRejected";
322
+ if (upper.startsWith("AUTH")) return "authExpired";
323
+ switch (canonical) {
324
+ case "DAILYQUOTAEXCEEDED":
325
+ case "QUOTAEXCEEDED":
326
+ return "quotaExceeded";
327
+ case "RATELIMITED":
328
+ case "TOOMANYREQUESTS":
329
+ return "rateLimited";
330
+ case "IDEMPOTENCYKEYCONFLICT":
331
+ case "IDEMPOTENCYCONFLICT":
332
+ return "idempotencyConflict";
333
+ case "ACCESSDENIED":
334
+ case "FORBIDDEN":
335
+ return "accessDenied";
336
+ case "NOTFOUND":
337
+ case "CONVERSATIONNOTFOUND":
338
+ return "conversationNotFound";
339
+ case "PETNOTFOUND":
340
+ return "petNotFound";
341
+ case "TIMEOUT":
342
+ case "STREAMTIMEOUT":
343
+ return "streamTimeout";
344
+ // Analysis-domain deterministic 400s (NON-retryable). Additive per SPEC-00 §3.1 / SPEC-11b §2.6:
345
+ // fold to a NON-retried target so the SDK never retries a permanently-failing bad-input request.
346
+ // (Comment above the group so the empty fall-through cases stay lint-clean under no-fallthrough.)
347
+ case "MEDIAUPLOADFAILED":
348
+ case "UNRECOGNIZEDVIDEOFORMAT":
349
+ case "FILETOOSMALL":
350
+ return "mediaUploadFailed";
351
+ case "MODERATIONBLOCKED":
352
+ return "moderationBlocked";
353
+ case "UPSTREAMLLMTIMEOUT":
354
+ return "upstreamLlmTimeout";
355
+ case "INTERNALERROR":
356
+ case "INTERNALSERVERERROR":
357
+ return "internalError";
358
+ case "STREAMINCOMPLETE":
359
+ case "CHATSTREAMINCOMPLETE":
360
+ return "streamIncomplete";
361
+ // Deterministic 400s that can only come from an SDK bug -> unknown (NON-retryable). NEVER internalError
362
+ // (which IS auto-retried): mapping a bad-input 400 to a retryable code retries a request that never succeeds.
363
+ case "INVALIDANALYSISTYPE":
364
+ case "INVALIDUPLOADPURPOSE":
365
+ return "unknown";
366
+ default:
367
+ return "unknown";
368
+ }
369
+ }
370
+ var AUTO_RETRYABLE_CODES = /* @__PURE__ */ new Set([
371
+ "streamTimeout",
372
+ "rateLimited",
373
+ "internalError",
374
+ "upstreamLlmTimeout",
375
+ "streamIncomplete"
376
+ ]);
377
+ function isAutoRetryable(code) {
378
+ return AUTO_RETRYABLE_CODES.has(code);
379
+ }
380
+ var RETRYABLE_CONTRACT_CODES = /* @__PURE__ */ new Set([
381
+ "serviceUnavailable",
382
+ "conflict",
383
+ "idempotencyInFlight"
384
+ ]);
385
+ function isRetryableCode(code) {
386
+ return isAutoRetryable(code) || RETRYABLE_CONTRACT_CODES.has(code);
387
+ }
388
+ var BACKOFF_BASE_MS = 500;
389
+ var BACKOFF_CAP_MS = 8e3;
390
+ var MAX_RETRY_ATTEMPTS = 4;
391
+ function backoffDelayMs(attempt, rng = Math.random) {
392
+ const bounded = Math.max(0, attempt);
393
+ const ceiling = Math.min(BACKOFF_BASE_MS * 2 ** bounded, BACKOFF_CAP_MS);
394
+ return Math.floor(rng() * ceiling);
395
+ }
396
+
397
+ // src/client/errors/EverfurError.ts
398
+ var USER_FACING_COPY = Object.freeze({
399
+ authExpired: "Please sign in again to continue.",
400
+ authRejected: "Please sign in again to continue.",
401
+ sessionRequired: "This app needs to be updated to keep using Everfur.",
402
+ accessDenied: "This feature isn't available on your account right now.",
403
+ paymentRequired: "This is part of a paid plan.",
404
+ quotaExceeded: "You have used today's messages. This resets tomorrow.",
405
+ rateLimited: "You are sending messages quickly. Try again in a few seconds.",
406
+ validationFailed: "Something in that request was not right. Check the details and try again.",
407
+ sdkUpdateRequired: "This app needs to be updated to keep using Everfur.",
408
+ conflict: "That is already running. Wait for it to finish, then try again.",
409
+ idempotencyConflict: "That message was already delivered.",
410
+ idempotencyInFlight: "That is still processing. Give it a moment.",
411
+ conversationNotFound: "This conversation is no longer available.",
412
+ petNotFound: "We could not find that pet. Please pick a pet and try again.",
413
+ resourceNotFound: "We could not find that.",
414
+ streamTimeout: "The response timed out. Tap retry to try again.",
415
+ mediaUploadFailed: "We could not upload that photo. Please attach it again.",
416
+ moderationBlocked: "This request cannot be answered here.",
417
+ upstreamLlmTimeout: "The response timed out. Tap retry to try again.",
418
+ internalError: "We hit a snag on our end. Please try again.",
419
+ notImplemented: "That is not available yet.",
420
+ serviceUnavailable: "That service is briefly unavailable. Try again shortly.",
421
+ streamIncomplete: "The connection dropped mid-answer. Tap retry to continue.",
422
+ unknown: "Something went wrong. Please try again."
423
+ });
424
+ function userFacingError(code) {
425
+ return USER_FACING_COPY[code];
426
+ }
427
+ function defineHidden(target, key, value) {
428
+ Object.defineProperty(target, key, {
429
+ value,
430
+ enumerable: false,
431
+ writable: false,
432
+ configurable: false
433
+ });
434
+ }
435
+ function makeEverfurError(code, opts) {
436
+ contractErrorFor(opts?.wireCode);
437
+ const error = {
438
+ code,
439
+ category: categoryFor(code),
440
+ retryable: opts?.retryable ?? isRetryableCode(code),
441
+ displayMessage: userFacingError(code)
442
+ };
443
+ if (opts?.httpStatus !== void 0) error.httpStatus = opts.httpStatus;
444
+ if (opts?.requestId) error.requestId = opts.requestId;
445
+ if (opts?.wireMessage) defineHidden(error, "wireMessage", opts.wireMessage);
446
+ if (opts?.raw !== void 0 && opts.raw !== null) defineHidden(error, "raw", opts.raw);
447
+ return Object.freeze(error);
448
+ }
449
+
450
+ // src/client/identity.ts
451
+ function newSessionId() {
452
+ const bytes = new Uint8Array(16);
453
+ const cryptoObj = globalThis.crypto;
454
+ if (typeof cryptoObj?.getRandomValues === "function") {
455
+ cryptoObj.getRandomValues(bytes);
456
+ } else {
457
+ for (let i = 0; i < bytes.length; i += 1) bytes[i] = Math.floor(Math.random() * 256);
458
+ }
459
+ bytes[6] = bytes[6] & 15 | 64;
460
+ bytes[8] = bytes[8] & 63 | 128;
461
+ const hex = [];
462
+ for (let i = 0; i < bytes.length; i += 1) hex.push(bytes[i].toString(16).padStart(2, "0"));
463
+ 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("");
464
+ }
465
+ function authHeaders(auth) {
466
+ const headers = {};
467
+ if (auth.mode === "personalized") {
468
+ headers.authorization = `Bearer ${auth.token}`;
469
+ } else {
470
+ headers["x-everfur-partner-key"] = auth.publishableKey;
471
+ }
472
+ if (auth.userRef) headers["x-everfur-user-ref"] = auth.userRef;
473
+ if (auth.sessionId) headers["x-everfur-session-id"] = auth.sessionId;
474
+ return headers;
475
+ }
476
+ function withAuthHeaders(req, auth) {
477
+ return { ...req, headers: { ...stripAuthHeaders(req.headers), ...authHeaders(auth) } };
478
+ }
479
+ function stripAuthHeaders(headers) {
480
+ if (!headers) return {};
481
+ const out = {};
482
+ for (const [key, value] of Object.entries(headers)) {
483
+ const lower = key.toLowerCase();
484
+ if (lower === "authorization" || lower === "x-everfur-partner-key") continue;
485
+ out[key] = value;
486
+ }
487
+ return out;
488
+ }
489
+ async function authedSend(req, ctx) {
490
+ if (ctx.mode === "anonymous") {
491
+ return ctx.transport.request(
492
+ withAuthHeaders(req, {
493
+ mode: "anonymous",
494
+ publishableKey: ctx.publishableKey,
495
+ userRef: ctx.userRef,
496
+ ...ctx.sessionId ? { sessionId: ctx.sessionId } : {}
497
+ })
498
+ );
499
+ }
500
+ let token;
501
+ try {
502
+ token = await ctx.identity.currentToken();
503
+ } catch {
504
+ return err(authRejectedError());
505
+ }
506
+ const first = await ctx.transport.request(
507
+ withAuthHeaders(req, {
508
+ mode: "personalized",
509
+ token,
510
+ userRef: ctx.userRef,
511
+ ...ctx.sessionId ? { sessionId: ctx.sessionId } : {}
512
+ })
513
+ );
514
+ if (first.ok || first.error.httpStatus !== 401) return first;
515
+ let refreshed;
516
+ try {
517
+ refreshed = await ctx.identity.currentToken({ forceRefresh: true });
518
+ } catch {
519
+ return err(authRejectedError());
520
+ }
521
+ const retry = await ctx.transport.request(
522
+ withAuthHeaders(req, {
523
+ mode: "personalized",
524
+ token: refreshed,
525
+ userRef: ctx.userRef,
526
+ ...ctx.sessionId ? { sessionId: ctx.sessionId } : {}
527
+ })
528
+ );
529
+ if (!retry.ok && retry.error.httpStatus === 401) {
530
+ return err(authRejectedError(retry.error.httpStatus));
531
+ }
532
+ return retry;
533
+ }
534
+ function authRejectedError(httpStatus) {
535
+ return makeEverfurError("authRejected", {
536
+ retryable: false,
537
+ ...httpStatus !== void 0 ? { httpStatus } : {}
538
+ });
539
+ }
540
+
541
+ // src/client/transport.ts
542
+ function networkError(cause) {
543
+ return makeEverfurError("internalError", { retryable: true, wireMessage: describeCause(cause) });
544
+ }
545
+ function describeCause(cause) {
546
+ if (cause instanceof Error) return cause.message;
547
+ return typeof cause === "string" ? cause : "network request failed";
548
+ }
549
+
550
+ // src/client/funnel/requestFunnel.ts
551
+ var FUNNEL_UNARY_TIMEOUT_MS = 3e4;
552
+ var RETRY_OVERRIDE_MAX_MS = BACKOFF_CAP_MS * 2;
553
+ var IDEMPOTENCY_HEADER = "idempotency-key";
554
+ var MUTATING_METHODS = /* @__PURE__ */ new Set(["POST", "PUT", "PATCH", "DELETE"]);
555
+ var NOOP_OBSERVER = Object.freeze({
556
+ onEvent() {
557
+ }
558
+ });
559
+ var defaultFunnelTimers = Object.freeze({
560
+ setTimeout: (handler, ms) => setTimeout(handler, ms),
561
+ clearTimeout: (handle) => clearTimeout(handle),
562
+ now: () => Date.now()
563
+ });
564
+ function createRequestFunnel(deps) {
565
+ const observer = deps.observer ?? NOOP_OBSERVER;
566
+ const timers = deps.timers ?? defaultFunnelTimers;
567
+ const rng = deps.rng ?? Math.random;
568
+ const sleep = deps.sleep ?? ((ms, signal) => delayAbortable(ms, timers, signal));
569
+ const ceiling = deps.maxAttempts ?? MAX_RETRY_ATTEMPTS;
570
+ const timeoutMs = deps.unaryTimeoutMs ?? FUNNEL_UNARY_TIMEOUT_MS;
571
+ const mintKey = deps.newIdempotencyKey ?? defaultIdempotencyKeyFactory();
572
+ const emit = (event) => {
573
+ try {
574
+ observer.onEvent(event);
575
+ } catch {
576
+ }
577
+ };
578
+ async function send(call, req, opts) {
579
+ const perCallMaxAttempts = opts?.maxAttempts;
580
+ const maxAttempts = Math.max(1, perCallMaxAttempts ?? ceiling);
581
+ const idempotent = opts?.idempotent ?? MUTATING_METHODS.has(req.method);
582
+ const idempotencyKey = idempotent ? mintKey() : null;
583
+ const base = assembleHeaders(req, idempotencyKey);
584
+ let attempt = 0;
585
+ for (; ; ) {
586
+ const stamp = (extra) => Object.freeze({
587
+ call,
588
+ method: req.method,
589
+ path: req.path,
590
+ attempt,
591
+ ...idempotencyKey ? { idempotencyKey } : {},
592
+ ...extra
593
+ });
594
+ emit(stamp({ phase: "attempt" }));
595
+ const deadline = boundedSignal(timeoutMs, timers);
596
+ const merged = mergeSignals(deadline.signal, req.signal);
597
+ let settled;
598
+ try {
599
+ settled = await authedSend({ ...base, signal: merged.signal }, deps.auth);
600
+ } catch (cause) {
601
+ settled = err(networkError(cause));
602
+ } finally {
603
+ merged.dispose();
604
+ deadline.cancel();
605
+ }
606
+ if (settled.ok) {
607
+ emit(stamp({ phase: "settled", ok: true, reason: "ok" }));
608
+ return settled;
609
+ }
610
+ const error = settled.error;
611
+ const decision = decideRetry(error, attempt, {
612
+ maxAttempts,
613
+ rng,
614
+ now: timers.now(),
615
+ aborted: req.signal?.aborted === true,
616
+ ...perCallMaxAttempts !== void 0 ? { perCallMaxAttempts } : {},
617
+ ...deps.errorPolicy !== void 0 ? { policy: deps.errorPolicy } : {}
618
+ });
619
+ const settledEvent = {
620
+ ok: false,
621
+ code: error.code,
622
+ reason: decision.reason,
623
+ ...error.httpStatus !== void 0 ? { httpStatus: error.httpStatus } : {},
624
+ ...error.requestId !== void 0 ? { requestId: error.requestId } : {}
625
+ };
626
+ if (!decision.retry) {
627
+ emit(stamp({ phase: "settled", ...settledEvent }));
628
+ return err(error);
629
+ }
630
+ emit(stamp({ phase: "retry", ...settledEvent, delayMs: decision.delayMs }));
631
+ await sleep(decision.delayMs, req.signal);
632
+ if (req.signal?.aborted === true) {
633
+ emit(stamp({ phase: "settled", ...settledEvent, reason: "aborted" }));
634
+ return err(error);
635
+ }
636
+ attempt += 1;
637
+ }
638
+ }
639
+ async function authorize(req) {
640
+ return withAuthHeaders(req, await resolveDeviceAuth(deps.auth));
641
+ }
642
+ async function* stream(call, req, signal) {
643
+ emit(
644
+ Object.freeze({
645
+ call,
646
+ phase: "stream.open",
647
+ method: req.method,
648
+ path: req.path,
649
+ attempt: 0
650
+ })
651
+ );
652
+ try {
653
+ yield* deps.auth.transport.stream(req, signal);
654
+ } catch {
655
+ yield errorFrame({
656
+ // The same wire spelling sse.ts synthesizes, so `fromWire` folds it to the retryable `internalError`
657
+ // like any other transport failure. wireMessage stays null: it is the SERVER's text, and a thrown
658
+ // host exception's `.message` is not that.
659
+ code: "internal_error",
660
+ retryable: true,
661
+ wireMessage: null,
662
+ synthesized: true,
663
+ lastEventId: null});
664
+ }
665
+ }
666
+ return Object.freeze({ send, authorize, stream });
667
+ }
668
+ function assembleHeaders(req, idempotencyKey) {
669
+ const headers = {};
670
+ for (const [key, value] of Object.entries(req.headers ?? {})) {
671
+ if (key.toLowerCase() === IDEMPOTENCY_HEADER) continue;
672
+ headers[key] = value;
673
+ }
674
+ if (idempotencyKey !== null) headers["Idempotency-Key"] = idempotencyKey;
675
+ return { ...req, headers };
676
+ }
677
+ function defaultIdempotencyKeyFactory() {
678
+ let counter = 0;
679
+ return () => `efk_${Date.now().toString(36)}_${(counter++).toString(36)}_${Math.random().toString(36).slice(2, 12)}`;
680
+ }
681
+ var POLICY_MAX_ATTEMPTS_CAP = 10;
682
+ function decideRetry(error, attempt, ctx) {
683
+ if (ctx.aborted) return { retry: false, reason: "aborted" };
684
+ const throttle = throttleKind(error);
685
+ if (throttle === "quota") {
686
+ return { retry: false, reason: "daily-quota-exhausted" };
687
+ }
688
+ if (throttle !== "burst" && !isAutoRetryable(error.code)) {
689
+ return { retry: false, reason: "terminal-code" };
690
+ }
691
+ const reason = throttle === "burst" ? "burst-throttle" : "retryable-code";
692
+ const policyVetoedRetry = () => {
693
+ if (ctx.policy === void 0) return false;
694
+ try {
695
+ return !ctx.policy.shouldRetry(error.code, attempt);
696
+ } catch {
697
+ return false;
698
+ }
699
+ };
700
+ if (policyVetoedRetry()) return { retry: false, reason: "terminal-code" };
701
+ const policyCeiling = () => {
702
+ if (ctx.policy === void 0) return null;
703
+ let raw;
704
+ try {
705
+ raw = ctx.policy.maxAttempts(error.code);
706
+ } catch {
707
+ return null;
708
+ }
709
+ if (typeof raw !== "number" || !Number.isFinite(raw)) return null;
710
+ return Math.max(1, Math.min(POLICY_MAX_ATTEMPTS_CAP, Math.floor(raw)));
711
+ };
712
+ const ceiling = ctx.perCallMaxAttempts ?? policyCeiling() ?? ctx.maxAttempts;
713
+ if (attempt + 1 >= ceiling) return { retry: false, reason: "attempts-exhausted" };
714
+ const override = retryOverrideMs(error, ctx.now);
715
+ if (override !== null) {
716
+ if (override > RETRY_OVERRIDE_MAX_MS) {
717
+ return { retry: false, reason: "server-reset-beyond-budget" };
718
+ }
719
+ return { retry: true, reason, delayMs: override };
720
+ }
721
+ return { retry: true, reason, delayMs: backoffDelayMs(attempt, ctx.rng) };
722
+ }
723
+ function throttleKind(error) {
724
+ const code = error.code === "unknown" ? fromWire(rawWireCode(error.raw)) : error.code;
725
+ if (code === "quotaExceeded") return "quota";
726
+ if (code === "rateLimited") return "burst";
727
+ if (error.httpStatus === 429) {
728
+ return "burst";
729
+ }
730
+ return null;
731
+ }
732
+ function retryOverrideMs(error, now) {
733
+ const at = findResetsAt(error.raw);
734
+ if (at === null) return null;
735
+ const delta = at - now;
736
+ return delta > 0 ? delta : 0;
737
+ }
738
+ function findResetsAt(raw) {
739
+ for (const scope of candidateScopes(raw)) {
740
+ const value = scope["resets_at"];
741
+ const parsed = parseInstantMs(value);
742
+ if (parsed !== null) return parsed;
743
+ }
744
+ return null;
745
+ }
746
+ function candidateScopes(raw) {
747
+ if (!isRecord(raw)) return [];
748
+ const out = [raw];
749
+ for (const nested of ["error", "detail"]) {
750
+ const value = raw[nested];
751
+ if (isRecord(value)) out.push(value);
752
+ }
753
+ return out;
754
+ }
755
+ function parseInstantMs(value) {
756
+ if (typeof value === "number" && Number.isFinite(value)) {
757
+ return value < 1e11 ? Math.round(value * 1e3) : Math.round(value);
758
+ }
759
+ if (typeof value === "string" && value.trim().length > 0) {
760
+ const parsed = Date.parse(value);
761
+ return Number.isFinite(parsed) ? parsed : null;
762
+ }
763
+ return null;
764
+ }
765
+ function rawWireCode(raw) {
766
+ for (const scope of candidateScopes(raw)) {
767
+ const code = scope["code"];
768
+ if (typeof code === "string" && code.length > 0) return code;
769
+ }
770
+ return null;
771
+ }
772
+ function isRecord(value) {
773
+ return typeof value === "object" && value !== null;
774
+ }
775
+ async function resolveDeviceAuth(auth) {
776
+ if (auth.mode === "anonymous") {
777
+ return {
778
+ mode: "anonymous",
779
+ publishableKey: auth.publishableKey,
780
+ userRef: auth.userRef,
781
+ ...auth.sessionId ? { sessionId: auth.sessionId } : {}
782
+ };
783
+ }
784
+ return {
785
+ mode: "personalized",
786
+ token: await auth.identity.currentToken(),
787
+ userRef: auth.userRef,
788
+ ...auth.sessionId ? { sessionId: auth.sessionId } : {}
789
+ };
790
+ }
791
+ function boundedSignal(ms, timers) {
792
+ const ctrl = new AbortController();
793
+ const handle = timers.setTimeout(() => ctrl.abort(), ms);
794
+ return { signal: ctrl.signal, cancel: () => timers.clearTimeout(handle) };
795
+ }
796
+ function mergeSignals(deadline, caller) {
797
+ const noop = () => void 0;
798
+ if (!caller) return { signal: deadline, dispose: noop };
799
+ const ctrl = new AbortController();
800
+ if (deadline.aborted || caller.aborted) {
801
+ ctrl.abort();
802
+ return { signal: ctrl.signal, dispose: noop };
803
+ }
804
+ const onAbort = () => ctrl.abort();
805
+ deadline.addEventListener("abort", onAbort, { once: true });
806
+ caller.addEventListener("abort", onAbort, { once: true });
807
+ return {
808
+ signal: ctrl.signal,
809
+ dispose: () => {
810
+ deadline.removeEventListener("abort", onAbort);
811
+ caller.removeEventListener("abort", onAbort);
812
+ }
813
+ };
814
+ }
815
+ function delayAbortable(ms, timers, signal) {
816
+ if (ms <= 0 || signal?.aborted === true) return Promise.resolve();
817
+ return new Promise((resolve) => {
818
+ const handle = timers.setTimeout(() => {
819
+ signal?.removeEventListener("abort", onAbort);
820
+ resolve();
821
+ }, ms);
822
+ const onAbort = () => {
823
+ timers.clearTimeout(handle);
824
+ resolve();
825
+ };
826
+ signal?.addEventListener("abort", onAbort, { once: true });
827
+ });
828
+ }
829
+
830
+ // src/client/text.ts
831
+ function hasLoneSurrogate(value) {
832
+ for (let i = 0; i < value.length; i += 1) {
833
+ const code = value.charCodeAt(i);
834
+ if (code >= 55296 && code <= 56319) {
835
+ const low = value.charCodeAt(i + 1);
836
+ if (!(low >= 56320 && low <= 57343)) return true;
837
+ i += 1;
838
+ } else if (code >= 56320 && code <= 57343) {
839
+ return true;
840
+ }
841
+ }
842
+ return false;
843
+ }
844
+
845
+ // src/client/entitlements/resolve.ts
846
+ var REQUIRES = Object.freeze({
847
+ chat: Object.freeze(["chat.message.create"]),
848
+ records: Object.freeze(["records.upload.create", "records.record.read"]),
849
+ video: Object.freeze(["video.gait.execute"]),
850
+ photo: Object.freeze(["photo.checkup.execute"]),
851
+ animations: Object.freeze(["animations.state.read"])
852
+ });
853
+ function requires(name) {
854
+ return REQUIRES[name];
855
+ }
856
+ function decideCapability(name, decisions, opts) {
857
+ if (opts?.isPending === true) {
858
+ return freezeDecision({ name, enabled: false, isPending: true, limits: {} });
859
+ }
860
+ const keys = requires(name);
861
+ const byResource = /* @__PURE__ */ new Map();
862
+ for (const decision of decisions) byResource.set(decision.resource, decision);
863
+ const limits = mergeLimits(keys, byResource);
864
+ const missing = keys.filter((key) => byResource.get(key)?.granted !== true);
865
+ if (missing.length === 0) {
866
+ return freezeDecision({ name, enabled: true, isPending: false, limits });
867
+ }
868
+ return freezeDecision({
869
+ name,
870
+ enabled: false,
871
+ isPending: false,
872
+ limits,
873
+ disabled: disabledFor(keys, byResource)
874
+ });
875
+ }
876
+ function mergeLimits(keys, byResource) {
877
+ const out = {};
878
+ for (const key of keys) {
879
+ const decisionLimits = byResource.get(key)?.limits;
880
+ if (!decisionLimits) continue;
881
+ for (const [limitKey, limitValue] of Object.entries(decisionLimits)) {
882
+ const existing = out[limitKey];
883
+ out[limitKey] = existing === void 0 ? limitValue : Math.min(existing, limitValue);
884
+ }
885
+ }
886
+ return out;
887
+ }
888
+ function disabledFor(keys, byResource) {
889
+ for (const key of keys) {
890
+ const explicit = byResource.get(key)?.disabled;
891
+ if (explicit) {
892
+ return Object.freeze({
893
+ reason: explicit.reason,
894
+ level: explicit.level,
895
+ recoverable: explicit.recoverable
896
+ });
897
+ }
898
+ }
899
+ return Object.freeze({
900
+ reason: userFacingError("accessDenied"),
901
+ level: "user_entitlement",
902
+ recoverable: false
903
+ });
904
+ }
905
+ function freezeDecision(d) {
906
+ const base = {
907
+ name: d.name,
908
+ enabled: d.enabled,
909
+ isPending: d.isPending,
910
+ limits: Object.freeze({ ...d.limits })
911
+ };
912
+ if (d.disabled !== void 0) base.disabled = d.disabled;
913
+ return Object.freeze(base);
914
+ }
915
+
916
+ // src/rn/facade.ts
917
+ var EVERFUR_CONTEXT_SYMBOL = /* @__PURE__ */ Symbol.for("@everfur/sdk#EverfurContext@v1");
918
+ var globalContextHost = globalThis;
919
+ var EverfurContext = globalContextHost[EVERFUR_CONTEXT_SYMBOL] ?? (globalContextHost[EVERFUR_CONTEXT_SYMBOL] = createContext(null));
920
+ EverfurContext.displayName ??= "EverfurContext";
921
+ function useEverfurContext() {
922
+ const ctx = useContext(EverfurContext);
923
+ if (ctx === null) {
924
+ throw new EverfurConfigError(
925
+ "not-initialized",
926
+ "Everfur hooks must be called inside <EverfurProvider>. Wrap your tree once, high."
927
+ );
928
+ }
929
+ return ctx;
930
+ }
931
+ var EVERFUR_THEME_CONTEXT_SYMBOL = /* @__PURE__ */ Symbol.for("@everfur/sdk#EverfurThemeContext@v1");
932
+ var globalThemeHost = globalThis;
933
+ var EverfurThemeContext = globalThemeHost[EVERFUR_THEME_CONTEXT_SYMBOL] ?? (globalThemeHost[EVERFUR_THEME_CONTEXT_SYMBOL] = createContext(EVERFUR_LIGHT));
934
+ EverfurThemeContext.displayName ??= "EverfurThemeContext";
935
+ function useEverfurTheme() {
936
+ return useContext(EverfurThemeContext);
937
+ }
938
+ function useCapability(name) {
939
+ const { runtime } = useEverfurContext();
940
+ const store = runtime.entitlements;
941
+ const snapshot = useSyncExternalStore(
942
+ store.subscribe,
943
+ store.getSnapshot,
944
+ store.getSnapshot
945
+ );
946
+ return useMemo(
947
+ () => decideCapability(name, snapshot.decisions, { isPending: snapshot.isPending }),
948
+ [name, snapshot]
949
+ );
950
+ }
951
+ var MIN_OFFSTATE_HEIGHT = 48;
952
+ function selectView(decision) {
953
+ if (decision.isPending) return "pending";
954
+ return decision.enabled ? "enabled" : "disabled";
955
+ }
956
+ function CapabilityGate(props) {
957
+ const { capability, children, renderDisabled, renderPending, style } = props;
958
+ const decision = useCapability(capability);
959
+ const view = useMemo(() => selectView(decision), [decision]);
960
+ switch (view) {
961
+ case "enabled":
962
+ return children;
963
+ case "pending":
964
+ return renderPending ? renderPending() : /* @__PURE__ */ jsx(PendingSkeleton, { capability, style });
965
+ case "disabled":
966
+ return renderDisabled ? renderDisabled(decision) : /* @__PURE__ */ jsx(OffState, { decision, style });
967
+ default:
968
+ return assertNever(view);
969
+ }
970
+ }
971
+ function PendingSkeleton({
972
+ capability,
973
+ style
974
+ }) {
975
+ const theme = useEverfurTheme();
976
+ const styles = useMemo(() => makeStyles(theme), [theme]);
977
+ return /* @__PURE__ */ jsx(
978
+ View,
979
+ {
980
+ style: [styles.offstate, style],
981
+ accessible: true,
982
+ accessibilityState: { busy: true },
983
+ accessibilityLabel: `Loading ${capability}`,
984
+ children: /* @__PURE__ */ jsx(View, { style: styles.skeletonBar })
985
+ }
986
+ );
987
+ }
988
+ function OffState({
989
+ decision,
990
+ style
991
+ }) {
992
+ const theme = useEverfurTheme();
993
+ const styles = useMemo(() => makeStyles(theme), [theme]);
994
+ const message = decision.disabled?.reason ?? "";
995
+ return /* @__PURE__ */ jsx(
996
+ View,
997
+ {
998
+ style: [styles.offstate, style],
999
+ accessible: true,
1000
+ accessibilityRole: "text",
1001
+ accessibilityLabel: message,
1002
+ children: message.length > 0 ? /* @__PURE__ */ jsx(Text, { style: styles.offstateText, children: message }) : null
1003
+ }
1004
+ );
1005
+ }
1006
+ function makeStyles(theme) {
1007
+ const { color, space, radius, type } = theme;
1008
+ return StyleSheet.create({
1009
+ // A deliberate cream card with a soft brand hairline, never a bare grey slab.
1010
+ offstate: {
1011
+ minHeight: MIN_OFFSTATE_HEIGHT,
1012
+ justifyContent: "center",
1013
+ paddingHorizontal: space.lg,
1014
+ paddingVertical: space.md,
1015
+ backgroundColor: color.surfaceCream,
1016
+ borderRadius: radius.md,
1017
+ borderWidth: StyleSheet.hairlineWidth,
1018
+ borderColor: color.brandBorder
1019
+ },
1020
+ offstateText: {
1021
+ fontFamily: type.family,
1022
+ fontSize: type.size.body,
1023
+ lineHeight: Math.round(type.size.body * type.lineHeight.normal),
1024
+ color: color.text.muted
1025
+ },
1026
+ // A soft green shimmer bar (brand wash) that stays legible on the cream card in both light and dark,
1027
+ // where the neutral `skeleton` token would collide with the dark cream surface.
1028
+ skeletonBar: {
1029
+ height: space.md,
1030
+ borderRadius: radius.xs,
1031
+ backgroundColor: color.brandSofter
1032
+ }
1033
+ });
1034
+ }
1035
+
1036
+ // src/client/animations/types.ts
1037
+ function mapTier(wire) {
1038
+ const tier = {
1039
+ url: wire.url,
1040
+ kind: wire.kind,
1041
+ expiresAt: wire.expires_at
1042
+ };
1043
+ if (typeof wire.loop_duration_ms === "number") tier.loopDurationMs = wire.loop_duration_ms;
1044
+ if (typeof wire.cache_key === "string" && wire.cache_key.length > 0) tier.cacheKey = wire.cache_key;
1045
+ return Object.freeze(tier);
1046
+ }
1047
+ function mapPetStateResponse(wire) {
1048
+ const tiers = {};
1049
+ if (wire.tiers.animation) tiers.animation = mapTier(wire.tiers.animation);
1050
+ if (wire.tiers.image) tiers.image = mapTier(wire.tiers.image);
1051
+ const overlays = {};
1052
+ if (wire.overlays.weather_alert) overlays.weatherAlert = mapTier(wire.overlays.weather_alert);
1053
+ const response = {
1054
+ category: wire.category,
1055
+ tiers: Object.freeze(tiers),
1056
+ overlays: Object.freeze(overlays),
1057
+ idle: "bundled",
1058
+ ttlSeconds: wire.ttl_seconds,
1059
+ degraded: wire.degraded
1060
+ };
1061
+ if (typeof wire.cache_epoch === "number") response.cacheEpoch = wire.cache_epoch;
1062
+ return Object.freeze(response);
1063
+ }
1064
+ var mediaKindWireSchema = z.enum(["webp", "video"]);
1065
+ var categoryWireSchema = z.enum(["health", "attention", "moment", "activity", "mood", "idle"]);
1066
+ var petStateTierWireSchema = z.object({
1067
+ url: z.string(),
1068
+ kind: mediaKindWireSchema.default("webp"),
1069
+ loop_duration_ms: z.number().nullish(),
1070
+ expires_at: z.string(),
1071
+ // SERVER-OWNED identity `{s3_key}@r{asset_revision}`; absent on an older backend (defaults to the
1072
+ // presign-stripped path downstream). Never derived from `url`.
1073
+ cache_key: z.string().nullish()
1074
+ });
1075
+ var petStateResponseWireSchema = z.object({
1076
+ category: categoryWireSchema,
1077
+ tiers: z.object({
1078
+ animation: petStateTierWireSchema.optional(),
1079
+ image: petStateTierWireSchema.optional()
1080
+ }).default({}),
1081
+ overlays: z.object({
1082
+ weather_alert: petStateTierWireSchema.optional()
1083
+ }).default({}),
1084
+ idle: z.literal("bundled").default("bundled"),
1085
+ ttl_seconds: z.number(),
1086
+ // TRANSIENT server idle (derive timeout / shed / IAM drift), NOT a dark pet.
1087
+ degraded: z.boolean().default(false),
1088
+ // Monotonic fleet-wide purge counter; 0 / absent == never purged.
1089
+ cache_epoch: z.number().default(0)
1090
+ });
1091
+ function parsePetStateWire(raw) {
1092
+ const parsed = petStateResponseWireSchema.safeParse(raw);
1093
+ return parsed.success ? parsed.data : null;
1094
+ }
1095
+
1096
+ // src/client/animations/petStateRepository.ts
1097
+ function createPetStateRepository(auth) {
1098
+ return createPetStateRepositoryOver(createRequestFunnel({ auth }));
1099
+ }
1100
+ function createPetStateRepositoryOver(funnel) {
1101
+ return {
1102
+ async getState(petRef, opts) {
1103
+ if (hasLoneSurrogate(petRef)) {
1104
+ return err(
1105
+ makeEverfurError("validationFailed", {
1106
+ retryable: false,
1107
+ wireMessage: "pet_ref contains an unpaired surrogate and cannot be encoded"
1108
+ })
1109
+ );
1110
+ }
1111
+ const path = `/widget/v1/pets/${encodeURIComponent(petRef)}/state`;
1112
+ const res = await funnel.send(
1113
+ "animations.getState",
1114
+ opts?.signal ? { method: "GET", path, signal: opts.signal } : { method: "GET", path }
1115
+ );
1116
+ if (res.ok) {
1117
+ const wire = parsePetStateWire(res.value);
1118
+ if (wire === null) {
1119
+ return err(makeEverfurError("internalError", { retryable: true }));
1120
+ }
1121
+ return ok(mapPetStateResponse(wire));
1122
+ }
1123
+ if (res.error.httpStatus === 404) return ok(null);
1124
+ return err(res.error);
1125
+ }
1126
+ };
1127
+ }
1128
+
1129
+ // src/client/animations/tier.ts
1130
+ function stableMediaKey(source) {
1131
+ if (source === void 0) return "bundled:none";
1132
+ if (typeof source === "number") return `bundled:${source}`;
1133
+ if ("kind" in source) return `bundled:${source.id}`;
1134
+ const uri = source.uri;
1135
+ const q = uri.indexOf("?");
1136
+ return q === -1 ? uri : uri.slice(0, q);
1137
+ }
1138
+ function selectTier(i) {
1139
+ if (i.hasPhoto && !i.photoFailed) return "photo";
1140
+ if (i.canAnimate && !i.animationFailed) return "animation";
1141
+ if (i.hasImage && !i.imageFailed) return "image";
1142
+ return "idle";
1143
+ }
1144
+ function retireTier(current, failed) {
1145
+ switch (current) {
1146
+ case "photo":
1147
+ return { failed: freezeFailed({ ...failed, photo: true }), reason: "network_error" };
1148
+ case "animation":
1149
+ return { failed: freezeFailed({ ...failed, animation: true }), reason: "network_error" };
1150
+ case "image":
1151
+ return { failed: freezeFailed({ ...failed, image: true }), reason: "network_error" };
1152
+ case "idle":
1153
+ return { failed: freezeFailed(failed), reason: "idle_asset_failed" };
1154
+ default:
1155
+ return { failed: freezeFailed(failed), reason: "network_error" };
1156
+ }
1157
+ }
1158
+ var NO_FAILURES = Object.freeze({ photo: false, animation: false, image: false });
1159
+ function freezeFailed(f) {
1160
+ return Object.freeze({ photo: f.photo, animation: f.animation, image: f.image });
1161
+ }
1162
+ function isLoaderSafeCategory(category) {
1163
+ switch (category) {
1164
+ case "activity":
1165
+ case "mood":
1166
+ case "moment":
1167
+ case "idle":
1168
+ return true;
1169
+ case "health":
1170
+ case "attention":
1171
+ return false;
1172
+ default:
1173
+ return false;
1174
+ }
1175
+ }
1176
+
1177
+ // src/core/animations/cacheEpoch.ts
1178
+ var CACHE_EPOCH_STORAGE_KEY = "everfur.petState.cacheEpoch";
1179
+ function createCacheEpochGuard(deps) {
1180
+ let lastActed = 0;
1181
+ let loaded = false;
1182
+ let inFlight = null;
1183
+ const run = async (serverEpoch) => {
1184
+ if (!loaded) {
1185
+ lastActed = await readStoredEpoch(deps.kv);
1186
+ loaded = true;
1187
+ }
1188
+ if (serverEpoch <= lastActed) return false;
1189
+ try {
1190
+ await deps.kv.setItem(CACHE_EPOCH_STORAGE_KEY, String(serverEpoch));
1191
+ } catch {
1192
+ }
1193
+ lastActed = serverEpoch;
1194
+ try {
1195
+ await deps.cache.clearMemoryCache();
1196
+ } catch {
1197
+ }
1198
+ try {
1199
+ await deps.cache.clearDiskCache();
1200
+ } catch {
1201
+ }
1202
+ return true;
1203
+ };
1204
+ return {
1205
+ async sync(serverEpoch) {
1206
+ if (typeof serverEpoch !== "number" || !Number.isFinite(serverEpoch) || serverEpoch <= 0) {
1207
+ return false;
1208
+ }
1209
+ if (loaded && serverEpoch <= lastActed) return false;
1210
+ if (inFlight) return inFlight;
1211
+ inFlight = run(serverEpoch).finally(() => {
1212
+ inFlight = null;
1213
+ });
1214
+ return inFlight;
1215
+ }
1216
+ };
1217
+ }
1218
+ async function readStoredEpoch(kv) {
1219
+ let raw;
1220
+ try {
1221
+ raw = await kv.getItem(CACHE_EPOCH_STORAGE_KEY);
1222
+ } catch {
1223
+ return 0;
1224
+ }
1225
+ if (raw === null) return 0;
1226
+ const parsed = Number(raw);
1227
+ return Number.isFinite(parsed) && parsed > 0 ? parsed : 0;
1228
+ }
1229
+ var SUPPORTED_SCHEMA_VERSION = 1;
1230
+ var MANIFEST_LKG_STORAGE_KEY = "everfur.manifest.lastKnownGood";
1231
+ var COMPILED_DEFAULT_IDLE = Object.freeze({ kind: "bundled", id: "everfur-idle" });
1232
+ var COMPILED_DEFAULT_MANIFEST = Object.freeze({
1233
+ schemaVersion: SUPPORTED_SCHEMA_VERSION,
1234
+ revision: "compiled-default",
1235
+ surfaces: Object.freeze({
1236
+ animations: Object.freeze({ enabled: true, idle: COMPILED_DEFAULT_IDLE })
1237
+ })
1238
+ });
1239
+ var bundledIdleSchema = z.object({ kind: z.literal("bundled"), id: z.string().min(1) });
1240
+ var animationsSurfaceWireSchema = z.object({
1241
+ enabled: z.boolean().default(true),
1242
+ idle: bundledIdleSchema.optional()
1243
+ });
1244
+ var manifestWireSchema = z.object({
1245
+ schema_version: z.number().int(),
1246
+ revision: z.string().default(""),
1247
+ surfaces: z.object({ animations: animationsSurfaceWireSchema.optional() }).default({})
1248
+ });
1249
+ function parseManifest(raw) {
1250
+ const parsed = manifestWireSchema.safeParse(raw);
1251
+ if (!parsed.success) return { ok: false, reason: "unparseable" };
1252
+ if (parsed.data.schema_version > SUPPORTED_SCHEMA_VERSION) {
1253
+ return { ok: false, reason: "newer_schema" };
1254
+ }
1255
+ const animationsWire = parsed.data.surfaces.animations;
1256
+ const surfaces = {};
1257
+ if (animationsWire) {
1258
+ surfaces.animations = Object.freeze({
1259
+ enabled: animationsWire.enabled,
1260
+ idle: animationsWire.idle ? Object.freeze({ ...animationsWire.idle }) : COMPILED_DEFAULT_IDLE
1261
+ });
1262
+ }
1263
+ return {
1264
+ ok: true,
1265
+ manifest: Object.freeze({
1266
+ schemaVersion: parsed.data.schema_version,
1267
+ revision: parsed.data.revision,
1268
+ surfaces: Object.freeze(surfaces)
1269
+ })
1270
+ };
1271
+ }
1272
+ async function resolveManifest(liveRaw, kv, tel) {
1273
+ if (liveRaw !== null && liveRaw !== void 0) {
1274
+ const parsed = parseManifest(liveRaw);
1275
+ if (parsed.ok) {
1276
+ await writeLastKnownGood(kv, liveRaw);
1277
+ tel.track("manifest.fallback", { source: "live" });
1278
+ return Object.freeze({ manifest: parsed.manifest, source: "live" });
1279
+ }
1280
+ if (parsed.reason === "newer_schema") tel.track("manifest.refused_newer", {});
1281
+ }
1282
+ const lkg = await readLastKnownGood(kv);
1283
+ if (lkg) {
1284
+ tel.track("manifest.fallback", { source: "last-known-good" });
1285
+ return Object.freeze({ manifest: lkg, source: "last-known-good" });
1286
+ }
1287
+ tel.track("manifest.fallback", { source: "compiled-default" });
1288
+ return Object.freeze({ manifest: COMPILED_DEFAULT_MANIFEST, source: "compiled-default" });
1289
+ }
1290
+ function animationsSurfaceOf(manifest) {
1291
+ return manifest.surfaces.animations ?? COMPILED_DEFAULT_MANIFEST.surfaces.animations ?? {
1292
+ enabled: true,
1293
+ idle: COMPILED_DEFAULT_IDLE
1294
+ };
1295
+ }
1296
+ async function writeLastKnownGood(kv, raw) {
1297
+ try {
1298
+ await kv.setItem(MANIFEST_LKG_STORAGE_KEY, JSON.stringify(raw));
1299
+ } catch {
1300
+ }
1301
+ }
1302
+ async function readLastKnownGood(kv) {
1303
+ let stored;
1304
+ try {
1305
+ stored = await kv.getItem(MANIFEST_LKG_STORAGE_KEY);
1306
+ } catch {
1307
+ return null;
1308
+ }
1309
+ if (stored === null) return null;
1310
+ let json;
1311
+ try {
1312
+ json = JSON.parse(stored);
1313
+ } catch {
1314
+ return null;
1315
+ }
1316
+ const parsed = parseManifest(json);
1317
+ return parsed.ok ? parsed.manifest : null;
1318
+ }
1319
+
1320
+ // src/core/animations/petStateStore.ts
1321
+ var DEFAULT_STALE_MS = 6e4;
1322
+ var MAX_TRANSIENT_RETRIES = 2;
1323
+ var MAX_WARM_ENTRIES = 32;
1324
+ var EMPTY_SNAPSHOT = Object.freeze({
1325
+ data: null,
1326
+ isPending: false,
1327
+ isError: false,
1328
+ error: null,
1329
+ isDark: false
1330
+ });
1331
+ function createPetStateStore(deps) {
1332
+ const { repo, cacheEpoch, timers } = deps;
1333
+ const listeners = /* @__PURE__ */ new Set();
1334
+ const warm = /* @__PURE__ */ new Map();
1335
+ let snapshot = EMPTY_SNAPSHOT;
1336
+ let currentPetRef = null;
1337
+ let dataPetRef = null;
1338
+ let isFocused = false;
1339
+ let terminatedPetRef = null;
1340
+ let remintHandle = null;
1341
+ let inFlight = null;
1342
+ let epoch = 0;
1343
+ const emit = () => {
1344
+ for (const listener of listeners) listener();
1345
+ };
1346
+ const patch = (partial) => {
1347
+ snapshot = Object.freeze({ ...snapshot, ...partial });
1348
+ emit();
1349
+ };
1350
+ const clearRemint = () => {
1351
+ if (remintHandle !== null) {
1352
+ timers.clearTimeout(remintHandle);
1353
+ remintHandle = null;
1354
+ }
1355
+ };
1356
+ const staleMs = (data) => data ? Math.max(1, data.ttlSeconds) * 1e3 : DEFAULT_STALE_MS;
1357
+ const touchWarm = (petRef) => {
1358
+ const entry = warm.get(petRef);
1359
+ if (entry === void 0) return;
1360
+ warm.delete(petRef);
1361
+ warm.set(petRef, entry);
1362
+ };
1363
+ const setWarm = (petRef, data) => {
1364
+ warm.delete(petRef);
1365
+ warm.set(petRef, Object.freeze({ data, fetchedAt: timers.now() }));
1366
+ while (warm.size > MAX_WARM_ENTRIES) {
1367
+ const oldest = warm.keys().next().value;
1368
+ if (oldest === void 0 || oldest === petRef) break;
1369
+ warm.delete(oldest);
1370
+ }
1371
+ };
1372
+ const hasGoodTiers = (petRef) => {
1373
+ const entry = warm.get(petRef);
1374
+ if (!entry) return false;
1375
+ return Boolean(entry.data.tiers.animation || entry.data.tiers.image);
1376
+ };
1377
+ const scheduleRemint = (petRef, ttlSeconds) => {
1378
+ clearRemint();
1379
+ if (!isFocused) return;
1380
+ const ms = Math.max(1, ttlSeconds) * 1e3;
1381
+ const scheduledEpoch = epoch;
1382
+ remintHandle = timers.setTimeout(() => {
1383
+ remintHandle = null;
1384
+ if (scheduledEpoch !== epoch || currentPetRef !== petRef || !isFocused) return;
1385
+ void fetchOnce(petRef, 0);
1386
+ }, ms);
1387
+ };
1388
+ const fetchOnce = async (petRef, attempt) => {
1389
+ if (currentPetRef !== petRef || terminatedPetRef === petRef || !isFocused) return;
1390
+ const myEpoch = epoch;
1391
+ inFlight?.abort();
1392
+ const ctrl = new AbortController();
1393
+ inFlight = ctrl;
1394
+ const res = await repo.getState(petRef, { signal: ctrl.signal });
1395
+ if (myEpoch !== epoch || currentPetRef !== petRef) return;
1396
+ if (res.ok) {
1397
+ const resp = res.value;
1398
+ if (resp === null) {
1399
+ onTerminalDark(petRef);
1400
+ return;
1401
+ }
1402
+ void cacheEpoch.sync(resp.cacheEpoch);
1403
+ const respHasTiers = Boolean(resp.tiers.animation || resp.tiers.image);
1404
+ if (resp.degraded && !respHasTiers && hasGoodTiers(petRef)) {
1405
+ patch({ isError: false, error: null, isPending: false, isDark: false });
1406
+ scheduleRemint(petRef, resp.ttlSeconds);
1407
+ return;
1408
+ }
1409
+ setWarm(petRef, resp);
1410
+ dataPetRef = petRef;
1411
+ patch({ data: resp, isPending: false, isError: false, error: null, isDark: false });
1412
+ scheduleRemint(petRef, resp.ttlSeconds);
1413
+ return;
1414
+ }
1415
+ if (isTerminalPetStateError(res.error)) {
1416
+ onTerminalDisabled(petRef, res.error);
1417
+ return;
1418
+ }
1419
+ patch({ isError: true, error: res.error, isPending: snapshot.data === null && dataPetRef !== petRef });
1420
+ if (attempt < MAX_TRANSIENT_RETRIES) {
1421
+ clearRemint();
1422
+ const backoff = 500 * (attempt + 1);
1423
+ const scheduledEpoch = epoch;
1424
+ remintHandle = timers.setTimeout(() => {
1425
+ remintHandle = null;
1426
+ if (scheduledEpoch !== epoch || currentPetRef !== petRef || !isFocused) return;
1427
+ void fetchOnce(petRef, attempt + 1);
1428
+ }, backoff);
1429
+ } else {
1430
+ scheduleRemint(petRef, 5);
1431
+ }
1432
+ };
1433
+ const onTerminalDark = (petRef) => {
1434
+ terminatedPetRef = petRef;
1435
+ warm.delete(petRef);
1436
+ clearRemint();
1437
+ dataPetRef = petRef;
1438
+ patch({ data: null, isPending: false, isError: false, error: null, isDark: true });
1439
+ };
1440
+ const onTerminalDisabled = (petRef, error) => {
1441
+ terminatedPetRef = petRef;
1442
+ warm.delete(petRef);
1443
+ clearRemint();
1444
+ dataPetRef = petRef;
1445
+ patch({ data: null, isPending: false, isError: false, error, isDark: true });
1446
+ };
1447
+ return {
1448
+ observe(petRef, opts) {
1449
+ const focusChanged = opts.isFocused !== isFocused;
1450
+ isFocused = opts.isFocused;
1451
+ if (petRef !== currentPetRef) {
1452
+ epoch += 1;
1453
+ inFlight?.abort();
1454
+ inFlight = null;
1455
+ clearRemint();
1456
+ terminatedPetRef = null;
1457
+ currentPetRef = petRef;
1458
+ if (petRef === null) {
1459
+ dataPetRef = null;
1460
+ snapshot = EMPTY_SNAPSHOT;
1461
+ emit();
1462
+ return;
1463
+ }
1464
+ const warmEntry = warm.get(petRef);
1465
+ const fresh = warmEntry && timers.now() - warmEntry.fetchedAt < staleMs(warmEntry.data) ? warmEntry : null;
1466
+ if (fresh) {
1467
+ touchWarm(petRef);
1468
+ dataPetRef = petRef;
1469
+ patch({ data: fresh.data, isPending: false, isError: false, error: null, isDark: false });
1470
+ } else {
1471
+ patch({ isPending: true, isError: false, error: null, isDark: false });
1472
+ }
1473
+ if (isFocused) void fetchOnce(petRef, 0);
1474
+ return;
1475
+ }
1476
+ if (!focusChanged || petRef === null) return;
1477
+ if (!isFocused) {
1478
+ clearRemint();
1479
+ return;
1480
+ }
1481
+ const entry = warm.get(petRef);
1482
+ if (!entry || timers.now() - entry.fetchedAt >= staleMs(entry.data)) {
1483
+ if (terminatedPetRef !== petRef) void fetchOnce(petRef, 0);
1484
+ } else {
1485
+ scheduleRemint(petRef, entry.data.ttlSeconds);
1486
+ }
1487
+ },
1488
+ getSnapshot() {
1489
+ return snapshot;
1490
+ },
1491
+ subscribe(listener) {
1492
+ listeners.add(listener);
1493
+ return () => {
1494
+ listeners.delete(listener);
1495
+ };
1496
+ },
1497
+ getCachedPetStateMedia(petRef) {
1498
+ const entry = warm.get(petRef);
1499
+ if (!entry) return null;
1500
+ if (timers.now() - entry.fetchedAt >= staleMs(entry.data)) return null;
1501
+ touchWarm(petRef);
1502
+ return entry.data;
1503
+ },
1504
+ dispose() {
1505
+ epoch += 1;
1506
+ inFlight?.abort();
1507
+ inFlight = null;
1508
+ clearRemint();
1509
+ listeners.clear();
1510
+ warm.clear();
1511
+ }
1512
+ };
1513
+ }
1514
+ function isTerminalPetStateError(error) {
1515
+ if (typeof error !== "object" || error === null) return false;
1516
+ const record = error;
1517
+ const status = typeof record.status === "number" ? record.status : record.httpStatus;
1518
+ return status === 403 || status === 404;
1519
+ }
1520
+
1521
+ // src/core/animations/AnimationController.ts
1522
+ function createAnimationController(deps) {
1523
+ const telemetry = deps.telemetry ?? noopTelemetry;
1524
+ const timers = deps.timers ?? defaultTimers(deps.now);
1525
+ const store = createPetStateStore({
1526
+ repo: deps.repo,
1527
+ cacheEpoch: createCacheEpochGuard({ kv: deps.kv, cache: deps.cache }),
1528
+ timers
1529
+ });
1530
+ const listeners = /* @__PURE__ */ new Set();
1531
+ let failed = NO_FAILURES;
1532
+ let fallbackReason = "none";
1533
+ let paused = false;
1534
+ let photoUrl = null;
1535
+ let lastData = null;
1536
+ let lastDark = false;
1537
+ let lastShownKey = "";
1538
+ let view = pendingView(surface());
1539
+ let disposed = false;
1540
+ function surface() {
1541
+ const manifest = deps.manifest ? deps.manifest() : COMPILED_DEFAULT_MANIFEST;
1542
+ return animationsSurfaceOf(manifest);
1543
+ }
1544
+ const emit = () => {
1545
+ for (const listener of listeners) listener();
1546
+ };
1547
+ const unsubscribeStore = store.subscribe(() => {
1548
+ onStoreChange();
1549
+ });
1550
+ function onStoreChange() {
1551
+ const snap = store.getSnapshot();
1552
+ if (snap.data !== lastData || snap.isDark !== lastDark) {
1553
+ lastData = snap.data;
1554
+ lastDark = snap.isDark;
1555
+ failed = NO_FAILURES;
1556
+ fallbackReason = snap.isDark ? "dark_or_missing" : "none";
1557
+ }
1558
+ recompute(snap);
1559
+ }
1560
+ function recompute(snap = store.getSnapshot()) {
1561
+ const surf = surface();
1562
+ const next = buildView(surf, snap, {
1563
+ failed,
1564
+ fallbackReason,
1565
+ paused,
1566
+ photoUrl,
1567
+ reducedMotion: deps.reducedMotion()});
1568
+ view = next;
1569
+ maybeEmitShown(next);
1570
+ emit();
1571
+ }
1572
+ function maybeEmitShown(next) {
1573
+ if (next.kind !== "ready") return;
1574
+ const key = `${next.category}|${next.tier}|${next.fallbackReason}|${next.reducedMotion ? 1 : 0}`;
1575
+ if (key === lastShownKey) return;
1576
+ lastShownKey = key;
1577
+ telemetry.track("pet_state_shown", {
1578
+ category: next.category,
1579
+ // coarse only; privacy-safe (§5.5)
1580
+ tier: next.tier,
1581
+ fallback_reason: next.fallbackReason,
1582
+ reduced_motion: next.reducedMotion
1583
+ });
1584
+ if (next.fallbackReason === "idle_asset_failed") {
1585
+ telemetry.trackExpectedFailure("idle_asset_failed", { category: next.category });
1586
+ }
1587
+ }
1588
+ return {
1589
+ observe(petRef, opts) {
1590
+ if (disposed) return;
1591
+ photoUrl = opts.photoUrl ?? null;
1592
+ failed = NO_FAILURES;
1593
+ store.observe(petRef, { isFocused: opts.isFocused });
1594
+ onStoreChange();
1595
+ },
1596
+ getState() {
1597
+ return view;
1598
+ },
1599
+ subscribe(listener) {
1600
+ listeners.add(listener);
1601
+ return () => {
1602
+ listeners.delete(listener);
1603
+ };
1604
+ },
1605
+ onMediaError() {
1606
+ if (disposed || view.kind !== "ready") return;
1607
+ const retired = retireTier(view.tier, failed);
1608
+ failed = retired.failed;
1609
+ fallbackReason = retired.reason;
1610
+ recompute();
1611
+ },
1612
+ setPaused(next) {
1613
+ if (disposed || paused === next) return;
1614
+ paused = next;
1615
+ recompute();
1616
+ },
1617
+ dispose() {
1618
+ if (disposed) return;
1619
+ disposed = true;
1620
+ unsubscribeStore();
1621
+ store.dispose();
1622
+ listeners.clear();
1623
+ }
1624
+ };
1625
+ }
1626
+ function buildView(surf, snap, inputs) {
1627
+ const idleSource = surf.idle;
1628
+ if (!surf.enabled) {
1629
+ return Object.freeze({
1630
+ kind: "disabled",
1631
+ reason: userFacingError("accessDenied"),
1632
+ level: "partner_config",
1633
+ source: idleSource,
1634
+ idle: surf.idle
1635
+ });
1636
+ }
1637
+ if (snap.isPending && snap.data === null && !snap.isDark) {
1638
+ return Object.freeze({ kind: "pending", showSkeleton: true, source: idleSource });
1639
+ }
1640
+ const data = snap.data;
1641
+ const category = data?.category ?? "idle";
1642
+ const animation = data?.tiers.animation;
1643
+ const image = data?.tiers.image;
1644
+ const canAnimate = Boolean(animation) && animation?.kind === "webp" && !inputs.reducedMotion && !inputs.failed.animation;
1645
+ const tier = selectTier({
1646
+ hasPhoto: inputs.photoUrl !== null && inputs.photoUrl.length > 0,
1647
+ photoFailed: inputs.failed.photo,
1648
+ canAnimate,
1649
+ animationFailed: inputs.failed.animation,
1650
+ hasImage: Boolean(image),
1651
+ imageFailed: inputs.failed.image
1652
+ });
1653
+ let source = idleSource;
1654
+ let loopDurationMs = null;
1655
+ let cacheHit = false;
1656
+ if (tier === "photo" && inputs.photoUrl) {
1657
+ source = uriSource(inputs.photoUrl, void 0);
1658
+ } else if (tier === "animation" && animation) {
1659
+ source = uriSource(animation.url, animation.cacheKey);
1660
+ loopDurationMs = animation.loopDurationMs ?? null;
1661
+ cacheHit = animation.cacheKey !== void 0;
1662
+ } else if (tier === "image" && image) {
1663
+ source = uriSource(image.url, image.cacheKey);
1664
+ cacheHit = image.cacheKey !== void 0;
1665
+ }
1666
+ const recyclingKey = source.kind === "uri" ? source.cacheKey : `bundled:${source.id}`;
1667
+ return Object.freeze({
1668
+ kind: "ready",
1669
+ tier,
1670
+ source,
1671
+ recyclingKey,
1672
+ category,
1673
+ loopDurationMs,
1674
+ paused: inputs.paused,
1675
+ reducedMotion: inputs.reducedMotion,
1676
+ cacheHit,
1677
+ fallbackReason: inputs.fallbackReason,
1678
+ isDark: snap.isDark,
1679
+ isTransientError: snap.isError
1680
+ });
1681
+ }
1682
+ function uriSource(uri, serverCacheKey) {
1683
+ return Object.freeze({
1684
+ kind: "uri",
1685
+ uri,
1686
+ cacheKey: serverCacheKey ?? stableMediaKey({ uri })
1687
+ });
1688
+ }
1689
+ function pendingView(surf) {
1690
+ return Object.freeze({ kind: "pending", showSkeleton: true, source: surf.idle });
1691
+ }
1692
+ function defaultTimers(now) {
1693
+ return {
1694
+ setTimeout: (handler, ms) => setTimeout(handler, ms),
1695
+ clearTimeout: (handle) => clearTimeout(handle),
1696
+ now
1697
+ };
1698
+ }
1699
+
1700
+ // src/rn/animations/useAnimations.ts
1701
+ var PENDING_FALLBACK = Object.freeze({
1702
+ kind: "pending",
1703
+ showSkeleton: true,
1704
+ source: COMPILED_DEFAULT_IDLE
1705
+ });
1706
+ var NOOP_UNSUBSCRIBE = () => {
1707
+ };
1708
+ function useAnimations(params) {
1709
+ const {
1710
+ petRef,
1711
+ repo,
1712
+ cache,
1713
+ kv,
1714
+ isFocused = true,
1715
+ photoUrl = null,
1716
+ telemetry,
1717
+ reducedMotion,
1718
+ manifest,
1719
+ timers,
1720
+ now
1721
+ } = params;
1722
+ const { runtime, userRef } = useEverfurContext();
1723
+ const capability = useCapability("animations");
1724
+ const reducedMotionReader = useSystemReducedMotion(reducedMotion);
1725
+ const hasOverride = repo !== void 0 && cache !== void 0 && kv !== void 0;
1726
+ const seamKey = hasOverride ? "override" : `${userRef ?? ""}|${petRef ?? ""}`;
1727
+ const [controller, setController] = useState(null);
1728
+ useEffect(() => {
1729
+ if (repo !== void 0 && cache !== void 0 && kv !== void 0) {
1730
+ const deps = {
1731
+ repo,
1732
+ cache,
1733
+ kv,
1734
+ reducedMotion: reducedMotionReader,
1735
+ now: now ?? defaultNow,
1736
+ ...telemetry ? { telemetry } : {},
1737
+ ...manifest ? { manifest } : {},
1738
+ ...timers ? { timers } : {}
1739
+ };
1740
+ const built = createAnimationController(deps);
1741
+ setController(built);
1742
+ return () => {
1743
+ setController((current) => current === built ? null : current);
1744
+ built.dispose();
1745
+ };
1746
+ }
1747
+ const { services } = runtime.registry;
1748
+ const acquired = runtime.registry.acquire(
1749
+ "animations",
1750
+ `${userRef ?? ""}|${petRef ?? ""}`,
1751
+ () => createAnimationController({
1752
+ repo: createPetStateRepository(services.authFor(userRef)),
1753
+ cache: services.imageCache,
1754
+ kv: services.kv,
1755
+ reducedMotion: reducedMotionReader,
1756
+ now: now ?? defaultNow,
1757
+ telemetry: services.telemetry,
1758
+ ...manifest ? { manifest } : {},
1759
+ ...timers ? { timers } : {}
1760
+ }),
1761
+ (controller2) => controller2.dispose()
1762
+ );
1763
+ setController(acquired);
1764
+ return () => {
1765
+ setController((current) => current === acquired ? null : current);
1766
+ runtime.registry.release(acquired);
1767
+ };
1768
+ }, [seamKey, repo, cache, kv, runtime]);
1769
+ useEffect(() => {
1770
+ controller?.observe(petRef, { isFocused, photoUrl });
1771
+ }, [controller, petRef, isFocused, photoUrl]);
1772
+ const subscribe = useCallback(
1773
+ (onChange) => controller ? controller.subscribe(onChange) : NOOP_UNSUBSCRIBE,
1774
+ [controller]
1775
+ );
1776
+ const getState = useCallback(
1777
+ () => controller ? controller.getState() : PENDING_FALLBACK,
1778
+ [controller]
1779
+ );
1780
+ const state = useSyncExternalStore(subscribe, getState, getState);
1781
+ const onMediaError = useCallback(() => {
1782
+ controller?.onMediaError();
1783
+ }, [controller]);
1784
+ const setPaused = useCallback(
1785
+ (paused) => {
1786
+ controller?.setPaused(paused);
1787
+ },
1788
+ [controller]
1789
+ );
1790
+ return useMemo(
1791
+ () => ({ capability, state, onMediaError, setPaused }),
1792
+ [capability, state, onMediaError, setPaused]
1793
+ );
1794
+ }
1795
+ function useSystemReducedMotion(provided) {
1796
+ const enabledRef = useRef(true);
1797
+ useEffect(() => {
1798
+ if (provided) return;
1799
+ let active = true;
1800
+ const probe = AccessibilityInfo.isReduceMotionEnabled?.();
1801
+ if (probe && typeof probe.then === "function") {
1802
+ void probe.then((value) => {
1803
+ if (active) enabledRef.current = value;
1804
+ });
1805
+ }
1806
+ const subscription = AccessibilityInfo.addEventListener?.("reduceMotionChanged", (value) => {
1807
+ enabledRef.current = value;
1808
+ });
1809
+ return () => {
1810
+ active = false;
1811
+ subscription?.remove?.();
1812
+ };
1813
+ }, [provided]);
1814
+ return useMemo(() => provided ?? (() => enabledRef.current), [provided]);
1815
+ }
1816
+ function defaultNow() {
1817
+ return Date.now();
1818
+ }
1819
+ var PET_STATE_CROSSFADE_MS = 200;
1820
+ var SPINNER_DELAY_MS = 300;
1821
+ var MIN_MEDIA_HEIGHT = 120;
1822
+ function PetStateView(props) {
1823
+ const { style, accessibilityLabel } = props;
1824
+ const a11y = { accessibilityLabel, decorative: isDecorative(props) };
1825
+ return /* @__PURE__ */ jsx(
1826
+ CapabilityGate,
1827
+ {
1828
+ capability: "animations",
1829
+ style,
1830
+ renderPending: () => /* @__PURE__ */ jsx(IdleRegion, { style, a11y, busy: true }),
1831
+ renderDisabled: (decision) => /* @__PURE__ */ jsx(IdleRegion, { style, a11y, reason: decision.disabled?.reason ?? "" }),
1832
+ children: /* @__PURE__ */ jsx(PetStateBody, { ...props })
1833
+ }
1834
+ );
1835
+ }
1836
+ function isDecorative(props) {
1837
+ return props.decorative === true || props.accessibilityLabel === void 0;
1838
+ }
1839
+ function PetStateBody(props) {
1840
+ const styles = useStyles();
1841
+ const a11y = {
1842
+ accessibilityLabel: props.accessibilityLabel,
1843
+ decorative: isDecorative(props)
1844
+ };
1845
+ const state = useAnimations(buildParams(props));
1846
+ return /* @__PURE__ */ jsx(View, { style: [styles.container, props.style], children: renderState(state.state, state.onMediaError, a11y) });
1847
+ }
1848
+ function renderState(view, onMediaError, a11y) {
1849
+ switch (view.kind) {
1850
+ case "pending":
1851
+ return /* @__PURE__ */ jsx(MediaNode, { source: view.source, recyclingKey: "pending", reducedMotion: true, a11y, busy: true, onMediaError });
1852
+ case "disabled":
1853
+ return /* @__PURE__ */ jsx(IdleRegion, { a11y, reason: view.reason });
1854
+ case "ready":
1855
+ return /* @__PURE__ */ jsx(
1856
+ MediaNode,
1857
+ {
1858
+ source: view.source,
1859
+ recyclingKey: view.recyclingKey,
1860
+ reducedMotion: view.reducedMotion,
1861
+ a11y,
1862
+ onMediaError
1863
+ }
1864
+ );
1865
+ default:
1866
+ return assertNever(view);
1867
+ }
1868
+ }
1869
+ function MediaNode({
1870
+ source,
1871
+ recyclingKey,
1872
+ reducedMotion,
1873
+ a11y,
1874
+ busy,
1875
+ onMediaError
1876
+ }) {
1877
+ const styles = useStyles();
1878
+ if (source.kind === "uri") {
1879
+ return /* @__PURE__ */ jsx(
1880
+ Image,
1881
+ {
1882
+ source: { uri: source.uri },
1883
+ onError: onMediaError,
1884
+ fadeDuration: reducedMotion ? 0 : PET_STATE_CROSSFADE_MS,
1885
+ style: styles.media,
1886
+ ...a11yProps(a11y)
1887
+ },
1888
+ recyclingKey
1889
+ );
1890
+ }
1891
+ return /* @__PURE__ */ jsx(IdleRegion, { a11y, busy });
1892
+ }
1893
+ function IdleRegion({
1894
+ style,
1895
+ a11y,
1896
+ busy,
1897
+ reason
1898
+ }) {
1899
+ const styles = useStyles();
1900
+ return /* @__PURE__ */ jsxs(View, { style: [styles.idlePlaceholder, style], ...a11yProps(a11y), children: [
1901
+ busy ? /* @__PURE__ */ jsx(DelayedSpinner, {}) : null,
1902
+ reason && reason.length > 0 ? /* @__PURE__ */ jsx(Text, { style: styles.reasonText, children: reason }) : null
1903
+ ] });
1904
+ }
1905
+ function DelayedSpinner() {
1906
+ const theme = useEverfurTheme();
1907
+ const [visible, setVisible] = useState(false);
1908
+ useEffect(() => {
1909
+ const id = setTimeout(() => setVisible(true), SPINNER_DELAY_MS);
1910
+ return () => clearTimeout(id);
1911
+ }, []);
1912
+ return visible ? /* @__PURE__ */ jsx(ActivityIndicator, { color: theme.color.brand }) : null;
1913
+ }
1914
+ function a11yProps(a11y) {
1915
+ if (a11y.decorative) {
1916
+ return { accessible: false, accessibilityElementsHidden: true, importantForAccessibility: "no-hide-descendants" };
1917
+ }
1918
+ const label = a11y.accessibilityLabel;
1919
+ return label !== void 0 ? { accessible: true, accessibilityRole: "image", accessibilityLabel: label } : { accessible: true, accessibilityRole: "image" };
1920
+ }
1921
+ function buildParams(props) {
1922
+ const params = { petRef: props.petRef, repo: props.repo, cache: props.cache, kv: props.kv };
1923
+ if (props.isFocused !== void 0) params.isFocused = props.isFocused;
1924
+ if (props.photoUrl !== void 0) params.photoUrl = props.photoUrl;
1925
+ if (props.telemetry !== void 0) params.telemetry = props.telemetry;
1926
+ if (props.reducedMotion !== void 0) params.reducedMotion = props.reducedMotion;
1927
+ if (props.manifest !== void 0) params.manifest = props.manifest;
1928
+ if (props.timers !== void 0) params.timers = props.timers;
1929
+ if (props.now !== void 0) params.now = props.now;
1930
+ return params;
1931
+ }
1932
+ function useStyles() {
1933
+ const theme = useEverfurTheme();
1934
+ return useMemo(() => makeStyles2(theme), [theme]);
1935
+ }
1936
+ function makeStyles2(theme) {
1937
+ return StyleSheet.create({
1938
+ // Cream ground + rounded frame so the media crossfade sits on a branded surface with clipped corners.
1939
+ container: {
1940
+ minHeight: MIN_MEDIA_HEIGHT,
1941
+ width: "100%",
1942
+ backgroundColor: theme.color.surfaceCream,
1943
+ borderRadius: theme.radius.lg,
1944
+ overflow: "hidden"
1945
+ },
1946
+ media: { minHeight: MIN_MEDIA_HEIGHT, width: "100%" },
1947
+ // Idle placeholder: an Everfur cream card with a hairline cream ring for subtle depth (never grey-on-blue).
1948
+ idlePlaceholder: {
1949
+ minHeight: MIN_MEDIA_HEIGHT,
1950
+ width: "100%",
1951
+ alignItems: "center",
1952
+ justifyContent: "center",
1953
+ backgroundColor: theme.color.surfaceCream,
1954
+ borderRadius: theme.radius.lg,
1955
+ borderWidth: StyleSheet.hairlineWidth,
1956
+ borderColor: theme.color.borderRingCream,
1957
+ padding: theme.space.lg
1958
+ },
1959
+ // Safe disabled reason: the warm muted ramp, on-brand type scale, legible in both themes.
1960
+ reasonText: {
1961
+ marginTop: theme.space.sm,
1962
+ fontFamily: theme.type.family,
1963
+ fontSize: theme.type.size.bodyTight,
1964
+ lineHeight: Math.round(theme.type.size.bodyTight * theme.type.lineHeight.normal),
1965
+ fontWeight: theme.type.weight.medium,
1966
+ color: theme.color.text.muted,
1967
+ textAlign: "center"
1968
+ }
1969
+ });
1970
+ }
1971
+
1972
+ export { CACHE_EPOCH_STORAGE_KEY, COMPILED_DEFAULT_IDLE, COMPILED_DEFAULT_MANIFEST, MANIFEST_LKG_STORAGE_KEY, NO_FAILURES, PetStateView, SUPPORTED_SCHEMA_VERSION, animationsSurfaceOf, createAnimationController, createCacheEpochGuard, createPetStateRepository, createPetStateStore, isLoaderSafeCategory, isTerminalPetStateError, mapPetStateResponse, newSessionId, parseManifest, parsePetStateWire, petStateResponseWireSchema, resolveManifest, retireTier, selectTier, stableMediaKey, useAnimations };