@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,2189 @@
1
+ 'use strict';
2
+
3
+ var react = require('react');
4
+ require('react-native-safe-area-context');
5
+ var reactNative = require('react-native');
6
+ var jsxRuntime = require('react/jsx-runtime');
7
+
8
+ // src/rn/photo/usePhoto.ts
9
+ var CONTRACT_RETRYABILITY = Object.freeze([
10
+ Object.freeze({ wireCode: "AccessDeniedException", envelope: "http_envelope", httpStatus: 403, retryable: false }),
11
+ Object.freeze({ wireCode: "AuthorizationException", envelope: "http_envelope", httpStatus: 401, retryable: false }),
12
+ Object.freeze({ wireCode: "ConflictException", envelope: "http_envelope", httpStatus: 409, retryable: true }),
13
+ Object.freeze({ wireCode: "DAILY_QUOTA_EXCEEDED", envelope: "http_envelope", httpStatus: 429, retryable: true }),
14
+ Object.freeze({ wireCode: "IDEMPOTENCY_KEY_IN_FLIGHT", envelope: "http_envelope", httpStatus: 409, retryable: true }),
15
+ Object.freeze({ wireCode: "IDEMPOTENCY_KEY_REUSED_DIFFERENT_REQUEST", envelope: "http_envelope", httpStatus: 409, retryable: false }),
16
+ Object.freeze({ wireCode: "InternalFailureException", envelope: "http_envelope", httpStatus: 500, retryable: true }),
17
+ Object.freeze({ wireCode: "NotImplementedException", envelope: "http_envelope", httpStatus: 501, retryable: false }),
18
+ Object.freeze({ wireCode: "PaymentRequiredException", envelope: "http_envelope", httpStatus: 402, retryable: false }),
19
+ Object.freeze({ wireCode: "ResourceNotFoundException", envelope: "http_envelope", httpStatus: 404, retryable: false }),
20
+ Object.freeze({ wireCode: "ServiceUnavailableException", envelope: "http_envelope", httpStatus: 503, retryable: true }),
21
+ Object.freeze({ wireCode: "TIER_UPGRADE_REQUIRED", envelope: "http_envelope", httpStatus: 402, retryable: false }),
22
+ Object.freeze({ wireCode: "ThrottlingException", envelope: "http_envelope", httpStatus: 429, retryable: true }),
23
+ Object.freeze({ wireCode: "ValidationException", envelope: "http_envelope", httpStatus: 400, retryable: false }),
24
+ Object.freeze({ wireCode: "accessDenied", envelope: "http_envelope", httpStatus: 403, retryable: false }),
25
+ Object.freeze({ wireCode: "authExpired", envelope: "http_envelope", httpStatus: 401, retryable: true }),
26
+ Object.freeze({ wireCode: "internal_error", envelope: "sse_frame", httpStatus: 200, retryable: false }),
27
+ Object.freeze({ wireCode: "invalidRequest", envelope: "http_envelope", httpStatus: 400, retryable: false }),
28
+ Object.freeze({ wireCode: "not_found", envelope: "sse_frame", httpStatus: 200, retryable: false }),
29
+ Object.freeze({ wireCode: "session_required", envelope: "http_envelope", httpStatus: 403, retryable: false }),
30
+ Object.freeze({ wireCode: "timeout", envelope: "sse_frame", httpStatus: 200, retryable: true }),
31
+ Object.freeze({ wireCode: "unavailable", envelope: "http_envelope", httpStatus: 503, retryable: true })
32
+ ]);
33
+ Object.freeze(
34
+ CONTRACT_RETRYABILITY.map((row) => row.wireCode)
35
+ );
36
+
37
+ // src/client/errors/contract.ts
38
+ var NORMALIZED_FOLD = Object.freeze({
39
+ // the default status-mapped envelope
40
+ ValidationException: "validationFailed",
41
+ AuthorizationException: "authRejected",
42
+ PaymentRequiredException: "paymentRequired",
43
+ AccessDeniedException: "accessDenied",
44
+ ResourceNotFoundException: "resourceNotFound",
45
+ ConflictException: "conflict",
46
+ ThrottlingException: "rateLimited",
47
+ InternalFailureException: "internalError",
48
+ NotImplementedException: "notImplemented",
49
+ ServiceUnavailableException: "serviceUnavailable",
50
+ // dict-detail codes on the widget surface
51
+ authExpired: "authExpired",
52
+ unavailable: "serviceUnavailable",
53
+ session_required: "sessionRequired",
54
+ accessDenied: "accessDenied",
55
+ invalidRequest: "sdkUpdateRequired",
56
+ // typed codes
57
+ IDEMPOTENCY_KEY_IN_FLIGHT: "idempotencyInFlight",
58
+ IDEMPOTENCY_KEY_REUSED_DIFFERENT_REQUEST: "idempotencyConflict",
59
+ DAILY_QUOTA_EXCEEDED: "quotaExceeded",
60
+ TIER_UPGRADE_REQUIRED: "paymentRequired",
61
+ // SSE error frames
62
+ not_found: "conversationNotFound",
63
+ timeout: "streamTimeout",
64
+ internal_error: "internalError"
65
+ });
66
+ var CONTRACT_ERROR_ROWS = Object.freeze(
67
+ CONTRACT_RETRYABILITY.map(
68
+ (generated) => Object.freeze({
69
+ wireCode: generated.wireCode,
70
+ envelope: generated.envelope,
71
+ retryable: generated.retryable,
72
+ normalized: NORMALIZED_FOLD[generated.wireCode]
73
+ })
74
+ )
75
+ );
76
+ var BY_UPPER = new Map(
77
+ CONTRACT_ERROR_ROWS.map((r) => [r.wireCode.toUpperCase(), r])
78
+ );
79
+ function contractErrorFor(wireCode) {
80
+ if (typeof wireCode !== "string") return void 0;
81
+ const key = wireCode.trim().toUpperCase();
82
+ return key.length > 0 ? BY_UPPER.get(key) : void 0;
83
+ }
84
+ var CATEGORY_OF = Object.freeze({
85
+ // the caller's sign-in state is wrong and a credential change is the remedy
86
+ authExpired: "authentication",
87
+ authRejected: "authentication",
88
+ sessionRequired: "authentication",
89
+ // signed in, correctly identified, and still not allowed
90
+ accessDenied: "authorization",
91
+ // a plan gate, not a permission failure: the remedy is commercial
92
+ paymentRequired: "entitlement",
93
+ // slow down / come back later
94
+ quotaExceeded: "rateLimit",
95
+ rateLimited: "rateLimit",
96
+ // the request itself was wrong; retrying it unchanged can never succeed
97
+ validationFailed: "invalidRequest",
98
+ sdkUpdateRequired: "invalidRequest",
99
+ // the target is gone, hidden, or was never visible to this caller
100
+ conversationNotFound: "notFound",
101
+ petNotFound: "notFound",
102
+ resourceNotFound: "notFound",
103
+ // something else already holds the thing
104
+ conflict: "conflict",
105
+ idempotencyConflict: "conflict",
106
+ idempotencyInFlight: "conflict",
107
+ // the pipe, not the request: timeouts, drops, a briefly unreachable dependency
108
+ streamTimeout: "connection",
109
+ streamIncomplete: "connection",
110
+ upstreamLlmTimeout: "connection",
111
+ serviceUnavailable: "connection",
112
+ // the server admits fault
113
+ internalError: "server",
114
+ notImplemented: "server",
115
+ mediaUploadFailed: "media",
116
+ moderationBlocked: "policy",
117
+ unknown: "unknown"
118
+ });
119
+ function categoryFor(code) {
120
+ return CATEGORY_OF[code];
121
+ }
122
+ function fromWire(wire) {
123
+ const contractRow = contractErrorFor(wire);
124
+ if (contractRow) return contractRow.normalized;
125
+ const upper = (wire ?? "").trim().toUpperCase();
126
+ const canonical = upper.replace(/[^A-Z0-9]/g, "");
127
+ if (canonical === "AUTHREJECTED") return "authRejected";
128
+ if (upper.startsWith("AUTH")) return "authExpired";
129
+ switch (canonical) {
130
+ case "DAILYQUOTAEXCEEDED":
131
+ case "QUOTAEXCEEDED":
132
+ return "quotaExceeded";
133
+ case "RATELIMITED":
134
+ case "TOOMANYREQUESTS":
135
+ return "rateLimited";
136
+ case "IDEMPOTENCYKEYCONFLICT":
137
+ case "IDEMPOTENCYCONFLICT":
138
+ return "idempotencyConflict";
139
+ case "ACCESSDENIED":
140
+ case "FORBIDDEN":
141
+ return "accessDenied";
142
+ case "NOTFOUND":
143
+ case "CONVERSATIONNOTFOUND":
144
+ return "conversationNotFound";
145
+ case "PETNOTFOUND":
146
+ return "petNotFound";
147
+ case "TIMEOUT":
148
+ case "STREAMTIMEOUT":
149
+ return "streamTimeout";
150
+ // Analysis-domain deterministic 400s (NON-retryable). Additive per SPEC-00 §3.1 / SPEC-11b §2.6:
151
+ // fold to a NON-retried target so the SDK never retries a permanently-failing bad-input request.
152
+ // (Comment above the group so the empty fall-through cases stay lint-clean under no-fallthrough.)
153
+ case "MEDIAUPLOADFAILED":
154
+ case "UNRECOGNIZEDVIDEOFORMAT":
155
+ case "FILETOOSMALL":
156
+ return "mediaUploadFailed";
157
+ case "MODERATIONBLOCKED":
158
+ return "moderationBlocked";
159
+ case "UPSTREAMLLMTIMEOUT":
160
+ return "upstreamLlmTimeout";
161
+ case "INTERNALERROR":
162
+ case "INTERNALSERVERERROR":
163
+ return "internalError";
164
+ case "STREAMINCOMPLETE":
165
+ case "CHATSTREAMINCOMPLETE":
166
+ return "streamIncomplete";
167
+ // Deterministic 400s that can only come from an SDK bug -> unknown (NON-retryable). NEVER internalError
168
+ // (which IS auto-retried): mapping a bad-input 400 to a retryable code retries a request that never succeeds.
169
+ case "INVALIDANALYSISTYPE":
170
+ case "INVALIDUPLOADPURPOSE":
171
+ return "unknown";
172
+ default:
173
+ return "unknown";
174
+ }
175
+ }
176
+ var AUTO_RETRYABLE_CODES = /* @__PURE__ */ new Set([
177
+ "streamTimeout",
178
+ "rateLimited",
179
+ "internalError",
180
+ "upstreamLlmTimeout",
181
+ "streamIncomplete"
182
+ ]);
183
+ function isAutoRetryable(code) {
184
+ return AUTO_RETRYABLE_CODES.has(code);
185
+ }
186
+ var RETRYABLE_CONTRACT_CODES = /* @__PURE__ */ new Set([
187
+ "serviceUnavailable",
188
+ "conflict",
189
+ "idempotencyInFlight"
190
+ ]);
191
+ function isRetryableCode(code) {
192
+ return isAutoRetryable(code) || RETRYABLE_CONTRACT_CODES.has(code);
193
+ }
194
+ var BACKOFF_BASE_MS = 500;
195
+ var BACKOFF_CAP_MS = 8e3;
196
+ var MAX_RETRY_ATTEMPTS = 4;
197
+ function backoffDelayMs(attempt, rng = Math.random) {
198
+ const bounded = Math.max(0, attempt);
199
+ const ceiling = Math.min(BACKOFF_BASE_MS * 2 ** bounded, BACKOFF_CAP_MS);
200
+ return Math.floor(rng() * ceiling);
201
+ }
202
+
203
+ // src/client/errors/EverfurError.ts
204
+ var USER_FACING_COPY = Object.freeze({
205
+ authExpired: "Please sign in again to continue.",
206
+ authRejected: "Please sign in again to continue.",
207
+ sessionRequired: "This app needs to be updated to keep using Everfur.",
208
+ accessDenied: "This feature isn't available on your account right now.",
209
+ paymentRequired: "This is part of a paid plan.",
210
+ quotaExceeded: "You have used today's messages. This resets tomorrow.",
211
+ rateLimited: "You are sending messages quickly. Try again in a few seconds.",
212
+ validationFailed: "Something in that request was not right. Check the details and try again.",
213
+ sdkUpdateRequired: "This app needs to be updated to keep using Everfur.",
214
+ conflict: "That is already running. Wait for it to finish, then try again.",
215
+ idempotencyConflict: "That message was already delivered.",
216
+ idempotencyInFlight: "That is still processing. Give it a moment.",
217
+ conversationNotFound: "This conversation is no longer available.",
218
+ petNotFound: "We could not find that pet. Please pick a pet and try again.",
219
+ resourceNotFound: "We could not find that.",
220
+ streamTimeout: "The response timed out. Tap retry to try again.",
221
+ mediaUploadFailed: "We could not upload that photo. Please attach it again.",
222
+ moderationBlocked: "This request cannot be answered here.",
223
+ upstreamLlmTimeout: "The response timed out. Tap retry to try again.",
224
+ internalError: "We hit a snag on our end. Please try again.",
225
+ notImplemented: "That is not available yet.",
226
+ serviceUnavailable: "That service is briefly unavailable. Try again shortly.",
227
+ streamIncomplete: "The connection dropped mid-answer. Tap retry to continue.",
228
+ unknown: "Something went wrong. Please try again."
229
+ });
230
+ function userFacingError(code) {
231
+ return USER_FACING_COPY[code];
232
+ }
233
+ function defineHidden(target, key, value) {
234
+ Object.defineProperty(target, key, {
235
+ value,
236
+ enumerable: false,
237
+ writable: false,
238
+ configurable: false
239
+ });
240
+ }
241
+ function makeEverfurError(code, opts) {
242
+ contractErrorFor(opts?.wireCode);
243
+ const error = {
244
+ code,
245
+ category: categoryFor(code),
246
+ retryable: opts?.retryable ?? isRetryableCode(code),
247
+ displayMessage: userFacingError(code)
248
+ };
249
+ if (opts?.httpStatus !== void 0) error.httpStatus = opts.httpStatus;
250
+ if (opts?.requestId) error.requestId = opts.requestId;
251
+ if (opts?.wireMessage) defineHidden(error, "wireMessage", opts.wireMessage);
252
+ if (opts?.raw !== void 0 && opts.raw !== null) defineHidden(error, "raw", opts.raw);
253
+ return Object.freeze(error);
254
+ }
255
+
256
+ // src/client/errors/EverfurResult.ts
257
+ function ok(value, warning) {
258
+ return Object.freeze(
259
+ { ok: true, value }
260
+ );
261
+ }
262
+ function err(error) {
263
+ return Object.freeze({ ok: false, error });
264
+ }
265
+ var EverfurConfigError = class _EverfurConfigError extends Error {
266
+ constructor(kind, message) {
267
+ super(message);
268
+ this.name = "EverfurConfigError";
269
+ this.kind = kind;
270
+ Object.setPrototypeOf(this, _EverfurConfigError.prototype);
271
+ }
272
+ };
273
+
274
+ // src/client/protocol/frames.ts
275
+ function assertNever(x) {
276
+ throw new Error(
277
+ `assertNever: unhandled discriminated-union member ${JSON.stringify(x)}`
278
+ );
279
+ }
280
+ function errorFrame(fields) {
281
+ return Object.freeze({
282
+ kind: "error",
283
+ terminal: true,
284
+ code: fields.code,
285
+ retryable: fields.retryable,
286
+ wireMessage: fields.wireMessage,
287
+ synthesized: fields.synthesized,
288
+ lastEventId: fields.lastEventId,
289
+ serverRequestId: null
290
+ });
291
+ }
292
+
293
+ // src/client/identity.ts
294
+ function authHeaders(auth) {
295
+ const headers = {};
296
+ if (auth.mode === "personalized") {
297
+ headers.authorization = `Bearer ${auth.token}`;
298
+ } else {
299
+ headers["x-everfur-partner-key"] = auth.publishableKey;
300
+ }
301
+ if (auth.userRef) headers["x-everfur-user-ref"] = auth.userRef;
302
+ if (auth.sessionId) headers["x-everfur-session-id"] = auth.sessionId;
303
+ return headers;
304
+ }
305
+ function withAuthHeaders(req, auth) {
306
+ return { ...req, headers: { ...stripAuthHeaders(req.headers), ...authHeaders(auth) } };
307
+ }
308
+ function stripAuthHeaders(headers) {
309
+ if (!headers) return {};
310
+ const out = {};
311
+ for (const [key, value] of Object.entries(headers)) {
312
+ const lower = key.toLowerCase();
313
+ if (lower === "authorization" || lower === "x-everfur-partner-key") continue;
314
+ out[key] = value;
315
+ }
316
+ return out;
317
+ }
318
+ async function authedSend(req, ctx) {
319
+ if (ctx.mode === "anonymous") {
320
+ return ctx.transport.request(
321
+ withAuthHeaders(req, {
322
+ mode: "anonymous",
323
+ publishableKey: ctx.publishableKey,
324
+ userRef: ctx.userRef,
325
+ ...ctx.sessionId ? { sessionId: ctx.sessionId } : {}
326
+ })
327
+ );
328
+ }
329
+ let token;
330
+ try {
331
+ token = await ctx.identity.currentToken();
332
+ } catch {
333
+ return err(authRejectedError());
334
+ }
335
+ const first = await ctx.transport.request(
336
+ withAuthHeaders(req, {
337
+ mode: "personalized",
338
+ token,
339
+ userRef: ctx.userRef,
340
+ ...ctx.sessionId ? { sessionId: ctx.sessionId } : {}
341
+ })
342
+ );
343
+ if (first.ok || first.error.httpStatus !== 401) return first;
344
+ let refreshed;
345
+ try {
346
+ refreshed = await ctx.identity.currentToken({ forceRefresh: true });
347
+ } catch {
348
+ return err(authRejectedError());
349
+ }
350
+ const retry = await ctx.transport.request(
351
+ withAuthHeaders(req, {
352
+ mode: "personalized",
353
+ token: refreshed,
354
+ userRef: ctx.userRef,
355
+ ...ctx.sessionId ? { sessionId: ctx.sessionId } : {}
356
+ })
357
+ );
358
+ if (!retry.ok && retry.error.httpStatus === 401) {
359
+ return err(authRejectedError(retry.error.httpStatus));
360
+ }
361
+ return retry;
362
+ }
363
+ function authRejectedError(httpStatus) {
364
+ return makeEverfurError("authRejected", {
365
+ retryable: false,
366
+ ...httpStatus !== void 0 ? { httpStatus } : {}
367
+ });
368
+ }
369
+
370
+ // src/client/transport.ts
371
+ function networkError(cause) {
372
+ return makeEverfurError("internalError", { retryable: true, wireMessage: describeCause(cause) });
373
+ }
374
+ function describeCause(cause) {
375
+ if (cause instanceof Error) return cause.message;
376
+ return typeof cause === "string" ? cause : "network request failed";
377
+ }
378
+
379
+ // src/client/funnel/requestFunnel.ts
380
+ var FUNNEL_UNARY_TIMEOUT_MS = 3e4;
381
+ var RETRY_OVERRIDE_MAX_MS = BACKOFF_CAP_MS * 2;
382
+ var IDEMPOTENCY_HEADER = "idempotency-key";
383
+ var MUTATING_METHODS = /* @__PURE__ */ new Set(["POST", "PUT", "PATCH", "DELETE"]);
384
+ var NOOP_OBSERVER = Object.freeze({
385
+ onEvent() {
386
+ }
387
+ });
388
+ var defaultFunnelTimers = Object.freeze({
389
+ setTimeout: (handler, ms) => setTimeout(handler, ms),
390
+ clearTimeout: (handle) => clearTimeout(handle),
391
+ now: () => Date.now()
392
+ });
393
+ function createRequestFunnel(deps) {
394
+ const observer = deps.observer ?? NOOP_OBSERVER;
395
+ const timers = deps.timers ?? defaultFunnelTimers;
396
+ const rng = deps.rng ?? Math.random;
397
+ const sleep = deps.sleep ?? ((ms, signal) => delayAbortable(ms, timers, signal));
398
+ const ceiling = deps.maxAttempts ?? MAX_RETRY_ATTEMPTS;
399
+ const timeoutMs = deps.unaryTimeoutMs ?? FUNNEL_UNARY_TIMEOUT_MS;
400
+ const mintKey = deps.newIdempotencyKey ?? defaultIdempotencyKeyFactory();
401
+ const emit = (event) => {
402
+ try {
403
+ observer.onEvent(event);
404
+ } catch {
405
+ }
406
+ };
407
+ async function send(call, req, opts) {
408
+ const perCallMaxAttempts = opts?.maxAttempts;
409
+ const maxAttempts = Math.max(1, perCallMaxAttempts ?? ceiling);
410
+ const idempotent = opts?.idempotent ?? MUTATING_METHODS.has(req.method);
411
+ const idempotencyKey = idempotent ? mintKey() : null;
412
+ const base = assembleHeaders(req, idempotencyKey);
413
+ let attempt = 0;
414
+ for (; ; ) {
415
+ const stamp = (extra) => Object.freeze({
416
+ call,
417
+ method: req.method,
418
+ path: req.path,
419
+ attempt,
420
+ ...idempotencyKey ? { idempotencyKey } : {},
421
+ ...extra
422
+ });
423
+ emit(stamp({ phase: "attempt" }));
424
+ const deadline = boundedSignal(timeoutMs, timers);
425
+ const merged = mergeSignals(deadline.signal, req.signal);
426
+ let settled;
427
+ try {
428
+ settled = await authedSend({ ...base, signal: merged.signal }, deps.auth);
429
+ } catch (cause) {
430
+ settled = err(networkError(cause));
431
+ } finally {
432
+ merged.dispose();
433
+ deadline.cancel();
434
+ }
435
+ if (settled.ok) {
436
+ emit(stamp({ phase: "settled", ok: true, reason: "ok" }));
437
+ return settled;
438
+ }
439
+ const error = settled.error;
440
+ const decision = decideRetry(error, attempt, {
441
+ maxAttempts,
442
+ rng,
443
+ now: timers.now(),
444
+ aborted: req.signal?.aborted === true,
445
+ ...perCallMaxAttempts !== void 0 ? { perCallMaxAttempts } : {},
446
+ ...deps.errorPolicy !== void 0 ? { policy: deps.errorPolicy } : {}
447
+ });
448
+ const settledEvent = {
449
+ ok: false,
450
+ code: error.code,
451
+ reason: decision.reason,
452
+ ...error.httpStatus !== void 0 ? { httpStatus: error.httpStatus } : {},
453
+ ...error.requestId !== void 0 ? { requestId: error.requestId } : {}
454
+ };
455
+ if (!decision.retry) {
456
+ emit(stamp({ phase: "settled", ...settledEvent }));
457
+ return err(error);
458
+ }
459
+ emit(stamp({ phase: "retry", ...settledEvent, delayMs: decision.delayMs }));
460
+ await sleep(decision.delayMs, req.signal);
461
+ if (req.signal?.aborted === true) {
462
+ emit(stamp({ phase: "settled", ...settledEvent, reason: "aborted" }));
463
+ return err(error);
464
+ }
465
+ attempt += 1;
466
+ }
467
+ }
468
+ async function authorize(req) {
469
+ return withAuthHeaders(req, await resolveDeviceAuth(deps.auth));
470
+ }
471
+ async function* stream(call, req, signal) {
472
+ emit(
473
+ Object.freeze({
474
+ call,
475
+ phase: "stream.open",
476
+ method: req.method,
477
+ path: req.path,
478
+ attempt: 0
479
+ })
480
+ );
481
+ try {
482
+ yield* deps.auth.transport.stream(req, signal);
483
+ } catch {
484
+ yield errorFrame({
485
+ // The same wire spelling sse.ts synthesizes, so `fromWire` folds it to the retryable `internalError`
486
+ // like any other transport failure. wireMessage stays null: it is the SERVER's text, and a thrown
487
+ // host exception's `.message` is not that.
488
+ code: "internal_error",
489
+ retryable: true,
490
+ wireMessage: null,
491
+ synthesized: true,
492
+ lastEventId: null});
493
+ }
494
+ }
495
+ return Object.freeze({ send, authorize, stream });
496
+ }
497
+ function assembleHeaders(req, idempotencyKey) {
498
+ const headers = {};
499
+ for (const [key, value] of Object.entries(req.headers ?? {})) {
500
+ if (key.toLowerCase() === IDEMPOTENCY_HEADER) continue;
501
+ headers[key] = value;
502
+ }
503
+ if (idempotencyKey !== null) headers["Idempotency-Key"] = idempotencyKey;
504
+ return { ...req, headers };
505
+ }
506
+ function defaultIdempotencyKeyFactory() {
507
+ let counter = 0;
508
+ return () => `efk_${Date.now().toString(36)}_${(counter++).toString(36)}_${Math.random().toString(36).slice(2, 12)}`;
509
+ }
510
+ var POLICY_MAX_ATTEMPTS_CAP = 10;
511
+ function decideRetry(error, attempt, ctx) {
512
+ if (ctx.aborted) return { retry: false, reason: "aborted" };
513
+ const throttle = throttleKind(error);
514
+ if (throttle === "quota") {
515
+ return { retry: false, reason: "daily-quota-exhausted" };
516
+ }
517
+ if (throttle !== "burst" && !isAutoRetryable(error.code)) {
518
+ return { retry: false, reason: "terminal-code" };
519
+ }
520
+ const reason = throttle === "burst" ? "burst-throttle" : "retryable-code";
521
+ const policyVetoedRetry = () => {
522
+ if (ctx.policy === void 0) return false;
523
+ try {
524
+ return !ctx.policy.shouldRetry(error.code, attempt);
525
+ } catch {
526
+ return false;
527
+ }
528
+ };
529
+ if (policyVetoedRetry()) return { retry: false, reason: "terminal-code" };
530
+ const policyCeiling = () => {
531
+ if (ctx.policy === void 0) return null;
532
+ let raw;
533
+ try {
534
+ raw = ctx.policy.maxAttempts(error.code);
535
+ } catch {
536
+ return null;
537
+ }
538
+ if (typeof raw !== "number" || !Number.isFinite(raw)) return null;
539
+ return Math.max(1, Math.min(POLICY_MAX_ATTEMPTS_CAP, Math.floor(raw)));
540
+ };
541
+ const ceiling = ctx.perCallMaxAttempts ?? policyCeiling() ?? ctx.maxAttempts;
542
+ if (attempt + 1 >= ceiling) return { retry: false, reason: "attempts-exhausted" };
543
+ const override = retryOverrideMs(error, ctx.now);
544
+ if (override !== null) {
545
+ if (override > RETRY_OVERRIDE_MAX_MS) {
546
+ return { retry: false, reason: "server-reset-beyond-budget" };
547
+ }
548
+ return { retry: true, reason, delayMs: override };
549
+ }
550
+ return { retry: true, reason, delayMs: backoffDelayMs(attempt, ctx.rng) };
551
+ }
552
+ function throttleKind(error) {
553
+ const code = error.code === "unknown" ? fromWire(rawWireCode(error.raw)) : error.code;
554
+ if (code === "quotaExceeded") return "quota";
555
+ if (code === "rateLimited") return "burst";
556
+ if (error.httpStatus === 429) {
557
+ return "burst";
558
+ }
559
+ return null;
560
+ }
561
+ function retryOverrideMs(error, now) {
562
+ const at = findResetsAt(error.raw);
563
+ if (at === null) return null;
564
+ const delta = at - now;
565
+ return delta > 0 ? delta : 0;
566
+ }
567
+ function findResetsAt(raw) {
568
+ for (const scope of candidateScopes(raw)) {
569
+ const value = scope["resets_at"];
570
+ const parsed = parseInstantMs(value);
571
+ if (parsed !== null) return parsed;
572
+ }
573
+ return null;
574
+ }
575
+ function candidateScopes(raw) {
576
+ if (!isRecord(raw)) return [];
577
+ const out = [raw];
578
+ for (const nested of ["error", "detail"]) {
579
+ const value = raw[nested];
580
+ if (isRecord(value)) out.push(value);
581
+ }
582
+ return out;
583
+ }
584
+ function parseInstantMs(value) {
585
+ if (typeof value === "number" && Number.isFinite(value)) {
586
+ return value < 1e11 ? Math.round(value * 1e3) : Math.round(value);
587
+ }
588
+ if (typeof value === "string" && value.trim().length > 0) {
589
+ const parsed = Date.parse(value);
590
+ return Number.isFinite(parsed) ? parsed : null;
591
+ }
592
+ return null;
593
+ }
594
+ function rawWireCode(raw) {
595
+ for (const scope of candidateScopes(raw)) {
596
+ const code = scope["code"];
597
+ if (typeof code === "string" && code.length > 0) return code;
598
+ }
599
+ return null;
600
+ }
601
+ function isRecord(value) {
602
+ return typeof value === "object" && value !== null;
603
+ }
604
+ async function resolveDeviceAuth(auth) {
605
+ if (auth.mode === "anonymous") {
606
+ return {
607
+ mode: "anonymous",
608
+ publishableKey: auth.publishableKey,
609
+ userRef: auth.userRef,
610
+ ...auth.sessionId ? { sessionId: auth.sessionId } : {}
611
+ };
612
+ }
613
+ return {
614
+ mode: "personalized",
615
+ token: await auth.identity.currentToken(),
616
+ userRef: auth.userRef,
617
+ ...auth.sessionId ? { sessionId: auth.sessionId } : {}
618
+ };
619
+ }
620
+ function boundedSignal(ms, timers) {
621
+ const ctrl = new AbortController();
622
+ const handle = timers.setTimeout(() => ctrl.abort(), ms);
623
+ return { signal: ctrl.signal, cancel: () => timers.clearTimeout(handle) };
624
+ }
625
+ function mergeSignals(deadline, caller) {
626
+ const noop = () => void 0;
627
+ if (!caller) return { signal: deadline, dispose: noop };
628
+ const ctrl = new AbortController();
629
+ if (deadline.aborted || caller.aborted) {
630
+ ctrl.abort();
631
+ return { signal: ctrl.signal, dispose: noop };
632
+ }
633
+ const onAbort = () => ctrl.abort();
634
+ deadline.addEventListener("abort", onAbort, { once: true });
635
+ caller.addEventListener("abort", onAbort, { once: true });
636
+ return {
637
+ signal: ctrl.signal,
638
+ dispose: () => {
639
+ deadline.removeEventListener("abort", onAbort);
640
+ caller.removeEventListener("abort", onAbort);
641
+ }
642
+ };
643
+ }
644
+ function delayAbortable(ms, timers, signal) {
645
+ if (ms <= 0 || signal?.aborted === true) return Promise.resolve();
646
+ return new Promise((resolve) => {
647
+ const handle = timers.setTimeout(() => {
648
+ signal?.removeEventListener("abort", onAbort);
649
+ resolve();
650
+ }, ms);
651
+ const onAbort = () => {
652
+ timers.clearTimeout(handle);
653
+ resolve();
654
+ };
655
+ signal?.addEventListener("abort", onAbort, { once: true });
656
+ });
657
+ }
658
+
659
+ // src/core/ports/TelemetryPort.ts
660
+ var noopTelemetry = Object.freeze({
661
+ track() {
662
+ },
663
+ trackExpectedFailure() {
664
+ }
665
+ });
666
+ function fileHandleFromMedia(source) {
667
+ const handle = {
668
+ uri: source.uri,
669
+ mimeType: source.mimeType
670
+ };
671
+ const size = mediaByteSize(source);
672
+ if (size !== null) handle.sizeBytes = size;
673
+ return Object.freeze(handle);
674
+ }
675
+ function mediaByteSize(source) {
676
+ const candidate = source.byteSize ?? source.sizeBytes;
677
+ return typeof candidate === "number" && Number.isFinite(candidate) && candidate >= 0 ? candidate : null;
678
+ }
679
+ function captureOptionsFor(mode, maxDurationSeconds) {
680
+ return maxDurationSeconds === void 0 ? Object.freeze({ mode }) : Object.freeze({ mode, maxDurationSeconds });
681
+ }
682
+ function isCaptureAvailable(camera) {
683
+ return camera != null && camera.isAvailable === true;
684
+ }
685
+ var defaultTimers = Object.freeze({
686
+ setTimeout: (handler, ms) => setTimeout(handler, ms),
687
+ clearTimeout: (handle) => clearTimeout(handle),
688
+ now: () => Date.now()
689
+ });
690
+ function delayAbortable2(ms, signal, timers) {
691
+ return new Promise((resolve) => {
692
+ if (signal.aborted) {
693
+ resolve();
694
+ return;
695
+ }
696
+ const holder = { handle: void 0 };
697
+ const done = () => {
698
+ timers.clearTimeout(holder.handle);
699
+ signal.removeEventListener("abort", done);
700
+ resolve();
701
+ };
702
+ holder.handle = timers.setTimeout(done, ms);
703
+ signal.addEventListener("abort", done, { once: true });
704
+ });
705
+ }
706
+ function mergeSignals2(a, b) {
707
+ if (!b) return a;
708
+ const ctrl = new AbortController();
709
+ if (a.aborted || b.aborted) {
710
+ ctrl.abort();
711
+ return ctrl.signal;
712
+ }
713
+ const onAbort = () => ctrl.abort();
714
+ a.addEventListener("abort", onAbort, { once: true });
715
+ b.addEventListener("abort", onAbort, { once: true });
716
+ return ctrl.signal;
717
+ }
718
+ var MediaStore = class {
719
+ constructor(initial) {
720
+ this.listeners = /* @__PURE__ */ new Set();
721
+ this.epoch = 0;
722
+ this.inFlight = null;
723
+ this.snapshot = Object.freeze({ ...initial });
724
+ }
725
+ subscribe(listener) {
726
+ this.listeners.add(listener);
727
+ return () => {
728
+ this.listeners.delete(listener);
729
+ };
730
+ }
731
+ getSnapshot() {
732
+ return this.snapshot;
733
+ }
734
+ patch(partial) {
735
+ this.snapshot = Object.freeze({ ...this.snapshot, ...partial });
736
+ for (const listener of this.listeners) listener();
737
+ }
738
+ beginOperation(external) {
739
+ this.inFlight?.abort();
740
+ const ctrl = new AbortController();
741
+ this.inFlight = ctrl;
742
+ const epoch = this.epoch;
743
+ const signal = external ? mergeSignals2(ctrl.signal, external) : ctrl.signal;
744
+ return {
745
+ signal,
746
+ epoch,
747
+ settle: () => {
748
+ if (this.inFlight === ctrl) this.inFlight = null;
749
+ }
750
+ };
751
+ }
752
+ alive(epoch) {
753
+ return epoch === this.epoch;
754
+ }
755
+ /** Re-scope on user/pet switch: aborts in-flight and bumps the epoch so a late write drops. */
756
+ rescope() {
757
+ this.epoch += 1;
758
+ this.inFlight?.abort();
759
+ this.inFlight = null;
760
+ }
761
+ /** Idempotent teardown: aborts in-flight, bumps the epoch, drops every listener. */
762
+ dispose() {
763
+ this.epoch += 1;
764
+ this.inFlight?.abort();
765
+ this.inFlight = null;
766
+ this.listeners.clear();
767
+ }
768
+ };
769
+
770
+ // src/client/text.ts
771
+ function hasLoneSurrogate(value) {
772
+ for (let i = 0; i < value.length; i += 1) {
773
+ const code = value.charCodeAt(i);
774
+ if (code >= 55296 && code <= 56319) {
775
+ const low = value.charCodeAt(i + 1);
776
+ if (!(low >= 56320 && low <= 57343)) return true;
777
+ i += 1;
778
+ } else if (code >= 56320 && code <= 57343) {
779
+ return true;
780
+ }
781
+ }
782
+ return false;
783
+ }
784
+
785
+ // src/core/media/projection.ts
786
+ var CONSUMER_SAFE_DETECTION_KEYS = Object.freeze([
787
+ "primary_label",
788
+ "primary_confidence",
789
+ "subtype_label",
790
+ "subtype_display",
791
+ "subtype_confidence",
792
+ "risk_tier",
793
+ "confidence_tier",
794
+ "copy_short",
795
+ "disease_name",
796
+ "disease_framing",
797
+ "model_version",
798
+ "skin_v2",
799
+ "eye_v2",
800
+ "llm_checkup"
801
+ ]);
802
+ var OPERATOR_INTERNAL_KEYS = Object.freeze([
803
+ "decision_audit",
804
+ "decision_thresholds",
805
+ "per_class_auroc",
806
+ "ood_layers",
807
+ "gate1_score",
808
+ "possible_conditions",
809
+ "top_class"
810
+ ]);
811
+ var BOOLEAN_KEYS = /* @__PURE__ */ new Set(["skin_v2", "eye_v2", "llm_checkup"]);
812
+ var CONFIDENCE_KEYS = /* @__PURE__ */ new Set(["primary_confidence", "subtype_confidence"]);
813
+ var RISK_TIER_VALUES = /* @__PURE__ */ new Set(["low_risk", "concern", "uncertain"]);
814
+ var CONFIDENCE_TIER_VALUES = /* @__PURE__ */ new Set(["possible", "probable"]);
815
+ var STRING_LIMITS = Object.freeze({
816
+ primary_label: 64,
817
+ subtype_label: 64,
818
+ subtype_display: 128,
819
+ copy_short: 512,
820
+ disease_name: 128,
821
+ disease_framing: 512,
822
+ model_version: 64
823
+ });
824
+ function projectDetectionMetadata(raw) {
825
+ const source = isRecord2(raw) ? raw : {};
826
+ const out = {};
827
+ for (const key of CONSUMER_SAFE_DETECTION_KEYS) {
828
+ if (!(key in source)) continue;
829
+ const value = source[key];
830
+ const accepted = acceptKey(key, value);
831
+ if (accepted !== DROP) out[key] = accepted;
832
+ }
833
+ let dropped = 0;
834
+ for (const key of OPERATOR_INTERNAL_KEYS) {
835
+ if (key in source) dropped += 1;
836
+ }
837
+ return Object.freeze({ metadata: Object.freeze(out), droppedOperatorKeys: dropped });
838
+ }
839
+ var DROP = /* @__PURE__ */ Symbol("drop");
840
+ function acceptKey(key, value) {
841
+ if (BOOLEAN_KEYS.has(key)) return typeof value === "boolean" ? value : DROP;
842
+ if (CONFIDENCE_KEYS.has(key)) return isUnitConfidence(value) ? value : DROP;
843
+ if (key === "risk_tier") return typeof value === "string" && RISK_TIER_VALUES.has(value) ? value : DROP;
844
+ if (key === "confidence_tier") {
845
+ return typeof value === "string" && CONFIDENCE_TIER_VALUES.has(value) ? value : DROP;
846
+ }
847
+ if (typeof value !== "string") return DROP;
848
+ const limit = STRING_LIMITS[key] ?? 256;
849
+ return value.length > limit ? value.slice(0, limit) : value;
850
+ }
851
+ function isUnitConfidence(value) {
852
+ return typeof value === "number" && Number.isFinite(value) && value >= 0 && value <= 1;
853
+ }
854
+ function parseInterpretation(raw) {
855
+ if (!isRecord2(raw)) return null;
856
+ const summary = asString(raw["summary"]);
857
+ const disclaimer = asString(raw["disclaimer"]);
858
+ const recommendations = asStringList(raw["recommendations"] ?? raw["recommendation"]);
859
+ if (summary === null && disclaimer === null && recommendations.length === 0) return null;
860
+ return Object.freeze({
861
+ summary: summary ?? "",
862
+ recommendations: Object.freeze(recommendations),
863
+ disclaimer: disclaimer ?? ""
864
+ });
865
+ }
866
+ function locateDetectionMetadata(body) {
867
+ if (!isRecord2(body)) return {};
868
+ if (isRecord2(body["metadata"])) return body["metadata"];
869
+ const detections = body["detections"];
870
+ if (Array.isArray(detections) && detections.length > 0) {
871
+ const first = detections[0];
872
+ if (isRecord2(first) && isRecord2(first["metadata"])) return first["metadata"];
873
+ if (isRecord2(first)) return first;
874
+ }
875
+ return body;
876
+ }
877
+ function locateInterpretation(body) {
878
+ if (!isRecord2(body)) return null;
879
+ if (isRecord2(body["interpretation"])) return body["interpretation"];
880
+ return body;
881
+ }
882
+ function isRecord2(value) {
883
+ return typeof value === "object" && value !== null && !Array.isArray(value);
884
+ }
885
+ function asString(value) {
886
+ return typeof value === "string" && value.length > 0 ? value : null;
887
+ }
888
+ function asStringList(value) {
889
+ if (typeof value === "string") return value.length > 0 ? [value] : [];
890
+ if (!Array.isArray(value)) return [];
891
+ return value.filter((entry) => typeof entry === "string" && entry.length > 0);
892
+ }
893
+ function asUnitNumber(value) {
894
+ return isUnitConfidence(value) ? value : null;
895
+ }
896
+ function asFiniteNumber(value) {
897
+ return typeof value === "number" && Number.isFinite(value) ? value : null;
898
+ }
899
+
900
+ // src/core/media/pipeline.ts
901
+ var ENDPOINTS = Object.freeze({
902
+ initiate: "/widget/v1/uploads/initiate",
903
+ precheck: "/widget/v1/photo/precheck",
904
+ photoAnalyze: "/widget/v1/photo/analyze",
905
+ videoAnalyze: "/widget/v1/video/analyze",
906
+ // `jobId` arrives from the WIRE, so it is not under this SDK's control, and `encodeURIComponent` throws
907
+ // URIError on a lone surrogate. Returning null lets the caller settle instead of throwing out of the
908
+ // poller. These routes are dark today, which is exactly why the guard goes in now: it costs one line and
909
+ // the gap re-opens silently the moment they land.
910
+ job: (jobId) => hasLoneSurrogate(jobId) ? null : `/widget/v1/analysis/jobs/${encodeURIComponent(jobId)}`
911
+ });
912
+ function brandJobId(raw) {
913
+ return raw;
914
+ }
915
+ async function initiateUpload(funnel, params) {
916
+ const body = { purpose: params.purpose, content_type: params.contentType };
917
+ if (params.byteSize !== null) body.byte_size = params.byteSize;
918
+ const req = {
919
+ method: "POST",
920
+ path: ENDPOINTS.initiate,
921
+ body,
922
+ ...params.signal ? { signal: params.signal } : {}
923
+ };
924
+ const res = await funnel.send("media.initiateUpload", req);
925
+ if (!res.ok) return err(res.error);
926
+ const policy = parsePresigned(res.value);
927
+ if (policy === null) return err(makeEverfurError("mediaUploadFailed", { retryable: false }));
928
+ return ok(policy);
929
+ }
930
+ function parsePresigned(raw) {
931
+ if (!isRecord2(raw)) return null;
932
+ const url = asString(raw["url"]);
933
+ const s3Key = asString(raw["s3_key"]);
934
+ if (url === null || s3Key === null) return null;
935
+ const fieldsRaw = raw["fields"];
936
+ const fields = {};
937
+ if (isRecord2(fieldsRaw)) {
938
+ for (const [key, value] of Object.entries(fieldsRaw)) {
939
+ if (typeof value === "string") fields[key] = value;
940
+ }
941
+ }
942
+ return Object.freeze({
943
+ url,
944
+ fields: Object.freeze(fields),
945
+ s3Key,
946
+ expiresAt: asFiniteNumber(raw["expires_at"])
947
+ });
948
+ }
949
+ async function stageUpload(upload, source, policy, idempotencyKey, signal) {
950
+ try {
951
+ await upload.presignedPut(fileHandleFromMedia(source), {
952
+ target: policy,
953
+ idempotencyKey,
954
+ ...signal ? { signal } : {}
955
+ });
956
+ return ok(void 0);
957
+ } catch {
958
+ return err(makeEverfurError("mediaUploadFailed", { retryable: false }));
959
+ }
960
+ }
961
+ async function runPrecheck(funnel, params) {
962
+ const req = {
963
+ method: "POST",
964
+ path: ENDPOINTS.precheck,
965
+ body: { s3_key: params.s3Key, type: params.type },
966
+ ...params.signal ? { signal: params.signal } : {}
967
+ };
968
+ const res = await funnel.send("media.precheck", req);
969
+ if (!res.ok) return { verdict: "proceed", reasonCodes: [], precheckToken: null };
970
+ return parsePrecheck(res.value);
971
+ }
972
+ function parsePrecheck(raw) {
973
+ if (!isRecord2(raw)) return { verdict: "proceed", reasonCodes: [], precheckToken: null };
974
+ const verdictRaw = asString(raw["verdict"]);
975
+ const verdict = verdictRaw === "retake" || verdictRaw === "reject" ? verdictRaw : "proceed";
976
+ const reasonCodes = Array.isArray(raw["reason_codes"]) ? raw["reason_codes"].filter((c) => typeof c === "string") : [];
977
+ return Object.freeze({
978
+ verdict,
979
+ reasonCodes: Object.freeze(reasonCodes),
980
+ precheckToken: asString(raw["precheck_token"])
981
+ });
982
+ }
983
+ async function submitAnalyze(funnel, path, body, detectGate, signal) {
984
+ const req = {
985
+ method: "POST",
986
+ path,
987
+ body,
988
+ ...signal ? { signal } : {}
989
+ };
990
+ const res = await funnel.send("media.analyze", req);
991
+ if (res.ok) {
992
+ const job = parseAsyncJob(res.value);
993
+ return job !== null ? { kind: "async", job } : { kind: "sync", body: res.value };
994
+ }
995
+ const gate = detectGate(res.error.httpStatus, res.error);
996
+ if (gate !== null) return { kind: "gate", gate };
997
+ return { kind: "error", error: res.error };
998
+ }
999
+ function parseAsyncJob(raw) {
1000
+ if (!isRecord2(raw)) return null;
1001
+ const jobId = asString(raw["job_id"]);
1002
+ if (jobId === null) return null;
1003
+ const status = asString(raw["status"]);
1004
+ if (status !== null && isTerminalStatus(status)) return null;
1005
+ return Object.freeze({
1006
+ jobId: brandJobId(jobId),
1007
+ estimatedSeconds: asFiniteNumber(raw["estimated_completion_seconds"])
1008
+ });
1009
+ }
1010
+ var POLL_FIRST_DELAY_MS = 2e3;
1011
+ var POLL_MAX_DELAY_MS = 5e3;
1012
+ var POLL_BUDGET_MS = 9e4;
1013
+ async function pollJob(funnel, jobId, deps) {
1014
+ const { timers, signal, alive } = deps;
1015
+ const start = timers.now();
1016
+ const budget = Math.max(POLL_BUDGET_MS, (deps.estimatedSeconds ?? 0) * 1e3);
1017
+ let delay = POLL_FIRST_DELAY_MS;
1018
+ for (; ; ) {
1019
+ if (signal.aborted || !alive()) return { kind: "aborted" };
1020
+ await delayAbortable2(delay, signal, timers);
1021
+ if (signal.aborted || !alive()) return { kind: "aborted" };
1022
+ if (timers.now() - start > budget) return { kind: "timeout" };
1023
+ const path = ENDPOINTS.job(jobId);
1024
+ if (path === null) return { kind: "notFound" };
1025
+ const res = await funnel.send(
1026
+ "media.pollJob",
1027
+ { method: "GET", path, ...signal ? { signal } : {} },
1028
+ { maxAttempts: 1 }
1029
+ );
1030
+ if (signal.aborted || !alive()) return { kind: "aborted" };
1031
+ if (!res.ok) {
1032
+ if (res.error.httpStatus === 404) return { kind: "notFound" };
1033
+ delay = Math.min(POLL_MAX_DELAY_MS, delay + 1e3);
1034
+ continue;
1035
+ }
1036
+ const status = jobStatusOf(res.value);
1037
+ if (status === "COMPLETED") return { kind: "complete", body: res.value };
1038
+ if (status === "FAILED") return { kind: "failed", error: jobFailureError(res.value) };
1039
+ delay = Math.min(POLL_MAX_DELAY_MS, delay + 1e3);
1040
+ }
1041
+ }
1042
+ function jobStatusOf(body) {
1043
+ if (!isRecord2(body)) return "PROCESSING";
1044
+ return (asString(body["status"]) ?? "PROCESSING").toUpperCase();
1045
+ }
1046
+ function isTerminalStatus(status) {
1047
+ const upper = status.toUpperCase();
1048
+ return upper === "COMPLETED" || upper === "FAILED";
1049
+ }
1050
+ function jobFailureError(body) {
1051
+ const wire = isRecord2(body) ? asString(body["error"]) ?? asString(body["error_code"]) : null;
1052
+ return makeEverfurError("internalError", { retryable: false, ...wire ? { wireMessage: wire } : {} });
1053
+ }
1054
+ function detectPhotoGate(httpStatus, _error) {
1055
+ if (httpStatus === 422) return { kind: "species_unsupported", species: "cat" };
1056
+ if (httpStatus === 400) return { kind: "pet_context_required" };
1057
+ return null;
1058
+ }
1059
+ function analyzeBody(s3Key, extra) {
1060
+ const body = { s3_key: s3Key };
1061
+ if (extra.type !== void 0) body.type = extra.type;
1062
+ if (extra.petRef != null) body.pet_id = extra.petRef;
1063
+ if (extra.precheckToken != null) body.precheck_token = extra.precheckToken;
1064
+ return body;
1065
+ }
1066
+
1067
+ // src/core/photo/PhotoController.ts
1068
+ var ACCEPTED = Object.freeze({ kind: "accepted" });
1069
+ function createPhotoController(deps) {
1070
+ return new PhotoController(deps);
1071
+ }
1072
+ var PhotoController = class extends MediaStore {
1073
+ constructor(deps) {
1074
+ super({
1075
+ status: "idle",
1076
+ region: deps.region ?? "skin",
1077
+ result: null,
1078
+ gate: ACCEPTED,
1079
+ error: null,
1080
+ isCaptureAvailable: isCaptureAvailable(deps.camera)
1081
+ });
1082
+ this.funnel = deps.funnel ?? createRequestFunnel({
1083
+ auth: deps.auth,
1084
+ ...deps.errorPolicy ? { errorPolicy: deps.errorPolicy } : {}
1085
+ });
1086
+ this.camera = deps.camera;
1087
+ this.upload = deps.upload;
1088
+ this.telemetry = deps.telemetry ?? noopTelemetry;
1089
+ this.timers = deps.timers ?? defaultTimers;
1090
+ this.makeIdempotencyKey = deps.makeIdempotencyKey ?? defaultIdempotencyFactory();
1091
+ }
1092
+ /** Open the CameraPort (photo), then analyze. No-op when capture is unavailable; a cancel returns to idle. */
1093
+ async capture(region, opts) {
1094
+ if (!isCaptureAvailable(this.camera)) {
1095
+ return err(makeEverfurError("unknown", { retryable: false }));
1096
+ }
1097
+ let source;
1098
+ try {
1099
+ source = await this.camera.capture(captureOptionsFor("photo"));
1100
+ } catch {
1101
+ if (this.snapshot.status !== "idle") this.patch({ status: "idle" });
1102
+ return err(makeEverfurError("unknown", { retryable: false }));
1103
+ }
1104
+ return this.analyze(source, region, opts);
1105
+ }
1106
+ /**
1107
+ * Server enforces the species gate (§6). The SDK NEVER runs a model and NEVER guesses species. `petRef` is
1108
+ * REQUIRED so a skin/eye request always carries pet context (§6.3 client invariant / PAR-07).
1109
+ */
1110
+ async analyze(source, region, opts) {
1111
+ const op = this.beginOperation(opts.signal);
1112
+ const idempotencyKey = this.makeIdempotencyKey();
1113
+ const startedAt = this.timers.now();
1114
+ this.patch({ status: "capturing", region, error: null, result: null, gate: ACCEPTED });
1115
+ try {
1116
+ const initiated = await initiateUpload(this.funnel, {
1117
+ purpose: "skin_scan",
1118
+ contentType: source.mimeType,
1119
+ byteSize: mediaByteSize(source),
1120
+ signal: op.signal
1121
+ });
1122
+ if (op.signal.aborted || !this.alive(op.epoch)) return abortedResult();
1123
+ if (!initiated.ok) return this.fail(op, initiated.error);
1124
+ const staged = await stageUpload(this.upload, source, initiated.value, idempotencyKey, op.signal);
1125
+ if (op.signal.aborted || !this.alive(op.epoch)) return abortedResult();
1126
+ if (!staged.ok) return this.fail(op, staged.error);
1127
+ const precheck = await runPrecheck(this.funnel, {
1128
+ s3Key: initiated.value.s3Key,
1129
+ type: region,
1130
+ signal: op.signal
1131
+ });
1132
+ if (op.signal.aborted || !this.alive(op.epoch)) return abortedResult();
1133
+ if (precheck.verdict !== "proceed") {
1134
+ return this.gateRetake(op, region, precheck.reasonCodes);
1135
+ }
1136
+ this.patch({ status: "analyzing" });
1137
+ const outcome = await submitAnalyze(
1138
+ this.funnel,
1139
+ ENDPOINTS.photoAnalyze,
1140
+ analyzeBody(initiated.value.s3Key, {
1141
+ type: region,
1142
+ petRef: opts.petRef,
1143
+ precheckToken: precheck.precheckToken
1144
+ }),
1145
+ detectPhotoGate,
1146
+ op.signal
1147
+ );
1148
+ if (op.signal.aborted || !this.alive(op.epoch)) return abortedResult();
1149
+ switch (outcome.kind) {
1150
+ case "error":
1151
+ return this.fail(op, outcome.error);
1152
+ case "gate":
1153
+ return this.gateDomain(op, region, outcome.gate);
1154
+ case "sync":
1155
+ return this.complete(op, outcome.body, region, null, startedAt);
1156
+ case "async": {
1157
+ const poll = await pollJob(this.funnel, outcome.job.jobId, {
1158
+ timers: this.timers,
1159
+ signal: op.signal,
1160
+ alive: () => this.alive(op.epoch),
1161
+ estimatedSeconds: outcome.job.estimatedSeconds
1162
+ });
1163
+ if (op.signal.aborted || !this.alive(op.epoch)) return abortedResult();
1164
+ switch (poll.kind) {
1165
+ case "aborted":
1166
+ return abortedResult();
1167
+ case "complete":
1168
+ return this.complete(op, poll.body, region, outcome.job.jobId, startedAt);
1169
+ case "failed":
1170
+ return this.fail(op, poll.error);
1171
+ case "timeout":
1172
+ return this.fail(op, makeEverfurError("streamTimeout", { retryable: true }));
1173
+ case "notFound":
1174
+ return this.fail(op, makeEverfurError("conversationNotFound", { retryable: false, httpStatus: 404 }));
1175
+ default:
1176
+ return this.fail(op, makeEverfurError("internalError", { retryable: false }));
1177
+ }
1178
+ }
1179
+ default:
1180
+ return this.fail(op, makeEverfurError("internalError", { retryable: false }));
1181
+ }
1182
+ } finally {
1183
+ op.settle();
1184
+ }
1185
+ }
1186
+ /** Clear the gate/result back to idle for a retake. */
1187
+ reset() {
1188
+ this.inFlight?.abort();
1189
+ this.inFlight = null;
1190
+ this.patch({ status: "idle", result: null, gate: ACCEPTED, error: null });
1191
+ }
1192
+ // ---- terminal transitions ---------------------------------------------
1193
+ complete(op, body, region, jobId, startedAt) {
1194
+ if (!this.alive(op.epoch)) return abortedResult();
1195
+ const mapped = mapPhotoResult(body, region, jobId);
1196
+ if (mapped.droppedOperatorKeys > 0) {
1197
+ this.telemetry.track("analysis.metadata_leak_guard", { droppedKeyCount: mapped.droppedOperatorKeys });
1198
+ }
1199
+ this.patch({ status: "complete", result: mapped.result, gate: ACCEPTED, error: null });
1200
+ this.telemetry.track("analysis.species_gate", { outcome: "accepted", region });
1201
+ this.telemetry.track("analysis.result", {
1202
+ capability: "photo",
1203
+ region,
1204
+ riskTier: mapped.result.riskTier ?? "",
1205
+ confidenceTier: mapped.result.confidenceTier ?? "",
1206
+ modelVersion: mapped.result.modelVersion ?? "",
1207
+ timeToResultMs: this.timers.now() - startedAt
1208
+ });
1209
+ return ok(mapped.result);
1210
+ }
1211
+ gateDomain(op, region, gate) {
1212
+ if (!this.alive(op.epoch)) return abortedResult();
1213
+ const outcome = gate.kind === "species_unsupported" ? Object.freeze({ kind: "species_unsupported", species: "cat" }) : Object.freeze({ kind: "pet_context_required" });
1214
+ this.patch({ status: "idle", gate: outcome, error: null, result: null });
1215
+ this.telemetry.track("analysis.species_gate", {
1216
+ outcome: gate.kind,
1217
+ region,
1218
+ ...gate.kind === "species_unsupported" ? { species: "cat" } : {}
1219
+ });
1220
+ return err(makeEverfurError("unknown", { retryable: false }));
1221
+ }
1222
+ gateRetake(op, region, reasons) {
1223
+ if (!this.alive(op.epoch)) return abortedResult();
1224
+ this.patch({
1225
+ status: "idle",
1226
+ gate: Object.freeze({ kind: "retake", reasons: Object.freeze([...reasons]) }),
1227
+ error: null,
1228
+ result: null
1229
+ });
1230
+ this.telemetry.track("analysis.quality_gate", { usable: false, reasons });
1231
+ const outcome = reasons.includes("wrong_species") ? "species_unsupported" : "retake";
1232
+ this.telemetry.track("analysis.species_gate", { outcome, region });
1233
+ return err(makeEverfurError("unknown", { retryable: false }));
1234
+ }
1235
+ fail(op, error) {
1236
+ if (!this.alive(op.epoch)) return abortedResult();
1237
+ this.patch({ status: "error", error, gate: ACCEPTED });
1238
+ this.telemetry.trackExpectedFailure("analysis.error", {
1239
+ code: error.code,
1240
+ ...error.httpStatus !== void 0 ? { httpStatus: error.httpStatus } : {}
1241
+ });
1242
+ return err(error);
1243
+ }
1244
+ };
1245
+ function mapPhotoResult(body, region, jobId) {
1246
+ const projection = projectDetectionMetadata(locateDetectionMetadata(body));
1247
+ const meta = projection.metadata;
1248
+ const interpretation = parseInterpretation(locateInterpretation(body));
1249
+ const result = Object.freeze({
1250
+ jobId,
1251
+ analysisType: region,
1252
+ primaryLabel: asString(meta["primary_label"]) ?? "Uncertain",
1253
+ riskTier: asRiskTier(meta["risk_tier"]),
1254
+ confidence: asUnitNumber(meta["primary_confidence"]),
1255
+ subtypeDisplay: asString(meta["subtype_display"]),
1256
+ confidenceTier: asConfidenceTier(meta["confidence_tier"]),
1257
+ diseaseName: asString(meta["disease_name"]),
1258
+ diseaseFraming: asString(meta["disease_framing"]),
1259
+ copyShort: asString(meta["copy_short"]),
1260
+ interpretation,
1261
+ modelVersion: asString(meta["model_version"]) ?? (isRecord2(body) ? asString(body["model_version"]) : null)
1262
+ });
1263
+ return { result, droppedOperatorKeys: projection.droppedOperatorKeys };
1264
+ }
1265
+ function asRiskTier(value) {
1266
+ return value === "low_risk" || value === "concern" || value === "uncertain" ? value : null;
1267
+ }
1268
+ function asConfidenceTier(value) {
1269
+ return value === "possible" || value === "probable" ? value : null;
1270
+ }
1271
+ function abortedResult() {
1272
+ return err(makeEverfurError("unknown", { retryable: false }));
1273
+ }
1274
+ function defaultIdempotencyFactory() {
1275
+ let counter = 0;
1276
+ return () => `photo-analyze-${Date.now().toString(36)}-${(counter++).toString(36)}-${Math.random().toString(36).slice(2, 10)}`;
1277
+ }
1278
+
1279
+ // src/client/entitlements/resolve.ts
1280
+ var REQUIRES = Object.freeze({
1281
+ chat: Object.freeze(["chat.message.create"]),
1282
+ records: Object.freeze(["records.upload.create", "records.record.read"]),
1283
+ video: Object.freeze(["video.gait.execute"]),
1284
+ photo: Object.freeze(["photo.checkup.execute"]),
1285
+ animations: Object.freeze(["animations.state.read"])
1286
+ });
1287
+ function requires(name) {
1288
+ return REQUIRES[name];
1289
+ }
1290
+ function decideCapability(name, decisions, opts) {
1291
+ if (opts?.isPending === true) {
1292
+ return freezeDecision({ name, enabled: false, isPending: true, limits: {} });
1293
+ }
1294
+ const keys = requires(name);
1295
+ const byResource = /* @__PURE__ */ new Map();
1296
+ for (const decision of decisions) byResource.set(decision.resource, decision);
1297
+ const limits = mergeLimits(keys, byResource);
1298
+ const missing = keys.filter((key) => byResource.get(key)?.granted !== true);
1299
+ if (missing.length === 0) {
1300
+ return freezeDecision({ name, enabled: true, isPending: false, limits });
1301
+ }
1302
+ return freezeDecision({
1303
+ name,
1304
+ enabled: false,
1305
+ isPending: false,
1306
+ limits,
1307
+ disabled: disabledFor(keys, byResource)
1308
+ });
1309
+ }
1310
+ function mergeLimits(keys, byResource) {
1311
+ const out = {};
1312
+ for (const key of keys) {
1313
+ const decisionLimits = byResource.get(key)?.limits;
1314
+ if (!decisionLimits) continue;
1315
+ for (const [limitKey, limitValue] of Object.entries(decisionLimits)) {
1316
+ const existing = out[limitKey];
1317
+ out[limitKey] = existing === void 0 ? limitValue : Math.min(existing, limitValue);
1318
+ }
1319
+ }
1320
+ return out;
1321
+ }
1322
+ function disabledFor(keys, byResource) {
1323
+ for (const key of keys) {
1324
+ const explicit = byResource.get(key)?.disabled;
1325
+ if (explicit) {
1326
+ return Object.freeze({
1327
+ reason: explicit.reason,
1328
+ level: explicit.level,
1329
+ recoverable: explicit.recoverable
1330
+ });
1331
+ }
1332
+ }
1333
+ return Object.freeze({
1334
+ reason: userFacingError("accessDenied"),
1335
+ level: "user_entitlement",
1336
+ recoverable: false
1337
+ });
1338
+ }
1339
+ function freezeDecision(d) {
1340
+ const base = {
1341
+ name: d.name,
1342
+ enabled: d.enabled,
1343
+ isPending: d.isPending,
1344
+ limits: Object.freeze({ ...d.limits })
1345
+ };
1346
+ if (d.disabled !== void 0) base.disabled = d.disabled;
1347
+ return Object.freeze(base);
1348
+ }
1349
+
1350
+ // src/client/theme/tokens.ts
1351
+ function deepFreeze(value) {
1352
+ if (value !== null && typeof value === "object" && !Object.isFrozen(value)) {
1353
+ Object.freeze(value);
1354
+ for (const key of Object.keys(value)) {
1355
+ deepFreeze(value[key]);
1356
+ }
1357
+ }
1358
+ return value;
1359
+ }
1360
+ var SPACE = { xs: 4, sm: 8, md: 12, lg: 16, xl: 24, xxl: 32 };
1361
+ var RADIUS = { tile: 5, xs: 6, sm: 10, md: 14, lg: 20, xl: 28, pill: 500 };
1362
+ var TYPE_SIZE = {
1363
+ nano: 8,
1364
+ small: 9,
1365
+ micro: 10,
1366
+ tiny: 11,
1367
+ caption: 12,
1368
+ bodyTight: 13,
1369
+ body: 14,
1370
+ subtitle: 16,
1371
+ heading: 18,
1372
+ verdict: 24
1373
+ };
1374
+ var LINE_HEIGHT = { tight: 1.15, snug: 1.3, normal: 1.4, relaxed: 1.55 };
1375
+ var WEIGHT = { regular: "400", medium: "500", bold: "700" };
1376
+ var LETTER_SPACING = {
1377
+ eyebrow: 1,
1378
+ monoWide: 0.9,
1379
+ headerBrand: -0.42,
1380
+ tight: -0.35
1381
+ };
1382
+ function baseType() {
1383
+ return {
1384
+ family: "System",
1385
+ mono: "monospace",
1386
+ fontUrl: null,
1387
+ size: TYPE_SIZE,
1388
+ lineHeight: LINE_HEIGHT,
1389
+ weight: WEIGHT,
1390
+ letterSpacing: LETTER_SPACING
1391
+ };
1392
+ }
1393
+ var MOTION = {
1394
+ duration: { instant: 80, fast: 140, normal: 220, slow: 320 },
1395
+ spring: { gentle: { damping: 18, stiffness: 200 } },
1396
+ easing: { standard: "cubic-bezier(0.4, 0, 0.2, 1)" },
1397
+ reducedMotion: false
1398
+ };
1399
+ var LIGHT_COLOR = {
1400
+ brand: "#10462E",
1401
+ brandSoft: "rgba(16,70,46,0.10)",
1402
+ brandSofter: "rgba(16,70,46,0.15)",
1403
+ brandBorder: "rgba(16,70,46,0.18)",
1404
+ borderHairlineGreen: "rgba(16,70,46,0.25)",
1405
+ surface: "#FFFFFF",
1406
+ surfaceCream: "#FDFBF8",
1407
+ surfaceSubtle: "#EFE9E3",
1408
+ background: "#FFFFFF",
1409
+ borderRingCream: "#D8D2C8",
1410
+ text: {
1411
+ primary: "#111111",
1412
+ secondary: "#0E462E",
1413
+ muted: "#6E6660",
1414
+ placeholder: "rgba(0,0,0,0.30)",
1415
+ onBrand: "#FFFFFF",
1416
+ metaCool: "#3D3D3D"
1417
+ },
1418
+ primary: "#10462E",
1419
+ onPrimary: "#FFFFFF",
1420
+ accent: "#10462E",
1421
+ onAccent: "#FFFFFF",
1422
+ accentEdge: "#07C168",
1423
+ success: "#07C168",
1424
+ danger: "#B91C1C",
1425
+ errorRed: "#FF1B00",
1426
+ warningStrong: "#A45610",
1427
+ cautionAccent: "#D9821D",
1428
+ riskConcern: "#EFA700",
1429
+ badgeBgPositive: "rgba(7,193,104,0.12)",
1430
+ badgeBgCaution: "rgba(217,130,29,0.14)",
1431
+ badgeBgCritical: "rgba(185,28,28,0.12)",
1432
+ badgeBgNeutral: "rgba(110,102,96,0.12)",
1433
+ bubbleUser: "#10462E",
1434
+ bubbleAssistant: "#FFFFFF",
1435
+ skeleton: "#EFE9E3",
1436
+ scanButtonPink: "#FFC3BC",
1437
+ checkupCardLowRiskBg: "rgba(7,193,104,0.10)",
1438
+ checkupCardConcernBg: "rgba(239,167,0,0.10)"
1439
+ };
1440
+ var EVERFUR_LIGHT = deepFreeze({
1441
+ brightness: "light",
1442
+ meta: { displayName: "Everfur", logoUrl: null, placeholder: null, hidePoweredBy: false },
1443
+ color: LIGHT_COLOR,
1444
+ space: SPACE,
1445
+ radius: RADIUS,
1446
+ type: baseType(),
1447
+ motion: MOTION
1448
+ });
1449
+ var DARK_COLOR = {
1450
+ brand: "#6BD39A",
1451
+ brandSoft: "rgba(107,211,154,0.12)",
1452
+ brandSofter: "rgba(107,211,154,0.18)",
1453
+ brandBorder: "rgba(107,211,154,0.22)",
1454
+ borderHairlineGreen: "rgba(107,211,154,0.28)",
1455
+ surface: "#1C1F23",
1456
+ surfaceCream: "#23272C",
1457
+ surfaceSubtle: "#23272C",
1458
+ background: "#15171A",
1459
+ borderRingCream: "#3A3F45",
1460
+ text: {
1461
+ primary: "#F5F3F0",
1462
+ secondary: "#A9E4C4",
1463
+ muted: "#9A938C",
1464
+ placeholder: "rgba(255,255,255,0.35)",
1465
+ onBrand: "#0E1F17",
1466
+ metaCool: "#C9C9C9"
1467
+ },
1468
+ primary: "#6BD39A",
1469
+ onPrimary: "#0E1F17",
1470
+ accent: "#6BD39A",
1471
+ onAccent: "#0E1F17",
1472
+ accentEdge: "#34D888",
1473
+ success: "#07C168",
1474
+ danger: "#B91C1C",
1475
+ errorRed: "#FF1B00",
1476
+ warningStrong: "#A45610",
1477
+ cautionAccent: "#D9821D",
1478
+ riskConcern: "#EFA700",
1479
+ badgeBgPositive: "rgba(7,193,104,0.18)",
1480
+ badgeBgCaution: "rgba(217,130,29,0.20)",
1481
+ badgeBgCritical: "rgba(185,28,28,0.22)",
1482
+ badgeBgNeutral: "rgba(255,255,255,0.10)",
1483
+ bubbleUser: "#6BD39A",
1484
+ bubbleAssistant: "#1C1F23",
1485
+ skeleton: "#23272C",
1486
+ scanButtonPink: "#FFC3BC",
1487
+ checkupCardLowRiskBg: "rgba(7,193,104,0.16)",
1488
+ checkupCardConcernBg: "rgba(239,167,0,0.16)"
1489
+ };
1490
+ deepFreeze({
1491
+ brightness: "dark",
1492
+ meta: { displayName: "Everfur", logoUrl: null, placeholder: null, hidePoweredBy: false },
1493
+ color: DARK_COLOR,
1494
+ space: SPACE,
1495
+ radius: RADIUS,
1496
+ type: baseType(),
1497
+ motion: MOTION
1498
+ });
1499
+ var EVERFUR_THEME_CONTEXT_SYMBOL = /* @__PURE__ */ Symbol.for("@everfur/sdk#EverfurThemeContext@v1");
1500
+ var globalThemeHost = globalThis;
1501
+ var EverfurThemeContext = globalThemeHost[EVERFUR_THEME_CONTEXT_SYMBOL] ?? (globalThemeHost[EVERFUR_THEME_CONTEXT_SYMBOL] = react.createContext(EVERFUR_LIGHT));
1502
+ EverfurThemeContext.displayName ??= "EverfurThemeContext";
1503
+ function useEverfurTheme() {
1504
+ return react.useContext(EverfurThemeContext);
1505
+ }
1506
+
1507
+ // src/rn/facade.ts
1508
+ var EVERFUR_CONTEXT_SYMBOL = /* @__PURE__ */ Symbol.for("@everfur/sdk#EverfurContext@v1");
1509
+ var globalContextHost = globalThis;
1510
+ var EverfurContext = globalContextHost[EVERFUR_CONTEXT_SYMBOL] ?? (globalContextHost[EVERFUR_CONTEXT_SYMBOL] = react.createContext(null));
1511
+ EverfurContext.displayName ??= "EverfurContext";
1512
+ function useEverfurContext() {
1513
+ const ctx = react.useContext(EverfurContext);
1514
+ if (ctx === null) {
1515
+ throw new EverfurConfigError(
1516
+ "not-initialized",
1517
+ "Everfur hooks must be called inside <EverfurProvider>. Wrap your tree once, high."
1518
+ );
1519
+ }
1520
+ return ctx;
1521
+ }
1522
+
1523
+ // src/rn/photo/usePhoto.ts
1524
+ var BOOTSTRAP_SNAPSHOT = Object.freeze({
1525
+ status: "idle",
1526
+ region: "skin",
1527
+ result: null,
1528
+ gate: Object.freeze({ kind: "accepted" }),
1529
+ error: null,
1530
+ isCaptureAvailable: false
1531
+ });
1532
+ var NOOP_UNSUBSCRIBE = () => {
1533
+ };
1534
+ function usePhotoCheckup(opts) {
1535
+ const { runtime, userRef } = useEverfurContext();
1536
+ const petRef = opts.petRef;
1537
+ const [controller, setController] = react.useState(null);
1538
+ react.useEffect(() => {
1539
+ const { services } = runtime.registry;
1540
+ const acquired = runtime.registry.acquire(
1541
+ "photo",
1542
+ `${userRef ?? ""}|${petRef}`,
1543
+ () => createPhotoController({
1544
+ ...services.errorPolicy ? { errorPolicy: services.errorPolicy } : {},
1545
+ auth: services.authFor(userRef),
1546
+ camera: services.camera,
1547
+ upload: services.upload,
1548
+ telemetry: services.telemetry
1549
+ }),
1550
+ (controller2) => controller2.dispose()
1551
+ );
1552
+ setController(acquired);
1553
+ return () => {
1554
+ setController((current) => current === acquired ? null : current);
1555
+ runtime.registry.release(acquired);
1556
+ };
1557
+ }, [runtime, userRef, petRef]);
1558
+ const subscribe = react.useCallback(
1559
+ (onChange) => controller ? controller.subscribe(onChange) : NOOP_UNSUBSCRIBE,
1560
+ [controller]
1561
+ );
1562
+ const getSnapshot = react.useCallback(
1563
+ () => controller ? controller.getSnapshot() : BOOTSTRAP_SNAPSHOT,
1564
+ [controller]
1565
+ );
1566
+ const snapshot = react.useSyncExternalStore(subscribe, getSnapshot, getSnapshot);
1567
+ const analyze = react.useCallback(
1568
+ (source, region) => controller ? controller.analyze(source, region, { petRef }) : Promise.resolve(notReadyError()),
1569
+ [controller, petRef]
1570
+ );
1571
+ const capture = react.useCallback(
1572
+ (region) => controller ? controller.capture(region, { petRef }) : Promise.resolve(notReadyError()),
1573
+ [controller, petRef]
1574
+ );
1575
+ const reset = react.useCallback(() => {
1576
+ controller?.reset();
1577
+ }, [controller]);
1578
+ return react.useMemo(
1579
+ () => ({
1580
+ status: snapshot.status,
1581
+ region: snapshot.region,
1582
+ result: snapshot.result,
1583
+ gate: snapshot.gate,
1584
+ error: snapshot.error,
1585
+ isCaptureAvailable: snapshot.isCaptureAvailable,
1586
+ isBootstrapping: controller === null,
1587
+ analyze,
1588
+ capture,
1589
+ reset
1590
+ }),
1591
+ [snapshot, controller, analyze, capture, reset]
1592
+ );
1593
+ }
1594
+ function notReadyError() {
1595
+ return err(
1596
+ makeEverfurError("internalError", { retryable: true })
1597
+ );
1598
+ }
1599
+ function useCapability(name) {
1600
+ const { runtime } = useEverfurContext();
1601
+ const store = runtime.entitlements;
1602
+ const snapshot = react.useSyncExternalStore(
1603
+ store.subscribe,
1604
+ store.getSnapshot,
1605
+ store.getSnapshot
1606
+ );
1607
+ return react.useMemo(
1608
+ () => decideCapability(name, snapshot.decisions, { isPending: snapshot.isPending }),
1609
+ [name, snapshot]
1610
+ );
1611
+ }
1612
+ var MIN_OFFSTATE_HEIGHT = 48;
1613
+ function selectView(decision) {
1614
+ if (decision.isPending) return "pending";
1615
+ return decision.enabled ? "enabled" : "disabled";
1616
+ }
1617
+ function CapabilityGate(props) {
1618
+ const { capability, children, renderDisabled, renderPending, style } = props;
1619
+ const decision = useCapability(capability);
1620
+ const view = react.useMemo(() => selectView(decision), [decision]);
1621
+ switch (view) {
1622
+ case "enabled":
1623
+ return children;
1624
+ case "pending":
1625
+ return renderPending ? renderPending() : /* @__PURE__ */ jsxRuntime.jsx(PendingSkeleton, { capability, style });
1626
+ case "disabled":
1627
+ return renderDisabled ? renderDisabled(decision) : /* @__PURE__ */ jsxRuntime.jsx(OffState, { decision, style });
1628
+ default:
1629
+ return assertNever(view);
1630
+ }
1631
+ }
1632
+ function PendingSkeleton({
1633
+ capability,
1634
+ style
1635
+ }) {
1636
+ const theme = useEverfurTheme();
1637
+ const styles = react.useMemo(() => makeStyles(theme), [theme]);
1638
+ return /* @__PURE__ */ jsxRuntime.jsx(
1639
+ reactNative.View,
1640
+ {
1641
+ style: [styles.offstate, style],
1642
+ accessible: true,
1643
+ accessibilityState: { busy: true },
1644
+ accessibilityLabel: `Loading ${capability}`,
1645
+ children: /* @__PURE__ */ jsxRuntime.jsx(reactNative.View, { style: styles.skeletonBar })
1646
+ }
1647
+ );
1648
+ }
1649
+ function OffState({
1650
+ decision,
1651
+ style
1652
+ }) {
1653
+ const theme = useEverfurTheme();
1654
+ const styles = react.useMemo(() => makeStyles(theme), [theme]);
1655
+ const message = decision.disabled?.reason ?? "";
1656
+ return /* @__PURE__ */ jsxRuntime.jsx(
1657
+ reactNative.View,
1658
+ {
1659
+ style: [styles.offstate, style],
1660
+ accessible: true,
1661
+ accessibilityRole: "text",
1662
+ accessibilityLabel: message,
1663
+ children: message.length > 0 ? /* @__PURE__ */ jsxRuntime.jsx(reactNative.Text, { style: styles.offstateText, children: message }) : null
1664
+ }
1665
+ );
1666
+ }
1667
+ function makeStyles(theme) {
1668
+ const { color, space, radius, type } = theme;
1669
+ return reactNative.StyleSheet.create({
1670
+ // A deliberate cream card with a soft brand hairline, never a bare grey slab.
1671
+ offstate: {
1672
+ minHeight: MIN_OFFSTATE_HEIGHT,
1673
+ justifyContent: "center",
1674
+ paddingHorizontal: space.lg,
1675
+ paddingVertical: space.md,
1676
+ backgroundColor: color.surfaceCream,
1677
+ borderRadius: radius.md,
1678
+ borderWidth: reactNative.StyleSheet.hairlineWidth,
1679
+ borderColor: color.brandBorder
1680
+ },
1681
+ offstateText: {
1682
+ fontFamily: type.family,
1683
+ fontSize: type.size.body,
1684
+ lineHeight: Math.round(type.size.body * type.lineHeight.normal),
1685
+ color: color.text.muted
1686
+ },
1687
+ // A soft green shimmer bar (brand wash) that stays legible on the cream card in both light and dark,
1688
+ // where the neutral `skeleton` token would collide with the dark cream surface.
1689
+ skeletonBar: {
1690
+ height: space.md,
1691
+ borderRadius: radius.xs,
1692
+ backgroundColor: color.brandSofter
1693
+ }
1694
+ });
1695
+ }
1696
+ var CLINICAL_DISCLAIMER = Object.freeze({
1697
+ title: "For educational use only",
1698
+ body: "Everfur is for educational purposes only. It helps you track visible changes through AI checkups. It does not diagnose, treat, prescribe, or replace veterinary care. For urgent symptoms or emergencies, contact a veterinarian immediately."
1699
+ });
1700
+ function ClinicalDisclaimer(props) {
1701
+ const theme = useEverfurTheme();
1702
+ const styles = react.useMemo(() => makeStyles2(theme), [theme]);
1703
+ return /* @__PURE__ */ jsxRuntime.jsxs(
1704
+ reactNative.View,
1705
+ {
1706
+ style: [styles.container, props.style],
1707
+ accessible: true,
1708
+ accessibilityRole: "text",
1709
+ accessibilityLabel: `${CLINICAL_DISCLAIMER.title}. ${CLINICAL_DISCLAIMER.body}`,
1710
+ children: [
1711
+ /* @__PURE__ */ jsxRuntime.jsx(reactNative.Text, { style: styles.title, children: CLINICAL_DISCLAIMER.title }),
1712
+ /* @__PURE__ */ jsxRuntime.jsx(reactNative.Text, { style: styles.body, children: CLINICAL_DISCLAIMER.body })
1713
+ ]
1714
+ }
1715
+ );
1716
+ }
1717
+ function makeStyles2(theme) {
1718
+ const { color, space, type } = theme;
1719
+ return reactNative.StyleSheet.create({
1720
+ container: {
1721
+ paddingHorizontal: space.lg,
1722
+ paddingVertical: space.md,
1723
+ borderTopWidth: reactNative.StyleSheet.hairlineWidth,
1724
+ borderTopColor: color.borderHairlineGreen,
1725
+ backgroundColor: color.surfaceCream,
1726
+ gap: space.xs
1727
+ },
1728
+ title: {
1729
+ fontFamily: type.family,
1730
+ fontSize: type.size.caption,
1731
+ lineHeight: Math.round(type.size.caption * type.lineHeight.snug),
1732
+ color: color.text.secondary,
1733
+ fontWeight: type.weight.bold,
1734
+ letterSpacing: type.letterSpacing.eyebrow
1735
+ },
1736
+ body: {
1737
+ fontFamily: type.family,
1738
+ fontSize: type.size.caption,
1739
+ lineHeight: Math.round(type.size.caption * type.lineHeight.snug),
1740
+ color: color.text.muted,
1741
+ fontWeight: type.weight.regular
1742
+ }
1743
+ });
1744
+ }
1745
+ var ROTATION_PERIOD_MS = 1400;
1746
+ var REVEAL_DELAY_MS = 300;
1747
+ function AnalyzingIndicator() {
1748
+ const theme = useEverfurTheme();
1749
+ const styles = react.useMemo(() => makeStyles3(theme), [theme]);
1750
+ const reduced = theme.motion.reducedMotion;
1751
+ const [visible, setVisible] = react.useState(false);
1752
+ react.useEffect(() => {
1753
+ const id = setTimeout(() => setVisible(true), REVEAL_DELAY_MS);
1754
+ return () => clearTimeout(id);
1755
+ }, []);
1756
+ const spin = react.useRef(new reactNative.Animated.Value(0)).current;
1757
+ react.useEffect(() => {
1758
+ if (reduced || !visible) return;
1759
+ const loop = reactNative.Animated.loop(
1760
+ reactNative.Animated.timing(spin, {
1761
+ toValue: 1,
1762
+ duration: ROTATION_PERIOD_MS,
1763
+ easing: reactNative.Easing.linear,
1764
+ useNativeDriver: true
1765
+ })
1766
+ );
1767
+ loop.start();
1768
+ return () => loop.stop();
1769
+ }, [reduced, visible, spin]);
1770
+ const arcMotionStyle = reduced ? null : { transform: [{ rotate: spin.interpolate({ inputRange: [0, 1], outputRange: ["0deg", "360deg"] }) }] };
1771
+ return /* @__PURE__ */ jsxRuntime.jsx(
1772
+ reactNative.View,
1773
+ {
1774
+ style: styles.wrap,
1775
+ accessible: true,
1776
+ accessibilityState: { busy: true },
1777
+ accessibilityLabel: "Analyzing photo",
1778
+ children: visible ? /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
1779
+ /* @__PURE__ */ jsxRuntime.jsx(reactNative.Animated.View, { style: [styles.ring, arcMotionStyle] }),
1780
+ /* @__PURE__ */ jsxRuntime.jsx(reactNative.Text, { style: styles.statusLine, children: "Analyzing" })
1781
+ ] }) : null
1782
+ }
1783
+ );
1784
+ }
1785
+ function makeStyles3(theme) {
1786
+ const { color, space, radius, type } = theme;
1787
+ const medium = type.weight.medium;
1788
+ const ringSize = space.xxl * 2;
1789
+ const ringThickness = space.xs;
1790
+ return reactNative.StyleSheet.create({
1791
+ wrap: {
1792
+ flexGrow: 1,
1793
+ alignItems: "center",
1794
+ justifyContent: "center",
1795
+ padding: space.xl,
1796
+ gap: space.md
1797
+ },
1798
+ // One rotating ring: success on the top/right, cream on the remainder. Only the success sweep is perceptible
1799
+ // (the cream half is uniform), so this reads as a cream ring with a rotating success arc - the mobile look.
1800
+ ring: {
1801
+ width: ringSize,
1802
+ height: ringSize,
1803
+ borderRadius: radius.pill,
1804
+ borderWidth: ringThickness,
1805
+ borderTopColor: color.success,
1806
+ borderRightColor: color.success,
1807
+ borderBottomColor: color.borderRingCream,
1808
+ borderLeftColor: color.borderRingCream
1809
+ },
1810
+ // Neutral SDK-owned structural status word (not clinical / product copy), on the brand-green secondary ramp
1811
+ // so it sits in the same family as the verdict hero. Legible in both themes via the token.
1812
+ statusLine: {
1813
+ color: color.text.secondary,
1814
+ fontFamily: type.family,
1815
+ fontSize: type.size.subtitle,
1816
+ lineHeight: type.size.subtitle * type.lineHeight.snug,
1817
+ fontWeight: medium,
1818
+ letterSpacing: type.letterSpacing.tight,
1819
+ textAlign: "center"
1820
+ }
1821
+ });
1822
+ }
1823
+ var PULSE_PERIOD_MS = 1100;
1824
+ var PULSE_MAX_SCALE = 1.6;
1825
+ var PULSE_START_OPACITY = 0.35;
1826
+ function toneSpec(theme, tier) {
1827
+ const { color } = theme;
1828
+ switch (tier) {
1829
+ case "low_risk":
1830
+ return { accent: color.success, wash: color.badgeBgPositive, label: "Low risk", pulse: false };
1831
+ case "concern":
1832
+ return { accent: color.cautionAccent, wash: color.badgeBgCaution, label: "Concern", pulse: true };
1833
+ case "uncertain":
1834
+ return { accent: color.text.muted, wash: color.badgeBgNeutral, label: "Uncertain", pulse: false };
1835
+ }
1836
+ }
1837
+ function SeverityBadge({ riskTier }) {
1838
+ const theme = useEverfurTheme();
1839
+ const styles = react.useMemo(() => makeStyles4(theme), [theme]);
1840
+ const pulse = react.useRef(new reactNative.Animated.Value(0)).current;
1841
+ const spec = riskTier === null ? null : toneSpec(theme, riskTier);
1842
+ const shouldPulse = spec !== null && spec.pulse && !theme.motion.reducedMotion;
1843
+ react.useEffect(() => {
1844
+ if (!shouldPulse) return;
1845
+ const loop = reactNative.Animated.loop(
1846
+ reactNative.Animated.timing(pulse, {
1847
+ toValue: 1,
1848
+ duration: PULSE_PERIOD_MS,
1849
+ easing: reactNative.Easing.out(reactNative.Easing.quad),
1850
+ useNativeDriver: true
1851
+ })
1852
+ );
1853
+ loop.start();
1854
+ return () => loop.stop();
1855
+ }, [shouldPulse, pulse]);
1856
+ if (spec === null) return null;
1857
+ return /* @__PURE__ */ jsxRuntime.jsxs(
1858
+ reactNative.View,
1859
+ {
1860
+ style: [styles.pill, { backgroundColor: spec.wash }],
1861
+ accessible: true,
1862
+ accessibilityRole: "text",
1863
+ accessibilityLabel: spec.label,
1864
+ children: [
1865
+ /* @__PURE__ */ jsxRuntime.jsxs(reactNative.View, { style: styles.dotWrap, children: [
1866
+ shouldPulse ? /* @__PURE__ */ jsxRuntime.jsx(
1867
+ reactNative.Animated.View,
1868
+ {
1869
+ pointerEvents: "none",
1870
+ style: [
1871
+ styles.dotRing,
1872
+ {
1873
+ backgroundColor: spec.accent,
1874
+ opacity: pulse.interpolate({ inputRange: [0, 1], outputRange: [PULSE_START_OPACITY, 0] }),
1875
+ transform: [{ scale: pulse.interpolate({ inputRange: [0, 1], outputRange: [1, PULSE_MAX_SCALE] }) }]
1876
+ }
1877
+ ]
1878
+ }
1879
+ ) : null,
1880
+ /* @__PURE__ */ jsxRuntime.jsx(reactNative.View, { style: [styles.dot, { backgroundColor: spec.accent }] })
1881
+ ] }),
1882
+ /* @__PURE__ */ jsxRuntime.jsx(reactNative.Text, { style: [styles.label, { color: spec.accent }], children: spec.label })
1883
+ ]
1884
+ }
1885
+ );
1886
+ }
1887
+ function makeStyles4(theme) {
1888
+ const { space, radius, type } = theme;
1889
+ const bold = type.weight.bold;
1890
+ const dotSize = space.sm;
1891
+ return reactNative.StyleSheet.create({
1892
+ pill: {
1893
+ alignSelf: "flex-start",
1894
+ flexDirection: "row",
1895
+ alignItems: "center",
1896
+ gap: space.sm,
1897
+ paddingHorizontal: space.md,
1898
+ paddingVertical: space.xs,
1899
+ borderRadius: radius.pill
1900
+ },
1901
+ dotWrap: {
1902
+ width: dotSize,
1903
+ height: dotSize,
1904
+ alignItems: "center",
1905
+ justifyContent: "center"
1906
+ },
1907
+ dot: {
1908
+ width: dotSize,
1909
+ height: dotSize,
1910
+ borderRadius: radius.pill
1911
+ },
1912
+ // The pulsing attention ring behind the dot (concern only). backgroundColor + animated opacity/scale set inline.
1913
+ dotRing: {
1914
+ position: "absolute",
1915
+ width: dotSize,
1916
+ height: dotSize,
1917
+ borderRadius: radius.pill
1918
+ },
1919
+ label: {
1920
+ fontFamily: type.family,
1921
+ fontSize: type.size.caption,
1922
+ lineHeight: type.size.caption * type.lineHeight.snug,
1923
+ fontWeight: bold,
1924
+ letterSpacing: type.letterSpacing.eyebrow
1925
+ }
1926
+ });
1927
+ }
1928
+ var MIN_SURFACE_HEIGHT = 120;
1929
+ var MIN_TOUCH_TARGET = 44;
1930
+ function PhotoCheckup(props) {
1931
+ const { petRef, region, style } = props;
1932
+ return /* @__PURE__ */ jsxRuntime.jsx(CapabilityGate, { capability: "photo", style, children: /* @__PURE__ */ jsxRuntime.jsx(PhotoBody, { petRef, region, style }) });
1933
+ }
1934
+ function selectView2(state) {
1935
+ if (state.isBootstrapping) return "loading";
1936
+ if (state.status === "capturing" || state.status === "analyzing") return "loading";
1937
+ if (state.status === "error" && state.error) return "error";
1938
+ if (state.status === "complete" && state.result) return "populated";
1939
+ if (state.gate.kind !== "accepted") return "gate";
1940
+ if (!state.isCaptureAvailable) return "native";
1941
+ return "empty";
1942
+ }
1943
+ function PhotoBody({
1944
+ petRef,
1945
+ region,
1946
+ style
1947
+ }) {
1948
+ const photo = usePhotoCheckup({ petRef });
1949
+ const activeRegion = region ?? "skin";
1950
+ const view = selectView2(photo);
1951
+ const capture = react.useMemo(() => () => void photo.capture(activeRegion), [photo, activeRegion]);
1952
+ const theme = useEverfurTheme();
1953
+ const styles = react.useMemo(() => makeStyles5(theme), [theme]);
1954
+ return /* @__PURE__ */ jsxRuntime.jsxs(reactNative.View, { style: [styles.container, style], children: [
1955
+ /* @__PURE__ */ jsxRuntime.jsx(reactNative.View, { style: styles.body, children: renderView(view, photo, capture) }),
1956
+ /* @__PURE__ */ jsxRuntime.jsx(ClinicalDisclaimer, {})
1957
+ ] });
1958
+ }
1959
+ function renderView(view, photo, capture) {
1960
+ switch (view) {
1961
+ case "loading":
1962
+ return /* @__PURE__ */ jsxRuntime.jsx(AnalyzingIndicator, {});
1963
+ case "native":
1964
+ return /* @__PURE__ */ jsxRuntime.jsx(NativeUnavailableState, {});
1965
+ case "empty":
1966
+ return /* @__PURE__ */ jsxRuntime.jsx(EmptyState, { onCapture: capture });
1967
+ case "error":
1968
+ return /* @__PURE__ */ jsxRuntime.jsx(ErrorState, { error: photo.error, onRetry: capture });
1969
+ case "gate":
1970
+ return /* @__PURE__ */ jsxRuntime.jsx(GateState, { gate: photo.gate, onRetry: photo.reset });
1971
+ case "populated":
1972
+ return /* @__PURE__ */ jsxRuntime.jsx(ResultState, { result: photo.result });
1973
+ default:
1974
+ return assertNever(view);
1975
+ }
1976
+ }
1977
+ function NativeUnavailableState() {
1978
+ const theme = useEverfurTheme();
1979
+ const styles = react.useMemo(() => makeStyles5(theme), [theme]);
1980
+ return /* @__PURE__ */ jsxRuntime.jsx(reactNative.View, { style: styles.offstate, accessible: true, accessibilityRole: "text", accessibilityLabel: "Camera is unavailable", children: /* @__PURE__ */ jsxRuntime.jsx(reactNative.View, { style: styles.emptyGlyph }) });
1981
+ }
1982
+ function EmptyState({ onCapture }) {
1983
+ const theme = useEverfurTheme();
1984
+ const styles = react.useMemo(() => makeStyles5(theme), [theme]);
1985
+ return /* @__PURE__ */ jsxRuntime.jsx(reactNative.View, { style: styles.centered, accessible: true, accessibilityRole: "summary", accessibilityLabel: "Take a photo to check", children: /* @__PURE__ */ jsxRuntime.jsx(reactNative.Pressable, { onPress: onCapture, accessibilityRole: "button", accessibilityLabel: "Take photo", style: styles.scanButton, children: /* @__PURE__ */ jsxRuntime.jsx(reactNative.Text, { style: styles.scanLabel, children: "Take photo" }) }) });
1986
+ }
1987
+ function ErrorState({ error, onRetry }) {
1988
+ const theme = useEverfurTheme();
1989
+ const styles = react.useMemo(() => makeStyles5(theme), [theme]);
1990
+ return /* @__PURE__ */ jsxRuntime.jsxs(reactNative.View, { style: styles.centered, accessible: true, accessibilityRole: "alert", children: [
1991
+ /* @__PURE__ */ jsxRuntime.jsx(reactNative.Text, { style: styles.errorText, children: error.displayMessage }),
1992
+ error.retryable ? /* @__PURE__ */ jsxRuntime.jsx(reactNative.Pressable, { onPress: onRetry, accessibilityRole: "button", accessibilityLabel: "Try again", style: styles.primaryButton, children: /* @__PURE__ */ jsxRuntime.jsx(reactNative.Text, { style: styles.primaryLabel, children: "Try again" }) }) : null
1993
+ ] });
1994
+ }
1995
+ function GateState({ gate, onRetry }) {
1996
+ const theme = useEverfurTheme();
1997
+ const styles = react.useMemo(() => makeStyles5(theme), [theme]);
1998
+ const message = gateMessage(gate);
1999
+ return /* @__PURE__ */ jsxRuntime.jsxs(reactNative.View, { style: styles.centered, accessible: true, accessibilityRole: "summary", accessibilityLabel: message, children: [
2000
+ /* @__PURE__ */ jsxRuntime.jsx(reactNative.Text, { style: styles.guidanceText, children: message }),
2001
+ gate.kind !== "species_unsupported" ? /* @__PURE__ */ jsxRuntime.jsx(reactNative.Pressable, { onPress: onRetry, accessibilityRole: "button", accessibilityLabel: "Try again", style: styles.primaryButton, children: /* @__PURE__ */ jsxRuntime.jsx(reactNative.Text, { style: styles.primaryLabel, children: "Try again" }) }) : null
2002
+ ] });
2003
+ }
2004
+ function gateMessage(gate) {
2005
+ switch (gate.kind) {
2006
+ case "species_unsupported":
2007
+ return "Photo checks are coming soon for this pet.";
2008
+ case "pet_context_required":
2009
+ return "Choose a pet first, then take the photo.";
2010
+ case "retake":
2011
+ return "That photo was hard to read. Please take another.";
2012
+ case "accepted":
2013
+ return "";
2014
+ default:
2015
+ return assertNever(gate);
2016
+ }
2017
+ }
2018
+ function ResultState({ result }) {
2019
+ const theme = useEverfurTheme();
2020
+ const styles = react.useMemo(() => makeStyles5(theme), [theme]);
2021
+ const headline = result.subtypeDisplay ?? result.diseaseName ?? result.primaryLabel;
2022
+ const cardTint = resultCardTint(theme, result.riskTier);
2023
+ return /* @__PURE__ */ jsxRuntime.jsxs(
2024
+ reactNative.ScrollView,
2025
+ {
2026
+ style: styles.list,
2027
+ contentContainerStyle: [styles.listContent, { backgroundColor: cardTint }],
2028
+ accessibilityLabel: "Photo checkup result",
2029
+ children: [
2030
+ /* @__PURE__ */ jsxRuntime.jsx(reactNative.Text, { style: styles.resultHeadline, children: headline }),
2031
+ /* @__PURE__ */ jsxRuntime.jsx(SeverityBadge, { riskTier: result.riskTier }),
2032
+ result.diseaseFraming ? /* @__PURE__ */ jsxRuntime.jsx(reactNative.Text, { style: styles.summaryText, children: result.diseaseFraming }) : null,
2033
+ result.copyShort ? /* @__PURE__ */ jsxRuntime.jsx(reactNative.Text, { style: styles.summaryText, children: result.copyShort }) : null,
2034
+ result.interpretation ? /* @__PURE__ */ jsxRuntime.jsxs(reactNative.View, { style: styles.interpretationBlock, children: [
2035
+ /* @__PURE__ */ jsxRuntime.jsx(reactNative.Text, { style: styles.summaryText, children: result.interpretation.summary }),
2036
+ /* @__PURE__ */ jsxRuntime.jsx(reactNative.Text, { style: styles.disclaimerText, children: result.interpretation.disclaimer })
2037
+ ] }) : null
2038
+ ]
2039
+ }
2040
+ );
2041
+ }
2042
+ function resultCardTint(theme, riskTier) {
2043
+ switch (riskTier) {
2044
+ case "low_risk":
2045
+ return theme.color.checkupCardLowRiskBg;
2046
+ case "concern":
2047
+ return theme.color.checkupCardConcernBg;
2048
+ default:
2049
+ return theme.color.surfaceCream;
2050
+ }
2051
+ }
2052
+ function makeStyles5(theme) {
2053
+ const { color, space, radius, type } = theme;
2054
+ const bold = type.weight.bold;
2055
+ const medium = type.weight.medium;
2056
+ const regular = type.weight.regular;
2057
+ const scanInk = theme.brightness === "dark" ? color.onAccent : color.brand;
2058
+ return reactNative.StyleSheet.create({
2059
+ container: { flex: 1, minHeight: MIN_SURFACE_HEIGHT, backgroundColor: color.background },
2060
+ body: { flex: 1 },
2061
+ centered: {
2062
+ minHeight: MIN_SURFACE_HEIGHT,
2063
+ flexGrow: 1,
2064
+ alignItems: "center",
2065
+ justifyContent: "center",
2066
+ padding: space.xl
2067
+ },
2068
+ offstate: {
2069
+ minHeight: MIN_SURFACE_HEIGHT,
2070
+ alignItems: "center",
2071
+ justifyContent: "center",
2072
+ padding: space.xl
2073
+ },
2074
+ emptyGlyph: {
2075
+ width: space.xxl,
2076
+ height: space.xxl,
2077
+ borderRadius: radius.pill,
2078
+ backgroundColor: color.surfaceSubtle,
2079
+ borderWidth: reactNative.StyleSheet.hairlineWidth,
2080
+ borderColor: color.brandBorder
2081
+ },
2082
+ // Capture CTA — the Everfur pink scan pill (brief: scanButtonPink, radius pill, subtle depth).
2083
+ scanButton: {
2084
+ minHeight: MIN_TOUCH_TARGET,
2085
+ minWidth: MIN_TOUCH_TARGET,
2086
+ alignItems: "center",
2087
+ justifyContent: "center",
2088
+ paddingHorizontal: space.xl,
2089
+ paddingVertical: space.md,
2090
+ borderRadius: radius.pill,
2091
+ backgroundColor: color.scanButtonPink,
2092
+ shadowColor: color.brand,
2093
+ shadowOpacity: 0.18,
2094
+ shadowRadius: radius.xs,
2095
+ shadowOffset: { width: 0, height: space.xs },
2096
+ elevation: 3
2097
+ },
2098
+ scanLabel: {
2099
+ color: scanInk,
2100
+ fontFamily: type.family,
2101
+ fontSize: type.size.subtitle,
2102
+ lineHeight: type.size.subtitle * type.lineHeight.snug,
2103
+ fontWeight: bold,
2104
+ letterSpacing: type.letterSpacing.tight
2105
+ },
2106
+ // Secondary CTA — retry / try-again, brand fill with WCAG-legible onPrimary.
2107
+ primaryButton: {
2108
+ minHeight: MIN_TOUCH_TARGET,
2109
+ minWidth: MIN_TOUCH_TARGET,
2110
+ alignItems: "center",
2111
+ justifyContent: "center",
2112
+ paddingHorizontal: space.xl,
2113
+ paddingVertical: space.sm,
2114
+ borderRadius: radius.pill,
2115
+ backgroundColor: color.brand
2116
+ },
2117
+ primaryLabel: {
2118
+ color: color.onPrimary,
2119
+ fontFamily: type.family,
2120
+ fontSize: type.size.body,
2121
+ lineHeight: type.size.body * type.lineHeight.snug,
2122
+ fontWeight: medium
2123
+ },
2124
+ errorText: {
2125
+ color: color.danger,
2126
+ fontFamily: type.family,
2127
+ fontSize: type.size.body,
2128
+ lineHeight: type.size.body * type.lineHeight.relaxed,
2129
+ textAlign: "center",
2130
+ marginBottom: space.md
2131
+ },
2132
+ guidanceText: {
2133
+ color: color.text.muted,
2134
+ fontFamily: type.family,
2135
+ fontSize: type.size.body,
2136
+ lineHeight: type.size.body * type.lineHeight.relaxed,
2137
+ textAlign: "center",
2138
+ marginBottom: space.md
2139
+ },
2140
+ list: { flex: 1 },
2141
+ // The checkup card — cream/risk-washed surface (backgroundColor supplied inline from resultCardTint), a
2142
+ // brand hairline border, and a subtle brand-tinted shadow for depth.
2143
+ listContent: {
2144
+ padding: space.lg,
2145
+ gap: space.sm,
2146
+ borderRadius: radius.lg,
2147
+ borderWidth: reactNative.StyleSheet.hairlineWidth,
2148
+ borderColor: color.brandBorder,
2149
+ shadowColor: color.brand,
2150
+ shadowOpacity: 0.08,
2151
+ shadowRadius: radius.xs,
2152
+ shadowOffset: { width: 0, height: space.xs },
2153
+ elevation: 2
2154
+ },
2155
+ // Verdict hero (brief: type.verdict 24) in brand green for character.
2156
+ resultHeadline: {
2157
+ color: color.text.secondary,
2158
+ fontFamily: type.family,
2159
+ fontSize: type.size.verdict,
2160
+ lineHeight: type.size.verdict * type.lineHeight.tight,
2161
+ fontWeight: bold,
2162
+ letterSpacing: type.letterSpacing.tight
2163
+ },
2164
+ summaryText: {
2165
+ color: color.text.primary,
2166
+ fontFamily: type.family,
2167
+ fontSize: type.size.body,
2168
+ lineHeight: type.size.body * type.lineHeight.relaxed,
2169
+ fontWeight: regular
2170
+ },
2171
+ interpretationBlock: {
2172
+ marginTop: space.sm,
2173
+ paddingTop: space.sm,
2174
+ gap: space.xs,
2175
+ borderTopWidth: reactNative.StyleSheet.hairlineWidth,
2176
+ borderTopColor: color.borderHairlineGreen
2177
+ },
2178
+ disclaimerText: {
2179
+ color: color.text.muted,
2180
+ fontFamily: type.family,
2181
+ fontSize: type.size.caption,
2182
+ lineHeight: type.size.caption * type.lineHeight.normal,
2183
+ fontWeight: regular
2184
+ }
2185
+ });
2186
+ }
2187
+
2188
+ exports.PhotoCheckup = PhotoCheckup;
2189
+ exports.usePhotoCheckup = usePhotoCheckup;