@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.
- package/CHANGELOG.md +74 -0
- package/LICENSE +21 -0
- package/README.md +161 -0
- package/animations/package.json +8 -0
- package/chat/package.json +8 -0
- package/client/package.json +8 -0
- package/core/package.json +8 -0
- package/dist/CameraPort-Cv31Pz7g.d.cts +29 -0
- package/dist/CameraPort-Cv31Pz7g.d.ts +29 -0
- package/dist/ChatController-CKdBvPj2.d.ts +146 -0
- package/dist/ChatController-CpUMvvZf.d.cts +146 -0
- package/dist/EverfurResult-D92-uL82.d.cts +240 -0
- package/dist/EverfurResult-D92-uL82.d.ts +240 -0
- package/dist/FilePort-BabWrv7I.d.cts +22 -0
- package/dist/FilePort-BabWrv7I.d.ts +22 -0
- package/dist/PhotoController-BItt5M7u.d.cts +43 -0
- package/dist/PhotoController-D8zMTdcW.d.ts +43 -0
- package/dist/TelemetryPort-BDNr00hu.d.cts +12 -0
- package/dist/TelemetryPort-BDNr00hu.d.ts +12 -0
- package/dist/animations/index.cjs +1997 -0
- package/dist/animations/index.d.cts +517 -0
- package/dist/animations/index.d.ts +517 -0
- package/dist/animations/index.js +1972 -0
- package/dist/cacheEpoch-DknKn3S0.d.cts +36 -0
- package/dist/cacheEpoch-DknKn3S0.d.ts +36 -0
- package/dist/chat/index.cjs +1170 -0
- package/dist/chat/index.d.cts +59 -0
- package/dist/chat/index.d.ts +59 -0
- package/dist/chat/index.js +1167 -0
- package/dist/client/index.cjs +2317 -0
- package/dist/client/index.d.cts +65 -0
- package/dist/client/index.d.ts +65 -0
- package/dist/client/index.js +2217 -0
- package/dist/config-BSjBdxrZ.d.cts +501 -0
- package/dist/config-CiJ0PVBB.d.ts +501 -0
- package/dist/core/index.cjs +3175 -0
- package/dist/core/index.d.cts +70 -0
- package/dist/core/index.d.ts +70 -0
- package/dist/core/index.js +3163 -0
- package/dist/identity-Brl-lDd6.d.cts +91 -0
- package/dist/identity-DK9zORrG.d.ts +91 -0
- package/dist/ids-CJ1S6adf.d.cts +46 -0
- package/dist/ids-CJ1S6adf.d.ts +46 -0
- package/dist/index.cjs +4488 -0
- package/dist/index.d.cts +156 -0
- package/dist/index.d.ts +156 -0
- package/dist/index.js +4464 -0
- package/dist/petsRepository-BEGb97M9.d.cts +326 -0
- package/dist/petsRepository-Bu18r2kK.d.ts +326 -0
- package/dist/photo/index.cjs +2189 -0
- package/dist/photo/index.d.cts +43 -0
- package/dist/photo/index.d.ts +43 -0
- package/dist/photo/index.js +2186 -0
- package/dist/projection-CeIUsbSk.d.cts +8 -0
- package/dist/projection-CeIUsbSk.d.ts +8 -0
- package/dist/records/index.cjs +2840 -0
- package/dist/records/index.d.cts +224 -0
- package/dist/records/index.d.ts +224 -0
- package/dist/records/index.js +2834 -0
- package/dist/requestFunnel-DuUH-kAe.d.cts +28 -0
- package/dist/requestFunnel-dio5OmR9.d.ts +28 -0
- package/dist/resolve-Dq_4_agU.d.cts +86 -0
- package/dist/resolve-Dq_4_agU.d.ts +86 -0
- package/dist/runtime-BgQnA594.d.cts +349 -0
- package/dist/runtime-CBA-LvdM.d.ts +349 -0
- package/dist/server/index.cjs +533 -0
- package/dist/server/index.d.cts +48 -0
- package/dist/server/index.d.ts +48 -0
- package/dist/server/index.js +530 -0
- package/dist/testing/index.cjs +825 -0
- package/dist/testing/index.d.cts +113 -0
- package/dist/testing/index.d.ts +113 -0
- package/dist/testing/index.js +822 -0
- package/dist/testing/rn/index.cjs +449 -0
- package/dist/testing/rn/index.d.cts +49 -0
- package/dist/testing/rn/index.d.ts +49 -0
- package/dist/testing/rn/index.js +444 -0
- package/dist/video/index.cjs +1941 -0
- package/dist/video/index.d.cts +66 -0
- package/dist/video/index.d.ts +66 -0
- package/dist/video/index.js +1938 -0
- package/package.json +311 -0
- package/photo/package.json +8 -0
- package/records/package.json +8 -0
- package/server/device-blocked.cjs +15 -0
- package/server/package.json +9 -0
- package/testing/package.json +8 -0
- package/testing/rn/package.json +8 -0
- package/video/package.json +8 -0
|
@@ -0,0 +1,825 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
var zod = require('zod');
|
|
4
|
+
|
|
5
|
+
// src/client/errors/EverfurResult.ts
|
|
6
|
+
function ok(value, warning) {
|
|
7
|
+
return Object.freeze(
|
|
8
|
+
{ ok: true, value }
|
|
9
|
+
);
|
|
10
|
+
}
|
|
11
|
+
function err(error) {
|
|
12
|
+
return Object.freeze({ ok: false, error });
|
|
13
|
+
}
|
|
14
|
+
var EverfurConfigError = class _EverfurConfigError extends Error {
|
|
15
|
+
constructor(kind, message) {
|
|
16
|
+
super(message);
|
|
17
|
+
this.name = "EverfurConfigError";
|
|
18
|
+
this.kind = kind;
|
|
19
|
+
Object.setPrototypeOf(this, _EverfurConfigError.prototype);
|
|
20
|
+
}
|
|
21
|
+
};
|
|
22
|
+
|
|
23
|
+
// src/core/testing/knownRoutes.ts
|
|
24
|
+
var KNOWN_PARTNER_ROUTES = [
|
|
25
|
+
"DELETE /widget/v1/me",
|
|
26
|
+
"DELETE /widget/v1/pets/{pet_ref}",
|
|
27
|
+
"DELETE /widget/v1/records/pets/{pet_ref}/consent",
|
|
28
|
+
"GET /widget/v1/consent",
|
|
29
|
+
"GET /widget/v1/conversations",
|
|
30
|
+
"GET /widget/v1/conversations/{conversation_id}/messages",
|
|
31
|
+
"GET /widget/v1/entitlements",
|
|
32
|
+
"GET /widget/v1/pets",
|
|
33
|
+
"GET /widget/v1/records/pets/{pet_ref}/consent",
|
|
34
|
+
"GET /widget/v1/records/pets/{pet_ref}/record",
|
|
35
|
+
"GET /widget/v1/records/requests",
|
|
36
|
+
"GET /widget/v1/records/requests/{request_id}",
|
|
37
|
+
"GET /widget/v1/suggested-prompts",
|
|
38
|
+
"PATCH /widget/v1/pets/{pet_ref}",
|
|
39
|
+
"POST /widget/v1/conversations",
|
|
40
|
+
"POST /widget/v1/conversations/{conversation_id}/analyze",
|
|
41
|
+
"POST /widget/v1/conversations/{conversation_id}/classify",
|
|
42
|
+
"POST /widget/v1/conversations/{conversation_id}/messages",
|
|
43
|
+
"POST /widget/v1/pets/{pet_ref}",
|
|
44
|
+
"POST /widget/v1/records/requests",
|
|
45
|
+
"POST /widget/v1/records/requests/{request_id}/uploads/complete",
|
|
46
|
+
"POST /widget/v1/records/requests/{request_id}/uploads/initiate",
|
|
47
|
+
"POST /widget/v1/sessions",
|
|
48
|
+
"PUT /widget/v1/consent",
|
|
49
|
+
"PUT /widget/v1/records/pets/{pet_ref}/consent"
|
|
50
|
+
];
|
|
51
|
+
var KNOWN_ABSENT_ROUTES = [
|
|
52
|
+
"POST /widget/v1/uploads/initiate",
|
|
53
|
+
"POST /widget/v1/photo/precheck",
|
|
54
|
+
"POST /widget/v1/photo/analyze",
|
|
55
|
+
"POST /widget/v1/video/analyze",
|
|
56
|
+
"GET /widget/v1/analysis/jobs/{job_id}",
|
|
57
|
+
"GET /widget/v1/pets/{pet_ref}/state"
|
|
58
|
+
];
|
|
59
|
+
function pathMatches(template, path) {
|
|
60
|
+
const templateParts = template.split("/");
|
|
61
|
+
const [withoutQuery = ""] = path.split("?");
|
|
62
|
+
const pathParts = withoutQuery.split("/");
|
|
63
|
+
if (templateParts.length !== pathParts.length) return false;
|
|
64
|
+
return templateParts.every((seg, i) => {
|
|
65
|
+
const actual = pathParts[i];
|
|
66
|
+
if (actual === void 0) return false;
|
|
67
|
+
const isWildcard = seg.startsWith("{") && seg.endsWith("}");
|
|
68
|
+
return isWildcard ? actual.length > 0 : seg === actual;
|
|
69
|
+
});
|
|
70
|
+
}
|
|
71
|
+
function classifyRoute(method, path) {
|
|
72
|
+
const matches = (list) => list.some((entry) => {
|
|
73
|
+
const [entryMethod, template] = entry.split(" ");
|
|
74
|
+
if (entryMethod === void 0 || template === void 0) return false;
|
|
75
|
+
return entryMethod === method.toUpperCase() && pathMatches(template, path);
|
|
76
|
+
});
|
|
77
|
+
if (matches(KNOWN_PARTNER_ROUTES)) return "known";
|
|
78
|
+
if (matches(KNOWN_ABSENT_ROUTES)) return "absent";
|
|
79
|
+
return "unknown";
|
|
80
|
+
}
|
|
81
|
+
var CONTRACT_RETRYABILITY = Object.freeze([
|
|
82
|
+
Object.freeze({ wireCode: "AccessDeniedException", envelope: "http_envelope", httpStatus: 403, retryable: false }),
|
|
83
|
+
Object.freeze({ wireCode: "AuthorizationException", envelope: "http_envelope", httpStatus: 401, retryable: false }),
|
|
84
|
+
Object.freeze({ wireCode: "ConflictException", envelope: "http_envelope", httpStatus: 409, retryable: true }),
|
|
85
|
+
Object.freeze({ wireCode: "DAILY_QUOTA_EXCEEDED", envelope: "http_envelope", httpStatus: 429, retryable: true }),
|
|
86
|
+
Object.freeze({ wireCode: "IDEMPOTENCY_KEY_IN_FLIGHT", envelope: "http_envelope", httpStatus: 409, retryable: true }),
|
|
87
|
+
Object.freeze({ wireCode: "IDEMPOTENCY_KEY_REUSED_DIFFERENT_REQUEST", envelope: "http_envelope", httpStatus: 409, retryable: false }),
|
|
88
|
+
Object.freeze({ wireCode: "InternalFailureException", envelope: "http_envelope", httpStatus: 500, retryable: true }),
|
|
89
|
+
Object.freeze({ wireCode: "NotImplementedException", envelope: "http_envelope", httpStatus: 501, retryable: false }),
|
|
90
|
+
Object.freeze({ wireCode: "PaymentRequiredException", envelope: "http_envelope", httpStatus: 402, retryable: false }),
|
|
91
|
+
Object.freeze({ wireCode: "ResourceNotFoundException", envelope: "http_envelope", httpStatus: 404, retryable: false }),
|
|
92
|
+
Object.freeze({ wireCode: "ServiceUnavailableException", envelope: "http_envelope", httpStatus: 503, retryable: true }),
|
|
93
|
+
Object.freeze({ wireCode: "TIER_UPGRADE_REQUIRED", envelope: "http_envelope", httpStatus: 402, retryable: false }),
|
|
94
|
+
Object.freeze({ wireCode: "ThrottlingException", envelope: "http_envelope", httpStatus: 429, retryable: true }),
|
|
95
|
+
Object.freeze({ wireCode: "ValidationException", envelope: "http_envelope", httpStatus: 400, retryable: false }),
|
|
96
|
+
Object.freeze({ wireCode: "accessDenied", envelope: "http_envelope", httpStatus: 403, retryable: false }),
|
|
97
|
+
Object.freeze({ wireCode: "authExpired", envelope: "http_envelope", httpStatus: 401, retryable: true }),
|
|
98
|
+
Object.freeze({ wireCode: "internal_error", envelope: "sse_frame", httpStatus: 200, retryable: false }),
|
|
99
|
+
Object.freeze({ wireCode: "invalidRequest", envelope: "http_envelope", httpStatus: 400, retryable: false }),
|
|
100
|
+
Object.freeze({ wireCode: "not_found", envelope: "sse_frame", httpStatus: 200, retryable: false }),
|
|
101
|
+
Object.freeze({ wireCode: "session_required", envelope: "http_envelope", httpStatus: 403, retryable: false }),
|
|
102
|
+
Object.freeze({ wireCode: "timeout", envelope: "sse_frame", httpStatus: 200, retryable: true }),
|
|
103
|
+
Object.freeze({ wireCode: "unavailable", envelope: "http_envelope", httpStatus: 503, retryable: true })
|
|
104
|
+
]);
|
|
105
|
+
Object.freeze(
|
|
106
|
+
CONTRACT_RETRYABILITY.map((row) => row.wireCode)
|
|
107
|
+
);
|
|
108
|
+
|
|
109
|
+
// src/client/errors/contract.ts
|
|
110
|
+
var NORMALIZED_FOLD = Object.freeze({
|
|
111
|
+
// the default status-mapped envelope
|
|
112
|
+
ValidationException: "validationFailed",
|
|
113
|
+
AuthorizationException: "authRejected",
|
|
114
|
+
PaymentRequiredException: "paymentRequired",
|
|
115
|
+
AccessDeniedException: "accessDenied",
|
|
116
|
+
ResourceNotFoundException: "resourceNotFound",
|
|
117
|
+
ConflictException: "conflict",
|
|
118
|
+
ThrottlingException: "rateLimited",
|
|
119
|
+
InternalFailureException: "internalError",
|
|
120
|
+
NotImplementedException: "notImplemented",
|
|
121
|
+
ServiceUnavailableException: "serviceUnavailable",
|
|
122
|
+
// dict-detail codes on the widget surface
|
|
123
|
+
authExpired: "authExpired",
|
|
124
|
+
unavailable: "serviceUnavailable",
|
|
125
|
+
session_required: "sessionRequired",
|
|
126
|
+
accessDenied: "accessDenied",
|
|
127
|
+
invalidRequest: "sdkUpdateRequired",
|
|
128
|
+
// typed codes
|
|
129
|
+
IDEMPOTENCY_KEY_IN_FLIGHT: "idempotencyInFlight",
|
|
130
|
+
IDEMPOTENCY_KEY_REUSED_DIFFERENT_REQUEST: "idempotencyConflict",
|
|
131
|
+
DAILY_QUOTA_EXCEEDED: "quotaExceeded",
|
|
132
|
+
TIER_UPGRADE_REQUIRED: "paymentRequired",
|
|
133
|
+
// SSE error frames
|
|
134
|
+
not_found: "conversationNotFound",
|
|
135
|
+
timeout: "streamTimeout",
|
|
136
|
+
internal_error: "internalError"
|
|
137
|
+
});
|
|
138
|
+
var CONTRACT_ERROR_ROWS = Object.freeze(
|
|
139
|
+
CONTRACT_RETRYABILITY.map(
|
|
140
|
+
(generated) => Object.freeze({
|
|
141
|
+
wireCode: generated.wireCode,
|
|
142
|
+
envelope: generated.envelope,
|
|
143
|
+
retryable: generated.retryable,
|
|
144
|
+
normalized: NORMALIZED_FOLD[generated.wireCode]
|
|
145
|
+
})
|
|
146
|
+
)
|
|
147
|
+
);
|
|
148
|
+
var BY_UPPER = new Map(
|
|
149
|
+
CONTRACT_ERROR_ROWS.map((r) => [r.wireCode.toUpperCase(), r])
|
|
150
|
+
);
|
|
151
|
+
function contractErrorFor(wireCode) {
|
|
152
|
+
if (typeof wireCode !== "string") return void 0;
|
|
153
|
+
const key = wireCode.trim().toUpperCase();
|
|
154
|
+
return key.length > 0 ? BY_UPPER.get(key) : void 0;
|
|
155
|
+
}
|
|
156
|
+
var CATEGORY_OF = Object.freeze({
|
|
157
|
+
// the caller's sign-in state is wrong and a credential change is the remedy
|
|
158
|
+
authExpired: "authentication",
|
|
159
|
+
authRejected: "authentication",
|
|
160
|
+
sessionRequired: "authentication",
|
|
161
|
+
// signed in, correctly identified, and still not allowed
|
|
162
|
+
accessDenied: "authorization",
|
|
163
|
+
// a plan gate, not a permission failure: the remedy is commercial
|
|
164
|
+
paymentRequired: "entitlement",
|
|
165
|
+
// slow down / come back later
|
|
166
|
+
quotaExceeded: "rateLimit",
|
|
167
|
+
rateLimited: "rateLimit",
|
|
168
|
+
// the request itself was wrong; retrying it unchanged can never succeed
|
|
169
|
+
validationFailed: "invalidRequest",
|
|
170
|
+
sdkUpdateRequired: "invalidRequest",
|
|
171
|
+
// the target is gone, hidden, or was never visible to this caller
|
|
172
|
+
conversationNotFound: "notFound",
|
|
173
|
+
petNotFound: "notFound",
|
|
174
|
+
resourceNotFound: "notFound",
|
|
175
|
+
// something else already holds the thing
|
|
176
|
+
conflict: "conflict",
|
|
177
|
+
idempotencyConflict: "conflict",
|
|
178
|
+
idempotencyInFlight: "conflict",
|
|
179
|
+
// the pipe, not the request: timeouts, drops, a briefly unreachable dependency
|
|
180
|
+
streamTimeout: "connection",
|
|
181
|
+
streamIncomplete: "connection",
|
|
182
|
+
upstreamLlmTimeout: "connection",
|
|
183
|
+
serviceUnavailable: "connection",
|
|
184
|
+
// the server admits fault
|
|
185
|
+
internalError: "server",
|
|
186
|
+
notImplemented: "server",
|
|
187
|
+
mediaUploadFailed: "media",
|
|
188
|
+
moderationBlocked: "policy",
|
|
189
|
+
unknown: "unknown"
|
|
190
|
+
});
|
|
191
|
+
function categoryFor(code) {
|
|
192
|
+
return CATEGORY_OF[code];
|
|
193
|
+
}
|
|
194
|
+
function fromWire(wire2) {
|
|
195
|
+
const contractRow = contractErrorFor(wire2);
|
|
196
|
+
if (contractRow) return contractRow.normalized;
|
|
197
|
+
const upper = (wire2 ?? "").trim().toUpperCase();
|
|
198
|
+
const canonical = upper.replace(/[^A-Z0-9]/g, "");
|
|
199
|
+
if (canonical === "AUTHREJECTED") return "authRejected";
|
|
200
|
+
if (upper.startsWith("AUTH")) return "authExpired";
|
|
201
|
+
switch (canonical) {
|
|
202
|
+
case "DAILYQUOTAEXCEEDED":
|
|
203
|
+
case "QUOTAEXCEEDED":
|
|
204
|
+
return "quotaExceeded";
|
|
205
|
+
case "RATELIMITED":
|
|
206
|
+
case "TOOMANYREQUESTS":
|
|
207
|
+
return "rateLimited";
|
|
208
|
+
case "IDEMPOTENCYKEYCONFLICT":
|
|
209
|
+
case "IDEMPOTENCYCONFLICT":
|
|
210
|
+
return "idempotencyConflict";
|
|
211
|
+
case "ACCESSDENIED":
|
|
212
|
+
case "FORBIDDEN":
|
|
213
|
+
return "accessDenied";
|
|
214
|
+
case "NOTFOUND":
|
|
215
|
+
case "CONVERSATIONNOTFOUND":
|
|
216
|
+
return "conversationNotFound";
|
|
217
|
+
case "PETNOTFOUND":
|
|
218
|
+
return "petNotFound";
|
|
219
|
+
case "TIMEOUT":
|
|
220
|
+
case "STREAMTIMEOUT":
|
|
221
|
+
return "streamTimeout";
|
|
222
|
+
// Analysis-domain deterministic 400s (NON-retryable). Additive per SPEC-00 §3.1 / SPEC-11b §2.6:
|
|
223
|
+
// fold to a NON-retried target so the SDK never retries a permanently-failing bad-input request.
|
|
224
|
+
// (Comment above the group so the empty fall-through cases stay lint-clean under no-fallthrough.)
|
|
225
|
+
case "MEDIAUPLOADFAILED":
|
|
226
|
+
case "UNRECOGNIZEDVIDEOFORMAT":
|
|
227
|
+
case "FILETOOSMALL":
|
|
228
|
+
return "mediaUploadFailed";
|
|
229
|
+
case "MODERATIONBLOCKED":
|
|
230
|
+
return "moderationBlocked";
|
|
231
|
+
case "UPSTREAMLLMTIMEOUT":
|
|
232
|
+
return "upstreamLlmTimeout";
|
|
233
|
+
case "INTERNALERROR":
|
|
234
|
+
case "INTERNALSERVERERROR":
|
|
235
|
+
return "internalError";
|
|
236
|
+
case "STREAMINCOMPLETE":
|
|
237
|
+
case "CHATSTREAMINCOMPLETE":
|
|
238
|
+
return "streamIncomplete";
|
|
239
|
+
// Deterministic 400s that can only come from an SDK bug -> unknown (NON-retryable). NEVER internalError
|
|
240
|
+
// (which IS auto-retried): mapping a bad-input 400 to a retryable code retries a request that never succeeds.
|
|
241
|
+
case "INVALIDANALYSISTYPE":
|
|
242
|
+
case "INVALIDUPLOADPURPOSE":
|
|
243
|
+
return "unknown";
|
|
244
|
+
default:
|
|
245
|
+
return "unknown";
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
function fromHttpStatus(status) {
|
|
249
|
+
if (status === 401) return "authExpired";
|
|
250
|
+
if (status === 403) return "accessDenied";
|
|
251
|
+
if (status === 404) return "conversationNotFound";
|
|
252
|
+
if (status === 409) return "idempotencyConflict";
|
|
253
|
+
if (status === 421) return "unknown";
|
|
254
|
+
if (status === 429) return "rateLimited";
|
|
255
|
+
if (status === 400 || status === 422) return "unknown";
|
|
256
|
+
if (status >= 500) return "internalError";
|
|
257
|
+
return "unknown";
|
|
258
|
+
}
|
|
259
|
+
var AUTO_RETRYABLE_CODES = /* @__PURE__ */ new Set([
|
|
260
|
+
"streamTimeout",
|
|
261
|
+
"rateLimited",
|
|
262
|
+
"internalError",
|
|
263
|
+
"upstreamLlmTimeout",
|
|
264
|
+
"streamIncomplete"
|
|
265
|
+
]);
|
|
266
|
+
function isAutoRetryable(code) {
|
|
267
|
+
return AUTO_RETRYABLE_CODES.has(code);
|
|
268
|
+
}
|
|
269
|
+
var RETRYABLE_CONTRACT_CODES = /* @__PURE__ */ new Set([
|
|
270
|
+
"serviceUnavailable",
|
|
271
|
+
"conflict",
|
|
272
|
+
"idempotencyInFlight"
|
|
273
|
+
]);
|
|
274
|
+
function isRetryableCode(code) {
|
|
275
|
+
return isAutoRetryable(code) || RETRYABLE_CONTRACT_CODES.has(code);
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
// src/client/protocol/frames.ts
|
|
279
|
+
function assertNever(x) {
|
|
280
|
+
throw new Error(
|
|
281
|
+
`assertNever: unhandled discriminated-union member ${JSON.stringify(x)}`
|
|
282
|
+
);
|
|
283
|
+
}
|
|
284
|
+
function acceptedFrame(streamId, lastEventId, serverRequestId = null) {
|
|
285
|
+
return Object.freeze({ kind: "accepted", streamId, lastEventId, serverRequestId, terminal: false });
|
|
286
|
+
}
|
|
287
|
+
function heartbeatFrame(lastEventId, serverRequestId = null) {
|
|
288
|
+
return Object.freeze({ kind: "heartbeat", lastEventId, serverRequestId, terminal: false });
|
|
289
|
+
}
|
|
290
|
+
function deltaFrame(delta, lastEventId, serverRequestId = null) {
|
|
291
|
+
return Object.freeze({ kind: "delta", delta, lastEventId, serverRequestId, terminal: false });
|
|
292
|
+
}
|
|
293
|
+
function doneFrame(fields, serverRequestId = null) {
|
|
294
|
+
return Object.freeze({
|
|
295
|
+
kind: "done",
|
|
296
|
+
terminal: true,
|
|
297
|
+
conversationId: fields.conversationId,
|
|
298
|
+
messageId: fields.messageId,
|
|
299
|
+
title: fields.title,
|
|
300
|
+
followUpQuestions: Object.freeze([...fields.followUpQuestions]),
|
|
301
|
+
citations: Object.freeze([...fields.citations]),
|
|
302
|
+
citationStatus: fields.citationStatus,
|
|
303
|
+
urgencyLevel: fields.urgencyLevel,
|
|
304
|
+
urgencyReason: fields.urgencyReason,
|
|
305
|
+
resultId: fields.resultId,
|
|
306
|
+
lastEventId: fields.lastEventId,
|
|
307
|
+
serverRequestId
|
|
308
|
+
});
|
|
309
|
+
}
|
|
310
|
+
function errorFrame(fields) {
|
|
311
|
+
return Object.freeze({
|
|
312
|
+
kind: "error",
|
|
313
|
+
terminal: true,
|
|
314
|
+
code: fields.code,
|
|
315
|
+
retryable: fields.retryable,
|
|
316
|
+
wireMessage: fields.wireMessage,
|
|
317
|
+
synthesized: fields.synthesized,
|
|
318
|
+
lastEventId: fields.lastEventId,
|
|
319
|
+
serverRequestId: fields.serverRequestId ?? null
|
|
320
|
+
});
|
|
321
|
+
}
|
|
322
|
+
function analysisStartedFrame(requestId, lastEventId, serverRequestId = null) {
|
|
323
|
+
return Object.freeze({
|
|
324
|
+
kind: "analysisStarted",
|
|
325
|
+
requestId,
|
|
326
|
+
lastEventId,
|
|
327
|
+
serverRequestId,
|
|
328
|
+
terminal: false
|
|
329
|
+
});
|
|
330
|
+
}
|
|
331
|
+
function analysisCompleteFrame(fields, serverRequestId = null) {
|
|
332
|
+
return Object.freeze({
|
|
333
|
+
kind: "analysisComplete",
|
|
334
|
+
terminal: false,
|
|
335
|
+
resultId: fields.resultId,
|
|
336
|
+
analysisType: fields.analysisType,
|
|
337
|
+
modelVersion: fields.modelVersion,
|
|
338
|
+
confidence: fields.confidence,
|
|
339
|
+
detections: Object.freeze([...fields.detections]),
|
|
340
|
+
interpretation: fields.interpretation,
|
|
341
|
+
lastEventId: fields.lastEventId,
|
|
342
|
+
serverRequestId
|
|
343
|
+
});
|
|
344
|
+
}
|
|
345
|
+
function unknownFrame(raw, lastEventId, serverRequestId = null) {
|
|
346
|
+
return Object.freeze({
|
|
347
|
+
kind: "unknown",
|
|
348
|
+
raw: { ...raw },
|
|
349
|
+
lastEventId,
|
|
350
|
+
serverRequestId,
|
|
351
|
+
terminal: false
|
|
352
|
+
});
|
|
353
|
+
}
|
|
354
|
+
var BLOCK_SEPARATOR = "\n\n";
|
|
355
|
+
var MAX_PENDING_BLOCK_CHARS = 1048576;
|
|
356
|
+
var wireObjectSchema = zod.z.record(zod.z.string(), zod.z.unknown());
|
|
357
|
+
var URGENCY_LEVELS = ["emergency", "schedule_soon", "home_care"];
|
|
358
|
+
async function* parseSse(bytes, serverRequestId = null) {
|
|
359
|
+
let resolvedRequestId = null;
|
|
360
|
+
const requestIdNow = () => {
|
|
361
|
+
if (resolvedRequestId !== null) return resolvedRequestId;
|
|
362
|
+
resolvedRequestId = typeof serverRequestId === "function" ? serverRequestId() : serverRequestId;
|
|
363
|
+
return resolvedRequestId;
|
|
364
|
+
};
|
|
365
|
+
const decoder = new TextDecoder("utf-8");
|
|
366
|
+
let buffer = "";
|
|
367
|
+
let scanFrom = 0;
|
|
368
|
+
let sawDelta = false;
|
|
369
|
+
for await (const chunk of bytes) {
|
|
370
|
+
buffer += decoder.decode(chunk, { stream: true });
|
|
371
|
+
for (; ; ) {
|
|
372
|
+
const sep = buffer.indexOf(BLOCK_SEPARATOR, scanFrom);
|
|
373
|
+
if (sep === -1) break;
|
|
374
|
+
const block = buffer.slice(0, sep);
|
|
375
|
+
buffer = buffer.slice(sep + BLOCK_SEPARATOR.length);
|
|
376
|
+
scanFrom = 0;
|
|
377
|
+
const frame = parseBlock(block, requestIdNow());
|
|
378
|
+
if (frame === null) continue;
|
|
379
|
+
if (frame.kind === "delta") sawDelta = true;
|
|
380
|
+
yield frame;
|
|
381
|
+
if (frame.terminal) return;
|
|
382
|
+
}
|
|
383
|
+
scanFrom = buffer.length > 0 ? buffer.length - 1 : 0;
|
|
384
|
+
if (buffer.length > MAX_PENDING_BLOCK_CHARS) {
|
|
385
|
+
yield errorFrame({
|
|
386
|
+
code: sawDelta ? "CHAT_STREAM_INCOMPLETE" : "internal_error",
|
|
387
|
+
retryable: true,
|
|
388
|
+
wireMessage: null,
|
|
389
|
+
synthesized: true,
|
|
390
|
+
lastEventId: null,
|
|
391
|
+
serverRequestId: requestIdNow()
|
|
392
|
+
});
|
|
393
|
+
return;
|
|
394
|
+
}
|
|
395
|
+
}
|
|
396
|
+
buffer += decoder.decode();
|
|
397
|
+
if (buffer.trim().length > 0) {
|
|
398
|
+
const frame = parseBlock(buffer, requestIdNow());
|
|
399
|
+
if (frame !== null) {
|
|
400
|
+
if (frame.kind === "delta") sawDelta = true;
|
|
401
|
+
yield frame;
|
|
402
|
+
if (frame.terminal) return;
|
|
403
|
+
}
|
|
404
|
+
}
|
|
405
|
+
yield errorFrame({
|
|
406
|
+
code: sawDelta ? "CHAT_STREAM_INCOMPLETE" : "internal_error",
|
|
407
|
+
retryable: true,
|
|
408
|
+
wireMessage: null,
|
|
409
|
+
synthesized: true,
|
|
410
|
+
lastEventId: null,
|
|
411
|
+
serverRequestId: requestIdNow()
|
|
412
|
+
});
|
|
413
|
+
}
|
|
414
|
+
function parseBlock(block, serverRequestId) {
|
|
415
|
+
let id = null;
|
|
416
|
+
const dataLines = [];
|
|
417
|
+
for (const rawLine of block.split("\n")) {
|
|
418
|
+
const line = rawLine.replace(/\s+$/, "");
|
|
419
|
+
if (line.length === 0 || line.startsWith(":")) continue;
|
|
420
|
+
if (line.startsWith("id:")) {
|
|
421
|
+
id = line.slice(3).trim();
|
|
422
|
+
} else if (line.startsWith("data:")) {
|
|
423
|
+
dataLines.push(line.slice(5).replace(/^ /, ""));
|
|
424
|
+
}
|
|
425
|
+
}
|
|
426
|
+
if (dataLines.length === 0) return null;
|
|
427
|
+
let decoded;
|
|
428
|
+
try {
|
|
429
|
+
decoded = JSON.parse(dataLines.join("\n"));
|
|
430
|
+
} catch {
|
|
431
|
+
return null;
|
|
432
|
+
}
|
|
433
|
+
if (typeof decoded !== "object" || decoded === null || Array.isArray(decoded)) return null;
|
|
434
|
+
const parsed = wireObjectSchema.safeParse(decoded);
|
|
435
|
+
if (!parsed.success) return null;
|
|
436
|
+
return frameFromWire(parsed.data, id, serverRequestId);
|
|
437
|
+
}
|
|
438
|
+
function frameFromWire(json, lastEventId, serverRequestId) {
|
|
439
|
+
const type = json["type"];
|
|
440
|
+
const event = json["event"];
|
|
441
|
+
if (type === "error" || "error" in json) {
|
|
442
|
+
return errorFrame({
|
|
443
|
+
code: asString(json["code"]) ?? "unknown",
|
|
444
|
+
retryable: json["retryable"] === true,
|
|
445
|
+
wireMessage: asString(json["error"]),
|
|
446
|
+
synthesized: false,
|
|
447
|
+
lastEventId,
|
|
448
|
+
serverRequestId
|
|
449
|
+
});
|
|
450
|
+
}
|
|
451
|
+
if (type === "done" || json["done"] === true) {
|
|
452
|
+
return doneFrame({
|
|
453
|
+
conversationId: asString(json["conversation_id"]) ?? "",
|
|
454
|
+
messageId: asString(json["message_id"]),
|
|
455
|
+
title: asString(json["title"]),
|
|
456
|
+
followUpQuestions: asStringList(json["follow_up_questions"]),
|
|
457
|
+
citations: asMapList(json["citations"]),
|
|
458
|
+
citationStatus: asString(json["citation_status"]),
|
|
459
|
+
urgencyLevel: asUrgency(json["urgency_level"]),
|
|
460
|
+
urgencyReason: asString(json["urgency_reason"]),
|
|
461
|
+
resultId: asString(json["result_id"]),
|
|
462
|
+
lastEventId
|
|
463
|
+
}, serverRequestId);
|
|
464
|
+
}
|
|
465
|
+
if (type === "accepted" || json["status"] === "reasoning") {
|
|
466
|
+
return acceptedFrame(asString(json["stream_id"]), lastEventId, serverRequestId);
|
|
467
|
+
}
|
|
468
|
+
if (type === "heartbeat" || json["heartbeat"] === true) {
|
|
469
|
+
return heartbeatFrame(lastEventId, serverRequestId);
|
|
470
|
+
}
|
|
471
|
+
if (type === "text.delta" || "delta" in json || "token" in json) {
|
|
472
|
+
const delta = asString(json["delta"]) ?? asString(json["token"]) ?? "";
|
|
473
|
+
return deltaFrame(delta, lastEventId, serverRequestId);
|
|
474
|
+
}
|
|
475
|
+
if (event === "analysis_started") {
|
|
476
|
+
return analysisStartedFrame(asString(json["request_id"]), lastEventId, serverRequestId);
|
|
477
|
+
}
|
|
478
|
+
if (event === "analysis_complete") {
|
|
479
|
+
return analysisCompleteFrame({
|
|
480
|
+
resultId: asString(json["result_id"]),
|
|
481
|
+
analysisType: asString(json["analysis_type"]),
|
|
482
|
+
modelVersion: asString(json["model_version"]),
|
|
483
|
+
confidence: asNumber(json["confidence"]),
|
|
484
|
+
detections: asMapList(json["detections"]),
|
|
485
|
+
interpretation: asString(json["interpretation"]),
|
|
486
|
+
lastEventId
|
|
487
|
+
}, serverRequestId);
|
|
488
|
+
}
|
|
489
|
+
return unknownFrame(json, lastEventId, serverRequestId);
|
|
490
|
+
}
|
|
491
|
+
function asString(v) {
|
|
492
|
+
return typeof v === "string" ? v : null;
|
|
493
|
+
}
|
|
494
|
+
function asNumber(v) {
|
|
495
|
+
return typeof v === "number" && Number.isFinite(v) ? v : null;
|
|
496
|
+
}
|
|
497
|
+
function asUrgency(v) {
|
|
498
|
+
return typeof v === "string" && URGENCY_LEVELS.includes(v) ? v : null;
|
|
499
|
+
}
|
|
500
|
+
function asStringList(v) {
|
|
501
|
+
if (!Array.isArray(v)) return [];
|
|
502
|
+
return v.map((e) => typeof e === "string" ? e : String(e));
|
|
503
|
+
}
|
|
504
|
+
function isPlainObject(v) {
|
|
505
|
+
return typeof v === "object" && v !== null && !Array.isArray(v);
|
|
506
|
+
}
|
|
507
|
+
function asMapList(v) {
|
|
508
|
+
if (!Array.isArray(v)) return [];
|
|
509
|
+
return v.filter(isPlainObject);
|
|
510
|
+
}
|
|
511
|
+
|
|
512
|
+
// src/client/errors/EverfurError.ts
|
|
513
|
+
var USER_FACING_COPY = Object.freeze({
|
|
514
|
+
authExpired: "Please sign in again to continue.",
|
|
515
|
+
authRejected: "Please sign in again to continue.",
|
|
516
|
+
sessionRequired: "This app needs to be updated to keep using Everfur.",
|
|
517
|
+
accessDenied: "This feature isn't available on your account right now.",
|
|
518
|
+
paymentRequired: "This is part of a paid plan.",
|
|
519
|
+
quotaExceeded: "You have used today's messages. This resets tomorrow.",
|
|
520
|
+
rateLimited: "You are sending messages quickly. Try again in a few seconds.",
|
|
521
|
+
validationFailed: "Something in that request was not right. Check the details and try again.",
|
|
522
|
+
sdkUpdateRequired: "This app needs to be updated to keep using Everfur.",
|
|
523
|
+
conflict: "That is already running. Wait for it to finish, then try again.",
|
|
524
|
+
idempotencyConflict: "That message was already delivered.",
|
|
525
|
+
idempotencyInFlight: "That is still processing. Give it a moment.",
|
|
526
|
+
conversationNotFound: "This conversation is no longer available.",
|
|
527
|
+
petNotFound: "We could not find that pet. Please pick a pet and try again.",
|
|
528
|
+
resourceNotFound: "We could not find that.",
|
|
529
|
+
streamTimeout: "The response timed out. Tap retry to try again.",
|
|
530
|
+
mediaUploadFailed: "We could not upload that photo. Please attach it again.",
|
|
531
|
+
moderationBlocked: "This request cannot be answered here.",
|
|
532
|
+
upstreamLlmTimeout: "The response timed out. Tap retry to try again.",
|
|
533
|
+
internalError: "We hit a snag on our end. Please try again.",
|
|
534
|
+
notImplemented: "That is not available yet.",
|
|
535
|
+
serviceUnavailable: "That service is briefly unavailable. Try again shortly.",
|
|
536
|
+
streamIncomplete: "The connection dropped mid-answer. Tap retry to continue.",
|
|
537
|
+
unknown: "Something went wrong. Please try again."
|
|
538
|
+
});
|
|
539
|
+
function userFacingError(code) {
|
|
540
|
+
return USER_FACING_COPY[code];
|
|
541
|
+
}
|
|
542
|
+
function defineHidden(target, key, value) {
|
|
543
|
+
Object.defineProperty(target, key, {
|
|
544
|
+
value,
|
|
545
|
+
enumerable: false,
|
|
546
|
+
writable: false,
|
|
547
|
+
configurable: false
|
|
548
|
+
});
|
|
549
|
+
}
|
|
550
|
+
function makeEverfurError(code, opts) {
|
|
551
|
+
contractErrorFor(opts?.wireCode);
|
|
552
|
+
const error = {
|
|
553
|
+
code,
|
|
554
|
+
category: categoryFor(code),
|
|
555
|
+
retryable: opts?.retryable ?? isRetryableCode(code),
|
|
556
|
+
displayMessage: userFacingError(code)
|
|
557
|
+
};
|
|
558
|
+
if (opts?.httpStatus !== void 0) error.httpStatus = opts.httpStatus;
|
|
559
|
+
if (opts?.requestId) error.requestId = opts.requestId;
|
|
560
|
+
if (opts?.wireMessage) defineHidden(error, "wireMessage", opts.wireMessage);
|
|
561
|
+
if (opts?.raw !== void 0 && opts.raw !== null) defineHidden(error, "raw", opts.raw);
|
|
562
|
+
return Object.freeze(error);
|
|
563
|
+
}
|
|
564
|
+
|
|
565
|
+
// src/client/transport.ts
|
|
566
|
+
async function* bufferedTextByteSource(text, splitAt = []) {
|
|
567
|
+
const bytes = new TextEncoder().encode(text);
|
|
568
|
+
const points = [...new Set(splitAt)].filter((n) => n > 0 && n < bytes.length).sort((a, b) => a - b);
|
|
569
|
+
let start = 0;
|
|
570
|
+
for (const point of points) {
|
|
571
|
+
yield bytes.subarray(start, point);
|
|
572
|
+
start = point;
|
|
573
|
+
}
|
|
574
|
+
yield bytes.subarray(start);
|
|
575
|
+
}
|
|
576
|
+
function errorFromResponse(status, body, requestId) {
|
|
577
|
+
const wireCode = extractWireCode(body);
|
|
578
|
+
const code = wireCode ? fromWire(wireCode) : fromHttpStatus(status);
|
|
579
|
+
const wireMessage = extractWireMessage(body);
|
|
580
|
+
return makeEverfurError(code, {
|
|
581
|
+
httpStatus: status,
|
|
582
|
+
...extractRetryable(body) ? { retryable: true } : {},
|
|
583
|
+
...{},
|
|
584
|
+
...wireCode ? { wireCode } : {},
|
|
585
|
+
...wireMessage ? { wireMessage } : {},
|
|
586
|
+
...body !== null && body !== void 0 ? { raw: body } : {}
|
|
587
|
+
});
|
|
588
|
+
}
|
|
589
|
+
function extractWireCode(body) {
|
|
590
|
+
const b = body;
|
|
591
|
+
const code = b?.error?.code ?? b?.code;
|
|
592
|
+
return typeof code === "string" && code.length > 0 ? code : null;
|
|
593
|
+
}
|
|
594
|
+
function extractWireMessage(body) {
|
|
595
|
+
const b = body;
|
|
596
|
+
const message = b?.error?.message ?? b?.message;
|
|
597
|
+
return typeof message === "string" && message.length > 0 ? message : null;
|
|
598
|
+
}
|
|
599
|
+
function extractRetryable(body) {
|
|
600
|
+
const b = body;
|
|
601
|
+
return b?.error?.retryable === true || b?.retryable === true;
|
|
602
|
+
}
|
|
603
|
+
|
|
604
|
+
// src/core/testing/MockTransport.ts
|
|
605
|
+
var wire = Object.freeze({
|
|
606
|
+
accepted: (streamId) => JSON.stringify(streamId ? { type: "accepted", stream_id: streamId } : { type: "accepted" }),
|
|
607
|
+
heartbeat: () => JSON.stringify({ type: "heartbeat" }),
|
|
608
|
+
delta: (text) => JSON.stringify({ type: "text.delta", delta: text }),
|
|
609
|
+
done: (fields) => JSON.stringify({ type: "done", ...fields ?? {} }),
|
|
610
|
+
error: (code, retryable = false) => JSON.stringify({ type: "error", code, retryable })
|
|
611
|
+
});
|
|
612
|
+
function assertRouteIsServed(method, path) {
|
|
613
|
+
const verdict = classifyRoute(method, path);
|
|
614
|
+
if (verdict === "known") return;
|
|
615
|
+
if (verdict === "absent") {
|
|
616
|
+
throw new EverfurConfigError(
|
|
617
|
+
"invalid-argument",
|
|
618
|
+
`MockTransport: ${method} ${path} is a route the Everfur backend does NOT serve, so this call returns 404 in production. Scripting a success for it makes a green test that hides a broken integration. Known-absent routes: ${KNOWN_ABSENT_ROUTES.join(", ")}. Pass { strictPaths: false } to MockTransport only if you are deliberately testing this shape.`
|
|
619
|
+
);
|
|
620
|
+
}
|
|
621
|
+
throw new EverfurConfigError(
|
|
622
|
+
"invalid-argument",
|
|
623
|
+
`MockTransport: ${method} ${path} is not a known partner-plane route. If the backend has gained it, add it to KNOWN_PARTNER_ROUTES in src/core/testing/knownRoutes.ts. Pass { strictPaths: false } to opt out for this transport.`
|
|
624
|
+
);
|
|
625
|
+
}
|
|
626
|
+
var MockTransport = class {
|
|
627
|
+
constructor(options = {}) {
|
|
628
|
+
this.streamQueue = [];
|
|
629
|
+
this.requestQueue = [];
|
|
630
|
+
/** The last script dequeued, replayed once the queue drains. See `request` for why. */
|
|
631
|
+
/**
|
|
632
|
+
* The last scripted response, KEYED BY ENDPOINT.
|
|
633
|
+
*
|
|
634
|
+
* It used to be a single field, so a `enqueueRequest({ status: 500 })` scripted for one endpoint kept
|
|
635
|
+
* replaying for every OTHER endpoint once the queue drained — the comment below says the fallback means
|
|
636
|
+
* "this endpoint is down", and a global field cannot mean that. A fault leaked across endpoints and a
|
|
637
|
+
* test could assert an outcome the SDK would never produce.
|
|
638
|
+
*/
|
|
639
|
+
this.lastRequestScript = /* @__PURE__ */ new Map();
|
|
640
|
+
this.openCount = 0;
|
|
641
|
+
this.requests = [];
|
|
642
|
+
this.streamRequests = [];
|
|
643
|
+
/** Peak concurrent open streams observed (bulkhead assertions). */
|
|
644
|
+
this.peak = 0;
|
|
645
|
+
this.strictPaths = options.strictPaths ?? true;
|
|
646
|
+
}
|
|
647
|
+
/** Live count of streams that have opened but not yet torn down. MUST return to 0 after a cancel. */
|
|
648
|
+
get openStreams() {
|
|
649
|
+
return this.openCount;
|
|
650
|
+
}
|
|
651
|
+
get peakOpenStreams() {
|
|
652
|
+
return this.peak;
|
|
653
|
+
}
|
|
654
|
+
enqueueStream(...scripts) {
|
|
655
|
+
this.streamQueue.push(...scripts);
|
|
656
|
+
return this;
|
|
657
|
+
}
|
|
658
|
+
enqueueRequest(...scripts) {
|
|
659
|
+
this.requestQueue.push(...scripts);
|
|
660
|
+
return this;
|
|
661
|
+
}
|
|
662
|
+
async request(req) {
|
|
663
|
+
if (this.strictPaths) assertRouteIsServed(req.method, req.path);
|
|
664
|
+
const base = {
|
|
665
|
+
method: req.method,
|
|
666
|
+
path: req.path,
|
|
667
|
+
headers: { ...req.headers ?? {} },
|
|
668
|
+
...req.query === void 0 ? {} : { query: { ...req.query } }
|
|
669
|
+
};
|
|
670
|
+
const record = req.body === void 0 ? base : { ...base, body: req.body };
|
|
671
|
+
this.requests.push(record);
|
|
672
|
+
const endpoint = `${req.method} ${req.path}`;
|
|
673
|
+
const next = this.requestQueue.shift();
|
|
674
|
+
if (next !== void 0) this.lastRequestScript.set(endpoint, next);
|
|
675
|
+
const script = next ?? this.lastRequestScript.get(endpoint) ?? { status: 200, body: {} };
|
|
676
|
+
const status = script.status ?? 200;
|
|
677
|
+
if (status === 304 || status >= 400) {
|
|
678
|
+
return err(errorFromResponse(status, script.body ?? null));
|
|
679
|
+
}
|
|
680
|
+
return ok(script.body ?? {});
|
|
681
|
+
}
|
|
682
|
+
stream(req, signal) {
|
|
683
|
+
if (this.strictPaths) assertRouteIsServed(req.method, req.path);
|
|
684
|
+
this.streamRequests.push({
|
|
685
|
+
path: req.path,
|
|
686
|
+
authorization: header(req, "authorization"),
|
|
687
|
+
partnerKey: header(req, "x-everfur-partner-key"),
|
|
688
|
+
idempotencyKey: header(req, "idempotency-key"),
|
|
689
|
+
...req.body === void 0 ? {} : { body: req.body },
|
|
690
|
+
headers: { ...req.headers ?? {} }
|
|
691
|
+
});
|
|
692
|
+
const script = this.streamQueue.shift() ?? { kind: "sse", blocks: [wire.done()] };
|
|
693
|
+
return this.openStream(script, signal);
|
|
694
|
+
}
|
|
695
|
+
async *openStream(script, signal) {
|
|
696
|
+
this.openCount += 1;
|
|
697
|
+
if (this.openCount > this.peak) this.peak = this.openCount;
|
|
698
|
+
try {
|
|
699
|
+
yield* this.runScript(script, signal);
|
|
700
|
+
} finally {
|
|
701
|
+
this.openCount -= 1;
|
|
702
|
+
}
|
|
703
|
+
}
|
|
704
|
+
async *runScript(script, signal) {
|
|
705
|
+
switch (script.kind) {
|
|
706
|
+
case "httpError": {
|
|
707
|
+
const wireCode = extractWireCode2(script.body) ?? statusToWireCode(script.status);
|
|
708
|
+
yield errorFrame({
|
|
709
|
+
code: wireCode,
|
|
710
|
+
retryable: extractRetryable2(script.body) || isAutoRetryable(fromWire(wireCode)),
|
|
711
|
+
wireMessage: extractWireMessage2(script.body),
|
|
712
|
+
synthesized: true,
|
|
713
|
+
lastEventId: null
|
|
714
|
+
});
|
|
715
|
+
return;
|
|
716
|
+
}
|
|
717
|
+
case "network":
|
|
718
|
+
yield errorFrame({
|
|
719
|
+
code: "INTERNAL_ERROR",
|
|
720
|
+
retryable: true,
|
|
721
|
+
wireMessage: "network request failed",
|
|
722
|
+
synthesized: true,
|
|
723
|
+
lastEventId: null
|
|
724
|
+
});
|
|
725
|
+
return;
|
|
726
|
+
case "partialByte":
|
|
727
|
+
yield* parseSse(bufferedTextByteSource(script.body, script.splitAt));
|
|
728
|
+
return;
|
|
729
|
+
case "sse":
|
|
730
|
+
yield* parseSse(sseByteSource(script.blocks, script.gapMs ?? 0, signal));
|
|
731
|
+
return;
|
|
732
|
+
case "drop":
|
|
733
|
+
yield* parseSse(sseByteSource(script.blocks, 0, signal));
|
|
734
|
+
return;
|
|
735
|
+
case "stall":
|
|
736
|
+
yield* parseSse(stallByteSource(script.preface ?? [], signal));
|
|
737
|
+
return;
|
|
738
|
+
default:
|
|
739
|
+
return assertNever(script);
|
|
740
|
+
}
|
|
741
|
+
}
|
|
742
|
+
};
|
|
743
|
+
async function* sseByteSource(blocks, gapMs, signal) {
|
|
744
|
+
const enc = new TextEncoder();
|
|
745
|
+
let first = true;
|
|
746
|
+
for (const block of blocks) {
|
|
747
|
+
if (signal.aborted) return;
|
|
748
|
+
if (!first && gapMs > 0) {
|
|
749
|
+
const outcome = await abortableSleep(gapMs, signal);
|
|
750
|
+
if (outcome === "abort") return;
|
|
751
|
+
}
|
|
752
|
+
first = false;
|
|
753
|
+
yield enc.encode(toSseBlock(block));
|
|
754
|
+
}
|
|
755
|
+
}
|
|
756
|
+
async function* stallByteSource(preface, signal) {
|
|
757
|
+
const enc = new TextEncoder();
|
|
758
|
+
for (const block of preface) {
|
|
759
|
+
if (signal.aborted) return;
|
|
760
|
+
yield enc.encode(toSseBlock(block));
|
|
761
|
+
}
|
|
762
|
+
await abortableSleep(Infinity, signal);
|
|
763
|
+
}
|
|
764
|
+
function toSseBlock(payload) {
|
|
765
|
+
return `data: ${payload}
|
|
766
|
+
|
|
767
|
+
`;
|
|
768
|
+
}
|
|
769
|
+
function abortableSleep(ms, signal) {
|
|
770
|
+
return new Promise((resolve) => {
|
|
771
|
+
if (signal.aborted) {
|
|
772
|
+
resolve("abort");
|
|
773
|
+
return;
|
|
774
|
+
}
|
|
775
|
+
let handle = null;
|
|
776
|
+
const onAbort = () => {
|
|
777
|
+
if (handle !== null) clearTimeout(handle);
|
|
778
|
+
signal.removeEventListener("abort", onAbort);
|
|
779
|
+
resolve("abort");
|
|
780
|
+
};
|
|
781
|
+
if (Number.isFinite(ms)) {
|
|
782
|
+
handle = setTimeout(() => {
|
|
783
|
+
signal.removeEventListener("abort", onAbort);
|
|
784
|
+
resolve("timeout");
|
|
785
|
+
}, ms);
|
|
786
|
+
}
|
|
787
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
788
|
+
});
|
|
789
|
+
}
|
|
790
|
+
function header(req, name) {
|
|
791
|
+
const headers = req.headers;
|
|
792
|
+
if (!headers) return null;
|
|
793
|
+
for (const [key, value] of Object.entries(headers)) {
|
|
794
|
+
if (key.toLowerCase() === name) return value;
|
|
795
|
+
}
|
|
796
|
+
return null;
|
|
797
|
+
}
|
|
798
|
+
function extractWireCode2(body) {
|
|
799
|
+
const b = body;
|
|
800
|
+
const code = b?.error?.code ?? b?.code;
|
|
801
|
+
return typeof code === "string" && code.length > 0 ? code : null;
|
|
802
|
+
}
|
|
803
|
+
function extractWireMessage2(body) {
|
|
804
|
+
const b = body;
|
|
805
|
+
const message = b?.error?.message ?? b?.message;
|
|
806
|
+
return typeof message === "string" && message.length > 0 ? message : null;
|
|
807
|
+
}
|
|
808
|
+
function extractRetryable2(body) {
|
|
809
|
+
const b = body;
|
|
810
|
+
return b?.error?.retryable === true || b?.retryable === true;
|
|
811
|
+
}
|
|
812
|
+
function statusToWireCode(status) {
|
|
813
|
+
if (status === 401) return "AUTH_EXPIRED";
|
|
814
|
+
if (status === 403) return "ACCESS_DENIED";
|
|
815
|
+
if (status === 404) return "NOT_FOUND";
|
|
816
|
+
if (status === 409) return "IDEMPOTENCY_CONFLICT";
|
|
817
|
+
if (status === 421) return "MISDIRECTED_REQUEST";
|
|
818
|
+
if (status === 429) return "RATE_LIMITED";
|
|
819
|
+
if (status === 400 || status === 422) return "INVALID_REQUEST";
|
|
820
|
+
if (status >= 500) return "INTERNAL_ERROR";
|
|
821
|
+
return "";
|
|
822
|
+
}
|
|
823
|
+
|
|
824
|
+
exports.MockTransport = MockTransport;
|
|
825
|
+
exports.wire = wire;
|