@pdfvector/client 0.0.54 → 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/dist/index.mjs ADDED
@@ -0,0 +1,1871 @@
1
+ Array.isArray;
2
+ // ../../node_modules/.bun/@orpc+shared@1.15.2+e40b0dfdd726a224/node_modules/@orpc/shared/dist/index.mjs
3
+ function resolveMaybeOptionalOptions(rest) {
4
+ return rest[0] ?? {};
5
+ }
6
+ function toArray(value) {
7
+ return Array.isArray(value) ? value : value === void 0 || value === null ? [] : [value];
8
+ }
9
+ const ORPC_NAME = "orpc";
10
+ const ORPC_SHARED_PACKAGE_NAME = "@orpc/shared";
11
+ const ORPC_SHARED_PACKAGE_VERSION = "1.15.2";
12
+ var AbortError = class extends Error {
13
+ constructor(...rest) {
14
+ super(...rest);
15
+ this.name = "AbortError";
16
+ }
17
+ };
18
+ function once(fn) {
19
+ let cached;
20
+ return () => {
21
+ if (cached) return cached.result;
22
+ const result = fn();
23
+ cached = { result };
24
+ return result;
25
+ };
26
+ }
27
+ function sequential(fn) {
28
+ let lastOperationPromise = Promise.resolve();
29
+ return (...args) => {
30
+ return lastOperationPromise = lastOperationPromise.catch(() => {}).then(() => {
31
+ return fn(...args);
32
+ });
33
+ };
34
+ }
35
+ const SPAN_ERROR_STATUS = 2;
36
+ const GLOBAL_OTEL_CONFIG_KEY = `__${ORPC_SHARED_PACKAGE_NAME}@${ORPC_SHARED_PACKAGE_VERSION}/otel/config__`;
37
+ function getGlobalOtelConfig() {
38
+ return globalThis[GLOBAL_OTEL_CONFIG_KEY];
39
+ }
40
+ function startSpan(name, options = {}, context) {
41
+ return (getGlobalOtelConfig()?.tracer)?.startSpan(name, options, context);
42
+ }
43
+ function setSpanError(span, error, options = {}) {
44
+ if (!span) return;
45
+ const exception = toOtelException(error);
46
+ span.recordException(exception);
47
+ if (!options.signal?.aborted || options.signal.reason !== error) span.setStatus({
48
+ code: SPAN_ERROR_STATUS,
49
+ message: exception.message
50
+ });
51
+ }
52
+ function toOtelException(error) {
53
+ if (error instanceof Error) {
54
+ const exception = {
55
+ message: error.message,
56
+ name: error.name,
57
+ stack: error.stack
58
+ };
59
+ if ("code" in error && (typeof error.code === "string" || typeof error.code === "number")) exception.code = error.code;
60
+ return exception;
61
+ }
62
+ return { message: String(error) };
63
+ }
64
+ async function runWithSpan({ name, context, ...options }, fn) {
65
+ const tracer = getGlobalOtelConfig()?.tracer;
66
+ if (!tracer) return fn();
67
+ const callback = async (span) => {
68
+ try {
69
+ return await fn(span);
70
+ } catch (e) {
71
+ setSpanError(span, e, options);
72
+ throw e;
73
+ } finally {
74
+ span.end();
75
+ }
76
+ };
77
+ if (context) return tracer.startActiveSpan(name, options, context, callback);
78
+ else return tracer.startActiveSpan(name, options, callback);
79
+ }
80
+ async function runInSpanContext(span, fn) {
81
+ const otelConfig = getGlobalOtelConfig();
82
+ if (!span || !otelConfig) return fn();
83
+ const ctx = otelConfig.trace.setSpan(otelConfig.context.active(), span);
84
+ return otelConfig.context.with(ctx, fn);
85
+ }
86
+ function isAsyncIteratorObject(maybe) {
87
+ if (!maybe || typeof maybe !== "object") return false;
88
+ return "next" in maybe && typeof maybe.next === "function" && Symbol.asyncIterator in maybe && typeof maybe[Symbol.asyncIterator] === "function";
89
+ }
90
+ const asyncDisposeSymbol = Symbol.asyncDispose ?? Symbol.for("asyncDispose");
91
+ var AsyncIteratorClass = class {
92
+ #isDone = false;
93
+ #isExecuteComplete = false;
94
+ #cleanup;
95
+ #next;
96
+ constructor(next, cleanup) {
97
+ this.#cleanup = cleanup;
98
+ this.#next = sequential(async () => {
99
+ if (this.#isDone) return {
100
+ done: true,
101
+ value: void 0
102
+ };
103
+ try {
104
+ const result = await next();
105
+ if (result.done) this.#isDone = true;
106
+ return result;
107
+ } catch (err) {
108
+ this.#isDone = true;
109
+ throw err;
110
+ } finally {
111
+ if (this.#isDone && !this.#isExecuteComplete) {
112
+ this.#isExecuteComplete = true;
113
+ await this.#cleanup("next");
114
+ }
115
+ }
116
+ });
117
+ }
118
+ next() {
119
+ return this.#next();
120
+ }
121
+ async return(value) {
122
+ this.#isDone = true;
123
+ if (!this.#isExecuteComplete) {
124
+ this.#isExecuteComplete = true;
125
+ await this.#cleanup("return");
126
+ }
127
+ return {
128
+ done: true,
129
+ value
130
+ };
131
+ }
132
+ async throw(err) {
133
+ this.#isDone = true;
134
+ if (!this.#isExecuteComplete) {
135
+ this.#isExecuteComplete = true;
136
+ await this.#cleanup("throw");
137
+ }
138
+ throw err;
139
+ }
140
+ /**
141
+ * asyncDispose symbol only available in esnext, we should fallback to Symbol.for('asyncDispose')
142
+ */
143
+ async [asyncDisposeSymbol]() {
144
+ this.#isDone = true;
145
+ if (!this.#isExecuteComplete) {
146
+ this.#isExecuteComplete = true;
147
+ await this.#cleanup("dispose");
148
+ }
149
+ }
150
+ [Symbol.asyncIterator]() {
151
+ return this;
152
+ }
153
+ };
154
+ function asyncIteratorWithSpan({ name, ...options }, iterator) {
155
+ let span;
156
+ return new AsyncIteratorClass(async () => {
157
+ span ??= startSpan(name);
158
+ try {
159
+ const result = await runInSpanContext(span, () => iterator.next());
160
+ span?.addEvent(result.done ? "completed" : "yielded");
161
+ return result;
162
+ } catch (err) {
163
+ setSpanError(span, err, options);
164
+ throw err;
165
+ }
166
+ }, async (reason) => {
167
+ try {
168
+ if (reason !== "next") await runInSpanContext(span, () => iterator.return?.());
169
+ } catch (err) {
170
+ setSpanError(span, err, options);
171
+ throw err;
172
+ } finally {
173
+ span?.end();
174
+ }
175
+ });
176
+ }
177
+ function onError(callback) {
178
+ return async (options, ...rest) => {
179
+ try {
180
+ return await options.next();
181
+ } catch (error) {
182
+ await callback(error, options, ...rest);
183
+ throw error;
184
+ }
185
+ };
186
+ }
187
+ function intercept(interceptors, options, main) {
188
+ const next = (options2, index) => {
189
+ const interceptor = interceptors[index];
190
+ if (!interceptor) return main(options2);
191
+ return interceptor({
192
+ ...options2,
193
+ next: (newOptions = options2) => next(newOptions, index + 1)
194
+ });
195
+ };
196
+ return next(options, 0);
197
+ }
198
+ function parseEmptyableJSON(text) {
199
+ if (!text) return;
200
+ return JSON.parse(text);
201
+ }
202
+ function stringifyJSON(value) {
203
+ return JSON.stringify(value);
204
+ }
205
+ function getConstructor(value) {
206
+ if (!isTypescriptObject(value)) return null;
207
+ return Object.getPrototypeOf(value)?.constructor;
208
+ }
209
+ function isObject(value) {
210
+ if (!value || typeof value !== "object") return false;
211
+ const proto = Object.getPrototypeOf(value);
212
+ return proto === Object.prototype || !proto || !proto.constructor;
213
+ }
214
+ function isTypescriptObject(value) {
215
+ return !!value && (typeof value === "object" || typeof value === "function");
216
+ }
217
+ function value(value2, ...args) {
218
+ if (typeof value2 === "function") return value2(...args);
219
+ return value2;
220
+ }
221
+ function preventNativeAwait(target) {
222
+ return new Proxy(target, { get(target2, prop, receiver) {
223
+ const value2 = Reflect.get(target2, prop, receiver);
224
+ if (prop !== "then" || typeof value2 !== "function") return value2;
225
+ return new Proxy(value2, { apply(targetFn, thisArg, args) {
226
+ if (args.length !== 2 || args.some((arg) => !isNativeFunction(arg))) return Reflect.apply(targetFn, thisArg, args);
227
+ let shouldOmit = true;
228
+ args[0].call(thisArg, preventNativeAwait(new Proxy(target2, { get: (target3, prop2, receiver2) => {
229
+ if (shouldOmit && prop2 === "then") {
230
+ shouldOmit = false;
231
+ return;
232
+ }
233
+ return Reflect.get(target3, prop2, receiver2);
234
+ } })));
235
+ } });
236
+ } });
237
+ }
238
+ const NATIVE_FUNCTION_REGEX = /^\s*function\s*\(\)\s*\{\s*\[native code\]\s*\}\s*$/;
239
+ function isNativeFunction(fn) {
240
+ return typeof fn === "function" && NATIVE_FUNCTION_REGEX.test(fn.toString());
241
+ }
242
+ const REGEXP_FLAGS = /^[dgimsuvy]*$/;
243
+ function isValidRegExpFlags(flags) {
244
+ return REGEXP_FLAGS.test(flags) && new Set(flags).size === flags.length && !(flags.includes("u") && flags.includes("v"));
245
+ }
246
+ function createLazyRegExp(pattern, flags) {
247
+ let compiled;
248
+ let lastIndex = 0;
249
+ const compile = () => {
250
+ if (compiled === void 0) {
251
+ compiled = new RegExp(pattern, flags);
252
+ compiled.lastIndex = lastIndex;
253
+ }
254
+ return compiled;
255
+ };
256
+ return new Proxy(Object.create(RegExp.prototype), {
257
+ get(_, prop) {
258
+ if (prop === Symbol.toStringTag) return "RegExp";
259
+ if (compiled === void 0) {
260
+ if (prop === "lastIndex") return lastIndex;
261
+ if (!(prop in RegExp.prototype)) return;
262
+ }
263
+ const target = compile();
264
+ const value = Reflect.get(target, prop, target);
265
+ return typeof value === "function" && prop !== "constructor" ? value.bind(target) : value;
266
+ },
267
+ set(_, prop, value) {
268
+ if (compiled === void 0 && prop === "lastIndex") {
269
+ lastIndex = value;
270
+ return true;
271
+ }
272
+ const target = compile();
273
+ return Reflect.set(target, prop, value, target);
274
+ },
275
+ has(_, prop) {
276
+ if (compiled === void 0) return prop === "lastIndex" || prop in RegExp.prototype;
277
+ return Reflect.has(compiled, prop);
278
+ }
279
+ });
280
+ }
281
+ function tryDecodeURIComponent(value) {
282
+ try {
283
+ return decodeURIComponent(value);
284
+ } catch {
285
+ return value;
286
+ }
287
+ }
288
+ // ../../node_modules/.bun/@orpc+client@1.15.2+e40b0dfdd726a224/node_modules/@orpc/client/dist/shared/client.t2tsjbV-.mjs
289
+ const ORPC_CLIENT_PACKAGE_NAME = "@orpc/client";
290
+ const ORPC_CLIENT_PACKAGE_VERSION = "1.15.2";
291
+ const RECURSIVE_CLIENT_UNWRAP_KEYS = /* @__PURE__ */ new Set([
292
+ "bind",
293
+ "valueOf",
294
+ "toString",
295
+ "toJSON"
296
+ ]);
297
+ const COMMON_ORPC_ERROR_DEFS = {
298
+ BAD_REQUEST: {
299
+ status: 400,
300
+ message: "Bad Request"
301
+ },
302
+ UNAUTHORIZED: {
303
+ status: 401,
304
+ message: "Unauthorized"
305
+ },
306
+ FORBIDDEN: {
307
+ status: 403,
308
+ message: "Forbidden"
309
+ },
310
+ NOT_FOUND: {
311
+ status: 404,
312
+ message: "Not Found"
313
+ },
314
+ METHOD_NOT_SUPPORTED: {
315
+ status: 405,
316
+ message: "Method Not Supported"
317
+ },
318
+ NOT_ACCEPTABLE: {
319
+ status: 406,
320
+ message: "Not Acceptable"
321
+ },
322
+ TIMEOUT: {
323
+ status: 408,
324
+ message: "Request Timeout"
325
+ },
326
+ CONFLICT: {
327
+ status: 409,
328
+ message: "Conflict"
329
+ },
330
+ PRECONDITION_FAILED: {
331
+ status: 412,
332
+ message: "Precondition Failed"
333
+ },
334
+ PAYLOAD_TOO_LARGE: {
335
+ status: 413,
336
+ message: "Payload Too Large"
337
+ },
338
+ UNSUPPORTED_MEDIA_TYPE: {
339
+ status: 415,
340
+ message: "Unsupported Media Type"
341
+ },
342
+ UNPROCESSABLE_CONTENT: {
343
+ status: 422,
344
+ message: "Unprocessable Content"
345
+ },
346
+ TOO_MANY_REQUESTS: {
347
+ status: 429,
348
+ message: "Too Many Requests"
349
+ },
350
+ CLIENT_CLOSED_REQUEST: {
351
+ status: 499,
352
+ message: "Client Closed Request"
353
+ },
354
+ INTERNAL_SERVER_ERROR: {
355
+ status: 500,
356
+ message: "Internal Server Error"
357
+ },
358
+ NOT_IMPLEMENTED: {
359
+ status: 501,
360
+ message: "Not Implemented"
361
+ },
362
+ BAD_GATEWAY: {
363
+ status: 502,
364
+ message: "Bad Gateway"
365
+ },
366
+ SERVICE_UNAVAILABLE: {
367
+ status: 503,
368
+ message: "Service Unavailable"
369
+ },
370
+ GATEWAY_TIMEOUT: {
371
+ status: 504,
372
+ message: "Gateway Timeout"
373
+ }
374
+ };
375
+ function fallbackORPCErrorStatus(code, status) {
376
+ return status ?? COMMON_ORPC_ERROR_DEFS[code]?.status ?? 500;
377
+ }
378
+ function fallbackORPCErrorMessage(code, message) {
379
+ return message || COMMON_ORPC_ERROR_DEFS[code]?.message || code;
380
+ }
381
+ let globalORPCErrorConstructors;
382
+ var ORPCError = class ORPCError extends Error {
383
+ defined;
384
+ code;
385
+ status;
386
+ data;
387
+ static {
388
+ const GLOBAL_ORPC_ERROR_CONSTRUCTORS_SYMBOL = Symbol.for(`__${ORPC_CLIENT_PACKAGE_NAME}@${ORPC_CLIENT_PACKAGE_VERSION}/error/ORPC_ERROR_CONSTRUCTORS__`);
389
+ globalThis[GLOBAL_ORPC_ERROR_CONSTRUCTORS_SYMBOL] ??= /* @__PURE__ */ new WeakSet();
390
+ globalORPCErrorConstructors = globalThis[GLOBAL_ORPC_ERROR_CONSTRUCTORS_SYMBOL];
391
+ globalORPCErrorConstructors.add(ORPCError);
392
+ }
393
+ constructor(code, ...rest) {
394
+ const options = resolveMaybeOptionalOptions(rest);
395
+ if (options.status !== void 0 && !isORPCErrorStatus(options.status)) throw new Error("[ORPCError] Invalid error status code.");
396
+ const message = fallbackORPCErrorMessage(code, options.message);
397
+ super(message, options);
398
+ this.code = code;
399
+ this.status = fallbackORPCErrorStatus(code, options.status);
400
+ this.defined = options.defined ?? false;
401
+ this.data = options.data;
402
+ }
403
+ toJSON() {
404
+ return {
405
+ defined: this.defined,
406
+ code: this.code,
407
+ status: this.status,
408
+ message: this.message,
409
+ data: this.data
410
+ };
411
+ }
412
+ /**
413
+ * Workaround for Next.js where different contexts use separate
414
+ * dependency graphs, causing multiple ORPCError constructors existing and breaking
415
+ * `instanceof` checks across contexts.
416
+ *
417
+ * This is particularly problematic with "Optimized SSR", where orpc-client
418
+ * executes in one context but is invoked from another. When an error is thrown
419
+ * in the execution context, `instanceof ORPCError` checks fail in the
420
+ * invocation context due to separate class constructors.
421
+ *
422
+ * @todo Remove this and related code if Next.js resolves the multiple dependency graph issue.
423
+ */
424
+ static [Symbol.hasInstance](instance) {
425
+ if (globalORPCErrorConstructors.has(this)) {
426
+ const constructor = getConstructor(instance);
427
+ if (constructor && globalORPCErrorConstructors.has(constructor)) return true;
428
+ }
429
+ return super[Symbol.hasInstance](instance);
430
+ }
431
+ };
432
+ function toORPCError(error) {
433
+ return error instanceof ORPCError ? error : new ORPCError("INTERNAL_SERVER_ERROR", {
434
+ message: "Internal server error",
435
+ cause: error
436
+ });
437
+ }
438
+ function isORPCErrorStatus(status) {
439
+ return status < 200 || status >= 400;
440
+ }
441
+ function isORPCErrorJson(json) {
442
+ if (!isObject(json)) return false;
443
+ const validKeys = [
444
+ "defined",
445
+ "code",
446
+ "status",
447
+ "message",
448
+ "data"
449
+ ];
450
+ if (Object.keys(json).some((k) => !validKeys.includes(k))) return false;
451
+ return "defined" in json && typeof json.defined === "boolean" && "code" in json && typeof json.code === "string" && "status" in json && typeof json.status === "number" && isORPCErrorStatus(json.status) && "message" in json && typeof json.message === "string";
452
+ }
453
+ function createORPCErrorFromJson(json, options = {}) {
454
+ return new ORPCError(json.code, {
455
+ ...options,
456
+ ...json
457
+ });
458
+ }
459
+ // ../../node_modules/.bun/@orpc+standard-server@1.15.2+e40b0dfdd726a224/node_modules/@orpc/standard-server/dist/index.mjs
460
+ var EventEncoderError = class extends TypeError {};
461
+ var EventDecoderError = class extends TypeError {};
462
+ var ErrorEvent = class extends Error {
463
+ data;
464
+ constructor(options) {
465
+ super(options?.message ?? "An error event was received", options);
466
+ this.data = options?.data;
467
+ }
468
+ };
469
+ const LINE_ENDING_REGEX$1 = /\r\n|\r(?!\n)|\n/;
470
+ const MESSAGE_DELIMITER_REGEX = /(?:\r\n|\r(?!\n)|\n){2}/;
471
+ const MESSAGE_DELIMITER_GLOBAL_REGEX = /(?:\r\n|\r(?!\n)|\n){2}/g;
472
+ const CR = 13;
473
+ const LF = 10;
474
+ const SPACE = 32;
475
+ function decodeEventMessage(encoded) {
476
+ const message = {
477
+ data: void 0,
478
+ event: void 0,
479
+ id: void 0,
480
+ retry: void 0,
481
+ comments: []
482
+ };
483
+ for (const line of encoded.split(LINE_ENDING_REGEX$1)) {
484
+ if (line === "") continue;
485
+ const index = line.indexOf(":");
486
+ const value = index === -1 ? "" : line.slice(line.charCodeAt(index + 1) === SPACE ? index + 2 : index + 1);
487
+ if (index === 0) {
488
+ message.comments.push(value);
489
+ continue;
490
+ }
491
+ switch (index === -1 ? line : line.slice(0, index)) {
492
+ case "data":
493
+ message.data = message.data === void 0 ? value : `${message.data}
494
+ ${value}`;
495
+ break;
496
+ case "event":
497
+ message.event = value;
498
+ break;
499
+ case "id":
500
+ message.id = value;
501
+ break;
502
+ case "retry": {
503
+ const maybeInteger = Number.parseInt(value, 10);
504
+ if (maybeInteger >= 0 && maybeInteger.toString() === value) message.retry = maybeInteger;
505
+ break;
506
+ }
507
+ }
508
+ }
509
+ return message;
510
+ }
511
+ var EventDecoder = class {
512
+ constructor(options = {}) {
513
+ this.options = options;
514
+ }
515
+ pending = [];
516
+ tail = "";
517
+ discardLeadingLF = false;
518
+ feed(chunk) {
519
+ if (chunk === "") return;
520
+ if (this.discardLeadingLF) {
521
+ this.discardLeadingLF = false;
522
+ if (chunk.charCodeAt(0) === LF) {
523
+ chunk = chunk.slice(1);
524
+ if (chunk === "") return;
525
+ }
526
+ }
527
+ const scan = this.tail + chunk;
528
+ if (!MESSAGE_DELIMITER_REGEX.test(scan)) {
529
+ this.pending.push(chunk);
530
+ this.tail = scan.slice(-3);
531
+ return;
532
+ }
533
+ this.pending.push(chunk);
534
+ const buffered = this.pending.length === 1 ? chunk : this.pending.join("");
535
+ const offset = buffered.length - scan.length;
536
+ const parts = [];
537
+ let start = 0;
538
+ for (const match of scan.matchAll(MESSAGE_DELIMITER_GLOBAL_REGEX)) {
539
+ parts.push(buffered.slice(start, offset + match.index));
540
+ start = offset + match.index + match[0].length;
541
+ }
542
+ const incomplete = buffered.slice(start);
543
+ this.pending.length = 0;
544
+ this.tail = incomplete.slice(-3);
545
+ if (incomplete === "") this.discardLeadingLF = chunk.charCodeAt(chunk.length - 1) === CR;
546
+ else this.pending.push(incomplete);
547
+ for (const encoded of parts) {
548
+ const message = decodeEventMessage(encoded);
549
+ if (this.options.onEvent) this.options.onEvent(message);
550
+ }
551
+ }
552
+ end() {
553
+ if (this.pending.length !== 0) throw new EventDecoderError("Event Iterator ended before complete");
554
+ }
555
+ };
556
+ var EventDecoderStream = class extends TransformStream {
557
+ constructor() {
558
+ let decoder;
559
+ super({
560
+ start(controller) {
561
+ decoder = new EventDecoder({ onEvent: (event) => {
562
+ controller.enqueue(event);
563
+ } });
564
+ },
565
+ transform(chunk) {
566
+ decoder.feed(chunk);
567
+ },
568
+ flush() {
569
+ decoder.end();
570
+ }
571
+ });
572
+ }
573
+ };
574
+ const LINE_ENDING_REGEX = /\r\n|[\n\r]/;
575
+ const LINE_ENDING_GLOBAL_REGEX = /\r\n|[\n\r]/g;
576
+ function containsLineBreak(value) {
577
+ return LINE_ENDING_REGEX.test(value);
578
+ }
579
+ function assertEventId(id) {
580
+ if (containsLineBreak(id)) throw new EventEncoderError("Event's id must not contain a carriage return or newline character");
581
+ }
582
+ function assertEventName(event) {
583
+ if (containsLineBreak(event)) throw new EventEncoderError("Event's event must not contain a carriage return or newline character");
584
+ }
585
+ function assertEventRetry(retry) {
586
+ if (!Number.isInteger(retry) || retry < 0) throw new EventEncoderError("Event's retry must be a integer and >= 0");
587
+ }
588
+ function assertEventComment(comment) {
589
+ if (containsLineBreak(comment)) throw new EventEncoderError("Event's comment must not contain a carriage return or newline character");
590
+ }
591
+ function encodeEventData(data) {
592
+ if (data === void 0) return "";
593
+ return `data: ${data.replace(LINE_ENDING_GLOBAL_REGEX, "\ndata: ")}
594
+ `;
595
+ }
596
+ function encodeEventComments(comments) {
597
+ let output = "";
598
+ for (const comment of comments ?? []) {
599
+ assertEventComment(comment);
600
+ output += `: ${comment}
601
+ `;
602
+ }
603
+ return output;
604
+ }
605
+ function encodeEventMessage(message) {
606
+ let output = "";
607
+ output += encodeEventComments(message.comments);
608
+ if (message.event !== void 0) {
609
+ assertEventName(message.event);
610
+ output += `event: ${message.event}
611
+ `;
612
+ }
613
+ if (message.retry !== void 0) {
614
+ assertEventRetry(message.retry);
615
+ output += `retry: ${message.retry}
616
+ `;
617
+ }
618
+ if (message.id !== void 0) {
619
+ assertEventId(message.id);
620
+ output += `id: ${message.id}
621
+ `;
622
+ }
623
+ output += encodeEventData(message.data);
624
+ output += "\n";
625
+ return output;
626
+ }
627
+ const EVENT_SOURCE_META_SYMBOL = Symbol("ORPC_EVENT_SOURCE_META");
628
+ function withEventMeta(container, meta) {
629
+ if (meta.id === void 0 && meta.retry === void 0 && !meta.comments?.length) return container;
630
+ if (meta.id !== void 0) assertEventId(meta.id);
631
+ if (meta.retry !== void 0) assertEventRetry(meta.retry);
632
+ if (meta.comments !== void 0) for (const comment of meta.comments) assertEventComment(comment);
633
+ return new Proxy(container, { get(target, prop, receiver) {
634
+ if (prop === EVENT_SOURCE_META_SYMBOL) return meta;
635
+ return Reflect.get(target, prop, receiver);
636
+ } });
637
+ }
638
+ function getEventMeta(container) {
639
+ return isTypescriptObject(container) ? Reflect.get(container, EVENT_SOURCE_META_SYMBOL) : void 0;
640
+ }
641
+ function generateContentDisposition(filename, disposition = "inline") {
642
+ return `${disposition}; filename="${filename.replace(/[^\x20-\x7E]/g, "_").replace(/"/g, "\\\"")}"; filename*=utf-8''${encodeURIComponent(filename).replace(/['()*]/g, (c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`).replace(/%(7C|60|5E)/g, (str, hex) => String.fromCharCode(Number.parseInt(hex, 16)))}`;
643
+ }
644
+ function getFilenameFromContentDisposition(contentDisposition) {
645
+ const encodedFilenameStarMatch = contentDisposition.match(/filename\*=(UTF-8'')?([^;]*)/i);
646
+ if (encodedFilenameStarMatch && typeof encodedFilenameStarMatch[2] === "string") return tryDecodeURIComponent(encodedFilenameStarMatch[2]);
647
+ const encodedFilenameMatch = contentDisposition.match(/filename="((?:\\"|[^"])*)"/i);
648
+ if (encodedFilenameMatch && typeof encodedFilenameMatch[1] === "string") return encodedFilenameMatch[1].replace(/\\"/g, "\"");
649
+ }
650
+ function mergeStandardHeaders(a, b) {
651
+ const merged = { ...a };
652
+ for (const key in b) if (Array.isArray(b[key])) merged[key] = [...toArray(merged[key]), ...b[key]];
653
+ else if (b[key] !== void 0) {
654
+ if (Array.isArray(merged[key])) merged[key] = [...merged[key], b[key]];
655
+ else if (merged[key] !== void 0) merged[key] = [merged[key], b[key]];
656
+ else merged[key] = b[key];
657
+ }
658
+ return merged;
659
+ }
660
+ // ../../node_modules/.bun/@orpc+client@1.15.2+e40b0dfdd726a224/node_modules/@orpc/client/dist/shared/client.BLtwTQUg.mjs
661
+ function mapEventIterator(iterator, maps) {
662
+ const mapError = async (error) => {
663
+ let mappedError = await maps.error(error);
664
+ if (mappedError !== error) {
665
+ const meta = getEventMeta(error);
666
+ if (meta && isTypescriptObject(mappedError)) mappedError = withEventMeta(mappedError, meta);
667
+ }
668
+ return mappedError;
669
+ };
670
+ return new AsyncIteratorClass(async () => {
671
+ const { done, value } = await (async () => {
672
+ try {
673
+ return await iterator.next();
674
+ } catch (error) {
675
+ throw await mapError(error);
676
+ }
677
+ })();
678
+ let mappedValue = await maps.value(value, done);
679
+ if (mappedValue !== value) {
680
+ const meta = getEventMeta(value);
681
+ if (meta && isTypescriptObject(mappedValue)) mappedValue = withEventMeta(mappedValue, meta);
682
+ }
683
+ return {
684
+ done,
685
+ value: mappedValue
686
+ };
687
+ }, async () => {
688
+ try {
689
+ await iterator.return?.();
690
+ } catch (error) {
691
+ throw await mapError(error);
692
+ }
693
+ });
694
+ }
695
+ // ../../node_modules/.bun/@orpc+client@1.15.2+e40b0dfdd726a224/node_modules/@orpc/client/dist/index.mjs
696
+ function resolveFriendlyClientOptions(options) {
697
+ return {
698
+ ...options,
699
+ context: options.context ?? {}
700
+ };
701
+ }
702
+ function createORPCClient(link, options = {}) {
703
+ const path = options.path ?? [];
704
+ const procedureClient = async (...[input, options2 = {}]) => {
705
+ return await link.call(path, input, resolveFriendlyClientOptions(options2));
706
+ };
707
+ return preventNativeAwait(new Proxy(procedureClient, { get(target, key) {
708
+ if (typeof key !== "string" || RECURSIVE_CLIENT_UNWRAP_KEYS.has(key)) return Reflect.get(target, key);
709
+ return createORPCClient(link, {
710
+ ...options,
711
+ path: [...path, key]
712
+ });
713
+ } }));
714
+ }
715
+ // ../../node_modules/.bun/@orpc+standard-server-fetch@1.15.2+e40b0dfdd726a224/node_modules/@orpc/standard-server-fetch/dist/index.mjs
716
+ function toEventIterator(stream, options = {}) {
717
+ const reader = (stream?.pipeThrough(new TextDecoderStream()).pipeThrough(new EventDecoderStream()))?.getReader();
718
+ let span;
719
+ let isCancelled = false;
720
+ return new AsyncIteratorClass(async () => {
721
+ span ??= startSpan("consume_event_iterator_stream");
722
+ try {
723
+ while (true) {
724
+ if (reader === void 0) return {
725
+ done: true,
726
+ value: void 0
727
+ };
728
+ const { done, value } = await runInSpanContext(span, () => reader.read());
729
+ if (done) {
730
+ if (isCancelled) throw new AbortError("Stream was cancelled");
731
+ return {
732
+ done: true,
733
+ value: void 0
734
+ };
735
+ }
736
+ switch (value.event) {
737
+ case "message": {
738
+ let message = parseEmptyableJSON(value.data);
739
+ if (isTypescriptObject(message)) message = withEventMeta(message, value);
740
+ span?.addEvent("message");
741
+ return {
742
+ done: false,
743
+ value: message
744
+ };
745
+ }
746
+ case "error": {
747
+ let error = new ErrorEvent({ data: parseEmptyableJSON(value.data) });
748
+ error = withEventMeta(error, value);
749
+ span?.addEvent("error");
750
+ throw error;
751
+ }
752
+ case "done": {
753
+ let done2 = parseEmptyableJSON(value.data);
754
+ if (isTypescriptObject(done2)) done2 = withEventMeta(done2, value);
755
+ span?.addEvent("done");
756
+ return {
757
+ done: true,
758
+ value: done2
759
+ };
760
+ }
761
+ default: span?.addEvent("maybe_keepalive");
762
+ }
763
+ }
764
+ } catch (e) {
765
+ if (!(e instanceof ErrorEvent)) setSpanError(span, e, options);
766
+ throw e;
767
+ }
768
+ }, async (reason) => {
769
+ try {
770
+ if (reason !== "next") {
771
+ isCancelled = true;
772
+ span?.addEvent("cancelled");
773
+ }
774
+ await runInSpanContext(span, () => reader?.cancel());
775
+ } catch (e) {
776
+ setSpanError(span, e, options);
777
+ throw e;
778
+ } finally {
779
+ span?.end();
780
+ }
781
+ });
782
+ }
783
+ function toEventStream(iterator, options = {}) {
784
+ const keepAliveEnabled = options.eventIteratorKeepAliveEnabled ?? true;
785
+ const keepAliveInterval = options.eventIteratorKeepAliveInterval ?? 5e3;
786
+ const keepAliveComment = options.eventIteratorKeepAliveComment ?? "";
787
+ const initialCommentEnabled = options.eventIteratorInitialCommentEnabled ?? true;
788
+ const initialComment = options.eventIteratorInitialComment ?? "";
789
+ let cancelled = false;
790
+ let timeout;
791
+ let span;
792
+ return new ReadableStream({
793
+ start(controller) {
794
+ span = startSpan("stream_event_iterator");
795
+ if (initialCommentEnabled) controller.enqueue(encodeEventMessage({ comments: [initialComment] }));
796
+ },
797
+ async pull(controller) {
798
+ try {
799
+ if (keepAliveEnabled) timeout = setInterval(() => {
800
+ controller.enqueue(encodeEventMessage({ comments: [keepAliveComment] }));
801
+ span?.addEvent("keepalive");
802
+ }, keepAliveInterval);
803
+ const value = await runInSpanContext(span, () => iterator.next());
804
+ clearInterval(timeout);
805
+ if (cancelled) return;
806
+ const meta = getEventMeta(value.value);
807
+ if (!value.done || value.value !== void 0 || meta !== void 0) {
808
+ const event = value.done ? "done" : "message";
809
+ controller.enqueue(encodeEventMessage({
810
+ ...meta,
811
+ event,
812
+ data: stringifyJSON(value.value)
813
+ }));
814
+ span?.addEvent(event);
815
+ }
816
+ if (value.done) {
817
+ controller.close();
818
+ span?.end();
819
+ }
820
+ } catch (err) {
821
+ clearInterval(timeout);
822
+ if (cancelled) return;
823
+ if (err instanceof ErrorEvent) {
824
+ controller.enqueue(encodeEventMessage({
825
+ ...getEventMeta(err),
826
+ event: "error",
827
+ data: stringifyJSON(err.data)
828
+ }));
829
+ span?.addEvent("error");
830
+ controller.close();
831
+ } else {
832
+ setSpanError(span, err);
833
+ controller.error(err);
834
+ }
835
+ span?.end();
836
+ }
837
+ },
838
+ async cancel() {
839
+ try {
840
+ cancelled = true;
841
+ clearInterval(timeout);
842
+ span?.addEvent("cancelled");
843
+ await runInSpanContext(span, () => iterator.return?.());
844
+ } catch (e) {
845
+ setSpanError(span, e);
846
+ throw e;
847
+ } finally {
848
+ span?.end();
849
+ }
850
+ }
851
+ }).pipeThrough(new TextEncoderStream());
852
+ }
853
+ function toStandardBody(re, options = {}) {
854
+ return runWithSpan({
855
+ name: "parse_standard_body",
856
+ signal: options.signal
857
+ }, async () => {
858
+ const contentDisposition = re.headers.get("content-disposition");
859
+ if (typeof contentDisposition === "string") {
860
+ const fileName = getFilenameFromContentDisposition(contentDisposition) ?? "blob";
861
+ const blob2 = await re.blob();
862
+ return new File([blob2], fileName, { type: blob2.type });
863
+ }
864
+ const contentType = re.headers.get("content-type");
865
+ if (!contentType || contentType.startsWith("application/json")) return parseEmptyableJSON(await re.text());
866
+ if (contentType.startsWith("multipart/form-data")) return await re.formData();
867
+ if (contentType.startsWith("application/x-www-form-urlencoded")) {
868
+ const text = await re.text();
869
+ return new URLSearchParams(text);
870
+ }
871
+ if (contentType.startsWith("text/event-stream")) return toEventIterator(re.body, options);
872
+ if (contentType.startsWith("text/plain")) return await re.text();
873
+ const blob = await re.blob();
874
+ return new File([blob], "blob", { type: blob.type });
875
+ });
876
+ }
877
+ function toFetchBody(body, headers, options = {}) {
878
+ if (body instanceof ReadableStream) return body;
879
+ const currentContentDisposition = headers.get("content-disposition");
880
+ headers.delete("content-type");
881
+ headers.delete("content-disposition");
882
+ if (body === void 0) return;
883
+ if (body instanceof Blob) {
884
+ headers.set("content-type", body.type);
885
+ headers.set("content-length", body.size.toString());
886
+ headers.set("content-disposition", currentContentDisposition ?? generateContentDisposition(body instanceof File ? body.name : "blob"));
887
+ return body;
888
+ }
889
+ if (body instanceof FormData) return body;
890
+ if (body instanceof URLSearchParams) return body;
891
+ if (isAsyncIteratorObject(body)) {
892
+ headers.set("content-type", "text/event-stream");
893
+ return toEventStream(body, options);
894
+ }
895
+ headers.set("content-type", "application/json");
896
+ return stringifyJSON(body);
897
+ }
898
+ function toStandardHeaders$1(headers, standardHeaders = {}) {
899
+ headers.forEach((value, key) => {
900
+ if (Array.isArray(standardHeaders[key])) standardHeaders[key].push(value);
901
+ else if (standardHeaders[key] !== void 0) standardHeaders[key] = [standardHeaders[key], value];
902
+ else standardHeaders[key] = value;
903
+ });
904
+ return standardHeaders;
905
+ }
906
+ function toFetchHeaders(headers, fetchHeaders = new Headers()) {
907
+ for (const [key, value] of Object.entries(headers)) if (Array.isArray(value)) for (const v of value) fetchHeaders.append(key, v);
908
+ else if (value !== void 0) fetchHeaders.append(key, value);
909
+ return fetchHeaders;
910
+ }
911
+ function toFetchRequest(request, options = {}) {
912
+ const headers = toFetchHeaders(request.headers);
913
+ const body = toFetchBody(request.body, headers, options);
914
+ return new Request(request.url, {
915
+ signal: request.signal,
916
+ method: request.method,
917
+ headers,
918
+ body
919
+ });
920
+ }
921
+ function toStandardLazyResponse(response, options = {}) {
922
+ return {
923
+ body: once(() => toStandardBody(response, options)),
924
+ status: response.status,
925
+ get headers() {
926
+ const headers = toStandardHeaders$1(response.headers);
927
+ Object.defineProperty(this, "headers", {
928
+ value: headers,
929
+ writable: true
930
+ });
931
+ return headers;
932
+ },
933
+ set headers(value) {
934
+ Object.defineProperty(this, "headers", {
935
+ value,
936
+ writable: true
937
+ });
938
+ }
939
+ };
940
+ }
941
+ // ../../node_modules/.bun/@orpc+client@1.15.2+e40b0dfdd726a224/node_modules/@orpc/client/dist/shared/client.BKdRDdCe.mjs
942
+ var CompositeStandardLinkPlugin = class {
943
+ plugins;
944
+ constructor(plugins = []) {
945
+ this.plugins = [...plugins].sort((a, b) => (a.order ?? 0) - (b.order ?? 0));
946
+ }
947
+ init(options) {
948
+ for (const plugin of this.plugins) plugin.init?.(options);
949
+ }
950
+ };
951
+ var StandardLink = class {
952
+ constructor(codec, sender, options = {}) {
953
+ this.codec = codec;
954
+ this.sender = sender;
955
+ new CompositeStandardLinkPlugin(options.plugins).init(options);
956
+ this.interceptors = toArray(options.interceptors);
957
+ this.clientInterceptors = toArray(options.clientInterceptors);
958
+ }
959
+ interceptors;
960
+ clientInterceptors;
961
+ call(path, input, options) {
962
+ return runWithSpan({
963
+ name: `${ORPC_NAME}.${path.join("/")}`,
964
+ signal: options.signal
965
+ }, (span) => {
966
+ span?.setAttribute("rpc.system", ORPC_NAME);
967
+ span?.setAttribute("rpc.method", path.join("."));
968
+ if (isAsyncIteratorObject(input)) input = asyncIteratorWithSpan({
969
+ name: "consume_event_iterator_input",
970
+ signal: options.signal
971
+ }, input);
972
+ return intercept(this.interceptors, {
973
+ ...options,
974
+ path,
975
+ input
976
+ }, async ({ path: path2, input: input2, ...options2 }) => {
977
+ const otelConfig = getGlobalOtelConfig();
978
+ let otelContext;
979
+ const currentSpan = otelConfig?.trace.getActiveSpan() ?? span;
980
+ if (currentSpan && otelConfig) otelContext = otelConfig?.trace.setSpan(otelConfig.context.active(), currentSpan);
981
+ const request = await runWithSpan({
982
+ name: "encode_request",
983
+ context: otelContext
984
+ }, () => this.codec.encode(path2, input2, options2));
985
+ const response = await intercept(this.clientInterceptors, {
986
+ ...options2,
987
+ input: input2,
988
+ path: path2,
989
+ request
990
+ }, ({ input: input3, path: path3, request: request2, ...options3 }) => {
991
+ return runWithSpan({
992
+ name: "send_request",
993
+ signal: options3.signal,
994
+ context: otelContext
995
+ }, () => this.sender.call(request2, options3, path3, input3));
996
+ });
997
+ const output = await runWithSpan({
998
+ name: "decode_response",
999
+ context: otelContext
1000
+ }, () => this.codec.decode(response, options2, path2, input2));
1001
+ if (isAsyncIteratorObject(output)) return asyncIteratorWithSpan({
1002
+ name: "consume_event_iterator_output",
1003
+ signal: options2.signal
1004
+ }, output);
1005
+ return output;
1006
+ });
1007
+ });
1008
+ }
1009
+ };
1010
+ const STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES = {
1011
+ BIGINT: 0,
1012
+ DATE: 1,
1013
+ NAN: 2,
1014
+ UNDEFINED: 3,
1015
+ URL: 4,
1016
+ REGEXP: 5,
1017
+ SET: 6,
1018
+ MAP: 7
1019
+ };
1020
+ const BUILT_IN_TYPES = new Set(Object.values(STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES));
1021
+ const SERIALIZED_REGEXP_FORMAT = /^\/(.*)\/([a-z]*)$/;
1022
+ function invalidSerializedData(detail) {
1023
+ return /* @__PURE__ */ new TypeError(`Invalid RPC serialized data: ${detail}`);
1024
+ }
1025
+ function invalidSerializedType(type, name, expected) {
1026
+ return invalidSerializedData(`type ${type} (${name}) expects ${expected}.`);
1027
+ }
1028
+ var StandardRPCJsonSerializer = class {
1029
+ customSerializers;
1030
+ constructor(options = {}) {
1031
+ this.customSerializers = options.customJsonSerializers ?? [];
1032
+ if (this.customSerializers.length !== new Set(this.customSerializers.map((custom) => custom.type)).size) throw new Error("Custom serializer type must be unique.");
1033
+ }
1034
+ serialize(data, segments = [], meta = [], maps = [], blobs = []) {
1035
+ for (const custom of this.customSerializers) if (custom.condition(data)) {
1036
+ const result = this.serialize(custom.serialize(data), segments, meta, maps, blobs);
1037
+ meta.push([custom.type, ...segments]);
1038
+ return result;
1039
+ }
1040
+ if (data instanceof Blob) {
1041
+ maps.push(segments);
1042
+ blobs.push(data);
1043
+ return [
1044
+ data,
1045
+ meta,
1046
+ maps,
1047
+ blobs
1048
+ ];
1049
+ }
1050
+ if (typeof data === "bigint") {
1051
+ meta.push([STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES.BIGINT, ...segments]);
1052
+ return [
1053
+ data.toString(),
1054
+ meta,
1055
+ maps,
1056
+ blobs
1057
+ ];
1058
+ }
1059
+ if (data instanceof Date) {
1060
+ meta.push([STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES.DATE, ...segments]);
1061
+ if (Number.isNaN(data.getTime())) return [
1062
+ null,
1063
+ meta,
1064
+ maps,
1065
+ blobs
1066
+ ];
1067
+ return [
1068
+ data.toISOString(),
1069
+ meta,
1070
+ maps,
1071
+ blobs
1072
+ ];
1073
+ }
1074
+ if (Number.isNaN(data)) {
1075
+ meta.push([STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES.NAN, ...segments]);
1076
+ return [
1077
+ null,
1078
+ meta,
1079
+ maps,
1080
+ blobs
1081
+ ];
1082
+ }
1083
+ if (data instanceof URL) {
1084
+ meta.push([STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES.URL, ...segments]);
1085
+ return [
1086
+ data.toString(),
1087
+ meta,
1088
+ maps,
1089
+ blobs
1090
+ ];
1091
+ }
1092
+ if (data instanceof RegExp) {
1093
+ meta.push([STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES.REGEXP, ...segments]);
1094
+ return [
1095
+ data.toString(),
1096
+ meta,
1097
+ maps,
1098
+ blobs
1099
+ ];
1100
+ }
1101
+ if (data instanceof Set) {
1102
+ const result = this.serialize(Array.from(data), segments, meta, maps, blobs);
1103
+ meta.push([STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES.SET, ...segments]);
1104
+ return result;
1105
+ }
1106
+ if (data instanceof Map) {
1107
+ const result = this.serialize(Array.from(data.entries()), segments, meta, maps, blobs);
1108
+ meta.push([STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES.MAP, ...segments]);
1109
+ return result;
1110
+ }
1111
+ if (Array.isArray(data)) return [
1112
+ data.map((v, i) => {
1113
+ if (v === void 0) {
1114
+ meta.push([
1115
+ STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES.UNDEFINED,
1116
+ ...segments,
1117
+ i
1118
+ ]);
1119
+ return null;
1120
+ }
1121
+ return this.serialize(v, [...segments, i], meta, maps, blobs)[0];
1122
+ }),
1123
+ meta,
1124
+ maps,
1125
+ blobs
1126
+ ];
1127
+ if (isObject(data)) {
1128
+ const json = {};
1129
+ for (const k in data) {
1130
+ if (k === "toJSON" && typeof data[k] === "function") continue;
1131
+ json[k] = this.serialize(data[k], [...segments, k], meta, maps, blobs)[0];
1132
+ }
1133
+ return [
1134
+ json,
1135
+ meta,
1136
+ maps,
1137
+ blobs
1138
+ ];
1139
+ }
1140
+ return [
1141
+ data,
1142
+ meta,
1143
+ maps,
1144
+ blobs
1145
+ ];
1146
+ }
1147
+ deserialize(json, meta, maps, getBlob) {
1148
+ const ref = { data: json };
1149
+ if (maps && getBlob) maps.forEach((segments, i) => {
1150
+ let currentRef = ref;
1151
+ let preSegment = "data";
1152
+ segments.forEach((segment) => {
1153
+ currentRef = currentRef[preSegment];
1154
+ preSegment = segment;
1155
+ if (!Object.hasOwn(currentRef, preSegment)) throw invalidSerializedData(`segment "${preSegment}" does not exist.`);
1156
+ });
1157
+ currentRef[preSegment] = getBlob(i);
1158
+ });
1159
+ for (const item of meta) {
1160
+ const type = item[0];
1161
+ const custom = this.customSerializers.find((custom2) => custom2.type === type);
1162
+ if (custom === void 0 && !BUILT_IN_TYPES.has(type)) continue;
1163
+ let currentRef = ref;
1164
+ let preSegment = "data";
1165
+ for (let i = 1; i < item.length; i++) {
1166
+ currentRef = currentRef[preSegment];
1167
+ preSegment = item[i];
1168
+ if (!Object.hasOwn(currentRef, preSegment)) throw invalidSerializedData(`segment "${preSegment}" does not exist.`);
1169
+ }
1170
+ if (custom !== void 0) {
1171
+ currentRef[preSegment] = custom.deserialize(currentRef[preSegment]);
1172
+ continue;
1173
+ }
1174
+ const serialized = currentRef[preSegment];
1175
+ switch (type) {
1176
+ case STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES.BIGINT:
1177
+ if (typeof serialized !== "string") throw invalidSerializedType(type, "bigint", "a string");
1178
+ currentRef[preSegment] = BigInt(serialized);
1179
+ break;
1180
+ case STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES.DATE:
1181
+ if (typeof serialized !== "string" && serialized !== null) throw invalidSerializedType(type, "date", "a string or null");
1182
+ currentRef[preSegment] = new Date(serialized ?? NaN);
1183
+ break;
1184
+ case STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES.NAN:
1185
+ if (serialized !== null) throw invalidSerializedType(type, "nan", "null");
1186
+ currentRef[preSegment] = NaN;
1187
+ break;
1188
+ case STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES.UNDEFINED:
1189
+ if (serialized !== null) throw invalidSerializedType(type, "undefined", "null");
1190
+ currentRef[preSegment] = void 0;
1191
+ break;
1192
+ case STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES.URL:
1193
+ if (typeof serialized !== "string") throw invalidSerializedType(type, "url", "a string");
1194
+ currentRef[preSegment] = new URL(serialized);
1195
+ break;
1196
+ case STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES.REGEXP: {
1197
+ if (typeof serialized !== "string") throw invalidSerializedType(type, "regexp", "a string");
1198
+ const match = serialized.match(SERIALIZED_REGEXP_FORMAT);
1199
+ if (match === null || !isValidRegExpFlags(match[2])) throw invalidSerializedData(`type ${type} (regexp) expects a "/pattern/flags" string.`);
1200
+ currentRef[preSegment] = createLazyRegExp(match[1], match[2]);
1201
+ break;
1202
+ }
1203
+ case STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES.SET:
1204
+ if (!Array.isArray(serialized)) throw invalidSerializedType(type, "set", "an array");
1205
+ currentRef[preSegment] = new Set(serialized);
1206
+ break;
1207
+ case STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES.MAP:
1208
+ if (!Array.isArray(serialized)) throw invalidSerializedType(type, "map", "an array");
1209
+ currentRef[preSegment] = new Map(serialized);
1210
+ }
1211
+ }
1212
+ return ref.data;
1213
+ }
1214
+ };
1215
+ function toHttpPath(path) {
1216
+ return `/${path.map(encodeURIComponent).join("/")}`;
1217
+ }
1218
+ function toStandardHeaders(headers) {
1219
+ if (typeof headers.forEach === "function") return toStandardHeaders$1(headers);
1220
+ return headers;
1221
+ }
1222
+ function getMalformedResponseErrorCode(status) {
1223
+ return Object.entries(COMMON_ORPC_ERROR_DEFS).find(([, def]) => def.status === status)?.[0] ?? "MALFORMED_ORPC_ERROR_RESPONSE";
1224
+ }
1225
+ var StandardRPCLinkCodec = class {
1226
+ constructor(serializer, options) {
1227
+ this.serializer = serializer;
1228
+ this.baseUrl = options.url;
1229
+ this.maxUrlLength = options.maxUrlLength ?? 2083;
1230
+ this.fallbackMethod = options.fallbackMethod ?? "POST";
1231
+ this.expectedMethod = options.method ?? this.fallbackMethod;
1232
+ this.headers = options.headers ?? {};
1233
+ }
1234
+ baseUrl;
1235
+ maxUrlLength;
1236
+ fallbackMethod;
1237
+ expectedMethod;
1238
+ headers;
1239
+ async encode(path, input, options) {
1240
+ let headers = toStandardHeaders(await value(this.headers, options, path, input));
1241
+ if (options.lastEventId !== void 0) headers = mergeStandardHeaders(headers, { "last-event-id": options.lastEventId });
1242
+ const expectedMethod = await value(this.expectedMethod, options, path, input);
1243
+ const baseUrl = await value(this.baseUrl, options, path, input);
1244
+ const url = new URL(baseUrl);
1245
+ url.pathname = `${url.pathname.replace(/\/$/, "")}${toHttpPath(path)}`;
1246
+ const serialized = this.serializer.serialize(input);
1247
+ if (expectedMethod === "GET" && !(serialized instanceof FormData) && !isAsyncIteratorObject(serialized)) {
1248
+ const maxUrlLength = await value(this.maxUrlLength, options, path, input);
1249
+ const getUrl = new URL(url);
1250
+ getUrl.searchParams.append("data", stringifyJSON(serialized));
1251
+ if (getUrl.toString().length <= maxUrlLength) return {
1252
+ body: void 0,
1253
+ method: expectedMethod,
1254
+ headers,
1255
+ url: getUrl,
1256
+ signal: options.signal
1257
+ };
1258
+ }
1259
+ return {
1260
+ url,
1261
+ method: expectedMethod === "GET" ? this.fallbackMethod : expectedMethod,
1262
+ headers,
1263
+ body: serialized,
1264
+ signal: options.signal
1265
+ };
1266
+ }
1267
+ async decode(response) {
1268
+ const isOk = !isORPCErrorStatus(response.status);
1269
+ const deserialized = await (async () => {
1270
+ let isBodyOk = false;
1271
+ try {
1272
+ const body = await response.body();
1273
+ isBodyOk = true;
1274
+ return this.serializer.deserialize(body);
1275
+ } catch (error) {
1276
+ if (!isBodyOk) throw new Error("Cannot parse response body, please check the response body and content-type.", { cause: error });
1277
+ throw new Error("Invalid RPC response format.", { cause: error });
1278
+ }
1279
+ })();
1280
+ if (!isOk) {
1281
+ if (isORPCErrorJson(deserialized)) throw createORPCErrorFromJson(deserialized);
1282
+ throw new ORPCError(getMalformedResponseErrorCode(response.status), {
1283
+ status: response.status,
1284
+ data: {
1285
+ ...response,
1286
+ body: deserialized
1287
+ }
1288
+ });
1289
+ }
1290
+ return deserialized;
1291
+ }
1292
+ };
1293
+ var StandardRPCSerializer = class {
1294
+ constructor(jsonSerializer) {
1295
+ this.jsonSerializer = jsonSerializer;
1296
+ }
1297
+ serialize(data) {
1298
+ if (isAsyncIteratorObject(data)) return mapEventIterator(data, {
1299
+ value: async (value) => this.#serialize(value, false),
1300
+ error: async (e) => {
1301
+ return new ErrorEvent({
1302
+ data: this.#serialize(toORPCError(e).toJSON(), false),
1303
+ cause: e
1304
+ });
1305
+ }
1306
+ });
1307
+ return this.#serialize(data, true);
1308
+ }
1309
+ #serialize(data, enableFormData) {
1310
+ const [json, meta_, maps, blobs] = this.jsonSerializer.serialize(data);
1311
+ const meta = meta_.length === 0 ? void 0 : meta_;
1312
+ if (!enableFormData || blobs.length === 0) return {
1313
+ json,
1314
+ meta
1315
+ };
1316
+ const form = new FormData();
1317
+ form.set("data", stringifyJSON({
1318
+ json,
1319
+ meta,
1320
+ maps
1321
+ }));
1322
+ blobs.forEach((blob, i) => {
1323
+ form.set(i.toString(), blob);
1324
+ });
1325
+ return form;
1326
+ }
1327
+ deserialize(data) {
1328
+ if (isAsyncIteratorObject(data)) return mapEventIterator(data, {
1329
+ value: async (value) => this.#deserialize(value),
1330
+ error: async (e) => {
1331
+ if (!(e instanceof ErrorEvent)) return e;
1332
+ const deserialized = this.#deserialize(e.data);
1333
+ if (isORPCErrorJson(deserialized)) return createORPCErrorFromJson(deserialized, { cause: e });
1334
+ return new ErrorEvent({
1335
+ data: deserialized,
1336
+ cause: e
1337
+ });
1338
+ }
1339
+ });
1340
+ return this.#deserialize(data);
1341
+ }
1342
+ #deserialize(data) {
1343
+ if (data === void 0) return;
1344
+ if (!(data instanceof FormData)) return this.jsonSerializer.deserialize(data.json, data.meta ?? []);
1345
+ const serialized = JSON.parse(data.get("data"));
1346
+ return this.jsonSerializer.deserialize(serialized.json, serialized.meta ?? [], serialized.maps, (i) => data.get(i.toString()));
1347
+ }
1348
+ };
1349
+ var StandardRPCLink = class extends StandardLink {
1350
+ constructor(linkClient, options) {
1351
+ const linkCodec = new StandardRPCLinkCodec(new StandardRPCSerializer(new StandardRPCJsonSerializer(options)), options);
1352
+ super(linkCodec, linkClient, options);
1353
+ }
1354
+ };
1355
+ // ../../node_modules/.bun/@orpc+client@1.15.2+e40b0dfdd726a224/node_modules/@orpc/client/dist/adapters/fetch/index.mjs
1356
+ var CompositeLinkFetchPlugin = class extends CompositeStandardLinkPlugin {
1357
+ initRuntimeAdapter(options) {
1358
+ for (const plugin of this.plugins) plugin.initRuntimeAdapter?.(options);
1359
+ }
1360
+ };
1361
+ var LinkFetchClient = class {
1362
+ fetch;
1363
+ toFetchRequestOptions;
1364
+ adapterInterceptors;
1365
+ constructor(options) {
1366
+ new CompositeLinkFetchPlugin(options.plugins).initRuntimeAdapter(options);
1367
+ this.fetch = options.fetch ?? globalThis.fetch.bind(globalThis);
1368
+ this.toFetchRequestOptions = options;
1369
+ this.adapterInterceptors = toArray(options.adapterInterceptors);
1370
+ }
1371
+ async call(standardRequest, options, path, input) {
1372
+ const request = toFetchRequest(standardRequest, this.toFetchRequestOptions);
1373
+ return toStandardLazyResponse(await intercept(this.adapterInterceptors, {
1374
+ ...options,
1375
+ request,
1376
+ path,
1377
+ input,
1378
+ init: { redirect: "manual" }
1379
+ }, ({ request: request2, path: path2, input: input2, init, ...options2 }) => this.fetch(request2, init, options2, path2, input2)), { signal: request.signal });
1380
+ }
1381
+ };
1382
+ var RPCLink = class extends StandardRPCLink {
1383
+ constructor(options) {
1384
+ const linkClient = new LinkFetchClient(options);
1385
+ super(linkClient, options);
1386
+ }
1387
+ };
1388
+ // ../instance-client/lib/errors.ts
1389
+ function readNumber(data, key) {
1390
+ const value = data?.[key];
1391
+ return typeof value === "number" ? value : void 0;
1392
+ }
1393
+ function readString(data, key) {
1394
+ const value = data?.[key];
1395
+ return typeof value === "string" ? value : void 0;
1396
+ }
1397
+ function readStringArray(data, key) {
1398
+ const value = data?.[key];
1399
+ if (!Array.isArray(value)) return void 0;
1400
+ const strings = value.filter((v) => typeof v === "string");
1401
+ return strings.length === value.length ? strings : void 0;
1402
+ }
1403
+ function readBoolean(data, key) {
1404
+ const value = data?.[key];
1405
+ return typeof value === "boolean" ? value : void 0;
1406
+ }
1407
+ function readNumberFromMatch(message, pattern) {
1408
+ const match = message.match(pattern);
1409
+ if (!match?.[1]) return void 0;
1410
+ const number = Number.parseFloat(match[1]);
1411
+ return Number.isFinite(number) ? number : void 0;
1412
+ }
1413
+ function readStringFromMatch(message, pattern) {
1414
+ const value = message.match(pattern)?.[1]?.trim();
1415
+ return value ? value : void 0;
1416
+ }
1417
+ function readListFromMatch(message, pattern) {
1418
+ const value = readStringFromMatch(message, pattern);
1419
+ if (!value) return void 0;
1420
+ const items = value.split(",").map((item) => item.trim()).filter(Boolean);
1421
+ return items.length > 0 ? items : void 0;
1422
+ }
1423
+ function hasHigherModelHint(message, data) {
1424
+ const lower = message.toLowerCase();
1425
+ return readBoolean(data, "retryableWithHigherModel") === true || lower.includes("try with a higher model") || lower.includes("use a higher model") || lower.includes("use higher model") || lower.startsWith("file too large") || lower.startsWith("document has") && lower.includes("page") && lower.includes("limit");
1426
+ }
1427
+ function inferCategory(code, message, data) {
1428
+ const lower = message.toLowerCase();
1429
+ if (code === "UNAUTHORIZED") return "authentication";
1430
+ if (code === "PAYMENT_REQUIRED") return "credits";
1431
+ if (code === "TOO_MANY_REQUESTS") return "rate_limit";
1432
+ if (code === "NOT_FOUND") return "not_found";
1433
+ if (code === "CONFLICT") return "conflict";
1434
+ if (code === "NOT_IMPLEMENTED") return "unsupported";
1435
+ if (code === "INTERNAL_SERVER_ERROR") return "server";
1436
+ if (code === "UNPROCESSABLE_CONTENT") return data["userError"] === true ? "document_input" : "document_processing";
1437
+ if (lower.includes("json schema") || lower.includes("invalid input") || lower.includes("invalid type") || lower.includes("expected")) return "validation";
1438
+ return "document_input";
1439
+ }
1440
+ function inferOrigin(code, category, data) {
1441
+ if (data["userError"] === true) return "user";
1442
+ if (code === "INTERNAL_SERVER_ERROR") return "system";
1443
+ if (category === "document_processing" && data["userError"] !== true) return "system";
1444
+ return "user";
1445
+ }
1446
+ function inferTitle(code, className, message, billingCode) {
1447
+ const lower = message.toLowerCase();
1448
+ if (className === "FileTooLargeError") return "File too large";
1449
+ if (className === "PageLimitExceededError") return "Page limit exceeded";
1450
+ if (className === "PasswordProtectedError") return "Password-protected document";
1451
+ if (className === "UnsupportedFormatError") return "Unsupported document format";
1452
+ if (className === "URLFetchError") return "Could not fetch document URL";
1453
+ if (className === "InvalidDocumentURLError") return "Invalid document URL";
1454
+ if (className === "InvalidBase64Error") return "Invalid base64 document";
1455
+ if (className === "TierNotSupportedError") return "Model does not support this file type";
1456
+ if (className === "InvalidSchemaError") return "Invalid JSON Schema";
1457
+ if (className === "NoInputProvidedError") return "No document input provided";
1458
+ if (className === "EmptyDocumentError") return "Empty document";
1459
+ if (className === "NoTextDetectedError") return "No readable text detected";
1460
+ if (className === "ExtractionFailedError") return "Extraction failed";
1461
+ if (className === "AcademicPaperNotFoundError") return "Paper not found";
1462
+ if (className === "NoPublicPDFError") return "No public PDF found";
1463
+ if (lower.includes("no public pdf url")) return "No public PDF found";
1464
+ if (lower.includes("paper not found")) return "Paper not found";
1465
+ switch (code) {
1466
+ case "BAD_REQUEST": return "Invalid request";
1467
+ case "UNAUTHORIZED": return "Authentication failed";
1468
+ case "PAYMENT_REQUIRED": return billingCode ? "Payment required" : "Out of credits";
1469
+ case "NOT_FOUND": return "Resource not found";
1470
+ case "TOO_MANY_REQUESTS": return "Rate limit exceeded";
1471
+ case "CONFLICT": return "Request conflict";
1472
+ case "NOT_IMPLEMENTED": return "Not implemented";
1473
+ case "UNPROCESSABLE_CONTENT": return "Document could not be processed";
1474
+ case "INTERNAL_SERVER_ERROR": return "PDF Vector server error";
1475
+ }
1476
+ }
1477
+ function inferSuggestion(code, message, data) {
1478
+ const lower = message.toLowerCase();
1479
+ const requestId = readNumber(data, "requestId");
1480
+ if (code === "UNAUTHORIZED") return "Check that the API key is present, valid, and belongs to the workspace you intend to use.";
1481
+ if (code === "PAYMENT_REQUIRED" && readString(data, "code")?.startsWith("BILLING_")) {
1482
+ const payUrl = readString(data, "payUrl");
1483
+ if (readString(data, "code") === "BILLING_DISPUTE") return "Resolve the payment dispute with your bank or contact team@pdfvector.com.";
1484
+ return payUrl ? `Pay the outstanding balance at ${payUrl}.` : "Open billing at https://app.pdfvector.com/workspace/billing and settle the outstanding balance.";
1485
+ }
1486
+ if (code === "PAYMENT_REQUIRED") {
1487
+ const resetsAt = readString(data, "resetsAt");
1488
+ return resetsAt ? `Upgrade your plan at https://app.pdfvector.com/plan, or wait until credits reset on ${resetsAt.slice(0, 10)}.` : "Upgrade your plan at https://app.pdfvector.com/plan to get more credits.";
1489
+ }
1490
+ if (code === "TOO_MANY_REQUESTS") {
1491
+ const resetAt = readString(data, "resetAt");
1492
+ return resetAt ? `Wait until ${resetAt}, then retry the request.` : "Wait for the rate limit window to reset, then retry the request.";
1493
+ }
1494
+ if (code === "INTERNAL_SERVER_ERROR") return requestId ? `Retry the request. If it keeps failing, contact support with requestId ${requestId}.` : "Retry the request. If it keeps failing, contact support with the request details.";
1495
+ if (hasHigherModelHint(message, data)) {
1496
+ const requestedModel = readString(data, "requestedModel");
1497
+ return requestedModel ? `Retry with a higher model than '${requestedModel}', or reduce the file size/pages before sending it again.` : "Retry with a higher model, or reduce the file size/pages before sending it again.";
1498
+ }
1499
+ const reasonCode = readString(data, "code");
1500
+ if (reasonCode === "DOCUMENT_PROCESSING_FAILED" || reasonCode === "DOCUMENT_AI_INVALID_ARGUMENT" || reasonCode === "DOCUMENT_INTELLIGENCE_INVALID_REQUEST") return requestId ? `Retry the request. If it keeps failing, contact support with requestId ${requestId}.` : "Retry the request. If it keeps failing, contact support with the request details.";
1501
+ if (reasonCode === "EXTRACTION_FAILED") return "Simplify the extraction schema or prompt, then retry.";
1502
+ if (reasonCode === "MODEL_OUTPUT_UNUSABLE") return "Try a simpler question or a clearer document, then retry.";
1503
+ if (lower.includes("password-protected")) return "Remove the document password or upload an unlocked copy.";
1504
+ if (lower.includes("json schema")) return "Fix the JSON Schema shape, then retry. Object schemas need properties, array schemas need items, and enum values must match their declared types.";
1505
+ if (lower.includes("no public pdf url")) return "Provide a direct PDF URL or upload the paper file directly.";
1506
+ if (lower.includes("url") || lower.includes("google drive") || lower.includes("docs returned an html page")) return "Use a direct, publicly fetchable document URL, or upload the file/base64 content instead.";
1507
+ if (lower.includes("base64")) return "Send only the raw base64 document content, without a data URL prefix or invalid characters.";
1508
+ if (lower.includes("unsupported format")) return "Convert the file to a supported format such as PDF, DOCX, XLSX, PPTX, CSV, TXT, HTML, or a supported image format.";
1509
+ if (lower.includes("no input provided") || lower.includes("empty document")) return "Send exactly one document source: url, file, or base64, and make sure it is not empty.";
1510
+ if (lower.includes("no readable text") || lower.includes("no text content") || lower.includes("document appears to be empty")) return "Upload a clearer scan or a source document with selectable/readable text.";
1511
+ if (code === "NOT_FOUND") return "Check the identifier or URL and retry with a value that PDF Vector can resolve.";
1512
+ if (code === "UNPROCESSABLE_CONTENT") return "Review the document quality and requested operation, then retry with clearer content or a simpler extraction prompt/schema.";
1513
+ return "Fix the request and retry.";
1514
+ }
1515
+ var PDFVectorError = class extends Error {
1516
+ code;
1517
+ status;
1518
+ data;
1519
+ requestId;
1520
+ documentId;
1521
+ userError;
1522
+ category;
1523
+ origin;
1524
+ title;
1525
+ suggestion;
1526
+ retryable;
1527
+ retryableWithHigherModel;
1528
+ requestedModel;
1529
+ reasonCode;
1530
+ supportMessage;
1531
+ constructor(options) {
1532
+ super(options.message, options.cause ? { cause: options.cause } : void 0);
1533
+ this.name = new.target.name;
1534
+ this.code = options.code;
1535
+ this.status = options.status;
1536
+ this.data = options.data ?? {};
1537
+ this.requestId = readNumber(this.data, "requestId");
1538
+ this.documentId = readString(this.data, "documentId");
1539
+ this.category = inferCategory(this.code, this.message, this.data);
1540
+ this.origin = inferOrigin(this.code, this.category, this.data);
1541
+ this.userError = this.origin === "user";
1542
+ this.title = inferTitle(this.code, this.name, this.message, readString(this.data, "code")?.startsWith("BILLING_") ?? false);
1543
+ this.suggestion = inferSuggestion(this.code, this.message, this.data);
1544
+ this.retryableWithHigherModel = hasHigherModelHint(this.message, this.data);
1545
+ this.retryable = this.retryableWithHigherModel || this.code === "TOO_MANY_REQUESTS" || this.code === "INTERNAL_SERVER_ERROR";
1546
+ this.requestedModel = readString(this.data, "requestedModel");
1547
+ this.reasonCode = readString(this.data, "code");
1548
+ this.supportMessage = this.requestId ? `PDF Vector request ${this.requestId} failed with ${this.code}: ${this.message}` : `PDF Vector request failed with ${this.code}: ${this.message}`;
1549
+ }
1550
+ toAgentError() {
1551
+ return {
1552
+ name: this.name,
1553
+ code: this.code,
1554
+ status: this.status,
1555
+ category: this.category,
1556
+ origin: this.origin,
1557
+ userError: this.userError,
1558
+ title: this.title,
1559
+ message: this.message,
1560
+ suggestion: this.suggestion,
1561
+ retryable: this.retryable,
1562
+ retryableWithHigherModel: this.retryableWithHigherModel,
1563
+ ...this.requestId !== void 0 ? { requestId: this.requestId } : {},
1564
+ ...this.documentId !== void 0 ? { documentId: this.documentId } : {},
1565
+ ...this.reasonCode !== void 0 ? { reasonCode: this.reasonCode } : {},
1566
+ ...this.requestedModel !== void 0 ? { requestedModel: this.requestedModel } : {},
1567
+ supportMessage: this.supportMessage,
1568
+ data: this.data
1569
+ };
1570
+ }
1571
+ toJSON() {
1572
+ return this.toAgentError();
1573
+ }
1574
+ };
1575
+ var BadRequestError = class extends PDFVectorError {
1576
+ constructor(options) {
1577
+ super({
1578
+ ...options,
1579
+ code: "BAD_REQUEST",
1580
+ status: 400
1581
+ });
1582
+ }
1583
+ };
1584
+ var UnauthorizedError = class extends PDFVectorError {
1585
+ constructor(options) {
1586
+ super({
1587
+ ...options,
1588
+ code: "UNAUTHORIZED",
1589
+ status: 401
1590
+ });
1591
+ }
1592
+ };
1593
+ var PaymentRequiredError = class extends PDFVectorError {
1594
+ totalCredits;
1595
+ remainingCredits;
1596
+ resetsAt;
1597
+ billingReason;
1598
+ invoiceCount;
1599
+ amountDue;
1600
+ currency;
1601
+ billingUrl;
1602
+ payUrl;
1603
+ constructor(options) {
1604
+ super({
1605
+ ...options,
1606
+ code: "PAYMENT_REQUIRED",
1607
+ status: 402
1608
+ });
1609
+ this.totalCredits = readNumber(options.data, "total");
1610
+ this.remainingCredits = readNumber(options.data, "remaining");
1611
+ this.resetsAt = readString(options.data, "resetsAt");
1612
+ this.billingReason = readString(options.data, "reason");
1613
+ this.invoiceCount = readNumber(options.data, "invoiceCount");
1614
+ this.amountDue = readNumber(options.data, "amountDue");
1615
+ this.currency = readString(options.data, "currency");
1616
+ this.billingUrl = readString(options.data, "billingUrl");
1617
+ this.payUrl = readString(options.data, "payUrl");
1618
+ }
1619
+ get isBillingHold() {
1620
+ return this.reasonCode?.startsWith("BILLING_") ?? false;
1621
+ }
1622
+ get isCreditsExhausted() {
1623
+ return this.reasonCode === "CREDITS_EXHAUSTED" || !this.isBillingHold;
1624
+ }
1625
+ };
1626
+ var NotFoundError = class extends PDFVectorError {
1627
+ constructor(options) {
1628
+ super({
1629
+ ...options,
1630
+ code: "NOT_FOUND",
1631
+ status: 404
1632
+ });
1633
+ }
1634
+ };
1635
+ var TooManyRequestsError = class extends PDFVectorError {
1636
+ limit;
1637
+ resetAt;
1638
+ retryAfterSeconds;
1639
+ constructor(options) {
1640
+ super({
1641
+ ...options,
1642
+ code: "TOO_MANY_REQUESTS",
1643
+ status: 429
1644
+ });
1645
+ this.limit = readNumber(options.data, "limit");
1646
+ this.resetAt = readString(options.data, "resetAt");
1647
+ this.retryAfterSeconds = readNumber(options.data, "retryAfterSeconds");
1648
+ }
1649
+ };
1650
+ var ConflictError = class extends PDFVectorError {
1651
+ constructor(options) {
1652
+ super({
1653
+ ...options,
1654
+ code: "CONFLICT",
1655
+ status: 409
1656
+ });
1657
+ }
1658
+ };
1659
+ var NotImplementedError = class extends PDFVectorError {
1660
+ constructor(options) {
1661
+ super({
1662
+ ...options,
1663
+ code: "NOT_IMPLEMENTED",
1664
+ status: 501
1665
+ });
1666
+ }
1667
+ };
1668
+ var UnprocessableContentError = class extends PDFVectorError {
1669
+ constructor(options) {
1670
+ super({
1671
+ ...options,
1672
+ code: "UNPROCESSABLE_CONTENT",
1673
+ status: 422
1674
+ });
1675
+ }
1676
+ };
1677
+ var InternalServerError = class extends PDFVectorError {
1678
+ constructor(options) {
1679
+ super({
1680
+ ...options,
1681
+ code: "INTERNAL_SERVER_ERROR",
1682
+ status: 500
1683
+ });
1684
+ }
1685
+ };
1686
+ var FileTooLargeError = class extends BadRequestError {
1687
+ fileSizeMB;
1688
+ limitMB;
1689
+ model;
1690
+ constructor(options) {
1691
+ super(options);
1692
+ this.fileSizeMB = readNumber(options.data, "fileSizeMB") ?? readNumberFromMatch(options.message, /file too large:\s*([\d.]+)\s*mb/i);
1693
+ this.limitMB = readNumber(options.data, "limitMB") ?? readNumberFromMatch(options.message, /exceeds the\s*([\d.]+)\s*mb limit/i);
1694
+ this.model = readString(options.data, "model") ?? readStringFromMatch(options.message, /for the '([^']+)' model/i);
1695
+ }
1696
+ };
1697
+ var PageLimitExceededError = class extends BadRequestError {
1698
+ pageCount;
1699
+ pageLimit;
1700
+ model;
1701
+ constructor(options) {
1702
+ super(options);
1703
+ this.pageCount = readNumber(options.data, "pageCount") ?? readNumberFromMatch(options.message, /document has\s*([\d.]+)\s*pages/i);
1704
+ this.pageLimit = readNumber(options.data, "pageLimit") ?? readNumberFromMatch(options.message, /exceeds the\s*([\d.]+)-page limit/i);
1705
+ this.model = readString(options.data, "model") ?? readStringFromMatch(options.message, /for the '([^']+)' model/i);
1706
+ }
1707
+ };
1708
+ var PasswordProtectedError = class extends BadRequestError {};
1709
+ var UnsupportedFormatError = class extends BadRequestError {
1710
+ format;
1711
+ supportedFormats;
1712
+ constructor(options) {
1713
+ super(options);
1714
+ this.format = readString(options.data, "format") ?? readStringFromMatch(options.message, /unsupported format \(([^)]+)\)/i);
1715
+ this.supportedFormats = readString(options.data, "supportedFormats") ?? readStringFromMatch(options.message, /supported formats:\s*(.+)$/i);
1716
+ }
1717
+ };
1718
+ var URLFetchError = class extends BadRequestError {
1719
+ url;
1720
+ statusCode;
1721
+ statusText;
1722
+ constructor(options) {
1723
+ super(options);
1724
+ this.url = readString(options.data, "url");
1725
+ this.statusCode = readNumber(options.data, "statusCode") ?? readNumberFromMatch(options.message, /document from url:\s*(\d{3})/i);
1726
+ this.statusText = readString(options.data, "statusText") ?? readStringFromMatch(options.message, /document from url:\s*\d{3}\s+(.+)$/i);
1727
+ }
1728
+ };
1729
+ var InvalidDocumentURLError = class extends BadRequestError {};
1730
+ var InvalidBase64Error = class extends BadRequestError {};
1731
+ var TierNotSupportedError = class extends BadRequestError {
1732
+ documentType;
1733
+ model;
1734
+ allowedTypes;
1735
+ constructor(options) {
1736
+ super(options);
1737
+ this.documentType = readString(options.data, "documentType") ?? readStringFromMatch(options.message, /file type '([^']+)'/i);
1738
+ this.model = readString(options.data, "model") ?? readStringFromMatch(options.message, /for the '([^']+)' tier/i);
1739
+ this.allowedTypes = readStringArray(options.data, "allowedTypes") ?? readListFromMatch(options.message, /supported types:\s*(.+)$/i);
1740
+ }
1741
+ };
1742
+ var InvalidSchemaError = class extends BadRequestError {
1743
+ reason;
1744
+ constructor(options) {
1745
+ super(options);
1746
+ this.reason = readString(options.data, "reason") ?? readStringFromMatch(options.message, /invalid json schema:\s*(.+)$/i);
1747
+ }
1748
+ };
1749
+ var NoInputProvidedError = class extends BadRequestError {};
1750
+ var EmptyDocumentError = class extends UnprocessableContentError {};
1751
+ var NoTextDetectedError = class extends UnprocessableContentError {};
1752
+ var ExtractionFailedError = class extends UnprocessableContentError {
1753
+ hint;
1754
+ rawText;
1755
+ constructor(options) {
1756
+ super(options);
1757
+ this.hint = readString(options.data, "hint");
1758
+ this.rawText = readString(options.data, "rawText");
1759
+ }
1760
+ };
1761
+ var AcademicPaperNotFoundError = class extends NotFoundError {
1762
+ input;
1763
+ paperErrorCode;
1764
+ constructor(options) {
1765
+ super(options);
1766
+ this.input = readString(options.data, "input");
1767
+ this.paperErrorCode = readString(options.data, "code");
1768
+ }
1769
+ };
1770
+ var NoPublicPDFError = class extends NotFoundError {
1771
+ input;
1772
+ paperTitle;
1773
+ doi;
1774
+ providerURL;
1775
+ constructor(options) {
1776
+ super(options);
1777
+ this.input = readString(options.data, "input");
1778
+ this.paperTitle = readString(options.data, "title");
1779
+ this.doi = readString(options.data, "doi");
1780
+ this.providerURL = readString(options.data, "providerURL");
1781
+ }
1782
+ };
1783
+ const ORPC_CODE_TO_CLASS = {
1784
+ BAD_REQUEST: BadRequestError,
1785
+ UNAUTHORIZED: UnauthorizedError,
1786
+ PAYMENT_REQUIRED: PaymentRequiredError,
1787
+ NOT_FOUND: NotFoundError,
1788
+ TOO_MANY_REQUESTS: TooManyRequestsError,
1789
+ CONFLICT: ConflictError,
1790
+ NOT_IMPLEMENTED: NotImplementedError,
1791
+ UNPROCESSABLE_CONTENT: UnprocessableContentError,
1792
+ INTERNAL_SERVER_ERROR: InternalServerError
1793
+ };
1794
+ function isPDFVectorErrorCode(code) {
1795
+ return code in ORPC_CODE_TO_CLASS;
1796
+ }
1797
+ function selectSpecializedClass(code, message, data) {
1798
+ const lower = message.toLowerCase();
1799
+ if (code === "BAD_REQUEST") {
1800
+ if (lower.includes("password-protected")) return PasswordProtectedError;
1801
+ if (lower.startsWith("file too large")) return FileTooLargeError;
1802
+ if (lower.startsWith("document has") && lower.includes("page") && lower.includes("limit")) return PageLimitExceededError;
1803
+ if (lower.startsWith("file type") && lower.includes("not supported for the")) return TierNotSupportedError;
1804
+ if (lower.startsWith("invalid json schema")) return InvalidSchemaError;
1805
+ if (lower.includes("unsupported format") || lower.includes("does not contain any supported document files")) return UnsupportedFormatError;
1806
+ if (lower.startsWith("failed to fetch document from url") || lower.startsWith("url did not return a supported document") || lower.includes("returned an html page instead of a document")) return URLFetchError;
1807
+ if (lower.startsWith("invalid document url") || lower.startsWith("document url must use")) return InvalidDocumentURLError;
1808
+ if (lower.startsWith("invalid base64-encoded string")) return InvalidBase64Error;
1809
+ if (lower.startsWith("no input provided") || lower.startsWith("empty document content")) return NoInputProvidedError;
1810
+ }
1811
+ if (code === "UNPROCESSABLE_CONTENT") {
1812
+ if (data["code"] === "EXTRACTION_FAILED") return ExtractionFailedError;
1813
+ if (lower.includes("does not appear to contain any readable text") || lower.includes("does not appear to contain any text")) return NoTextDetectedError;
1814
+ if (lower.includes("no text content detected") || lower.includes("document appears to be empty")) return EmptyDocumentError;
1815
+ if (lower.startsWith("failed to extract structured data")) return ExtractionFailedError;
1816
+ if (data["hint"] !== void 0 || data["rawText"] !== void 0) return ExtractionFailedError;
1817
+ }
1818
+ if (code === "NOT_FOUND") {
1819
+ if (data["code"] === "NO_PUBLIC_PDF" || lower.includes("no public pdf url")) return NoPublicPDFError;
1820
+ if (lower.startsWith("paper not found")) return AcademicPaperNotFoundError;
1821
+ }
1822
+ return ORPC_CODE_TO_CLASS[code];
1823
+ }
1824
+ function fromORPCError(error) {
1825
+ if (error instanceof PDFVectorError) return error;
1826
+ if (!(error instanceof ORPCError)) return void 0;
1827
+ if (!isPDFVectorErrorCode(error.code)) return void 0;
1828
+ const data = error.data != null && typeof error.data === "object" ? error.data : {};
1829
+ return new (selectSpecializedClass(error.code, error.message, data))({
1830
+ message: error.message,
1831
+ data,
1832
+ cause: error
1833
+ });
1834
+ }
1835
+ function isPDFVectorError(error) {
1836
+ return error instanceof PDFVectorError;
1837
+ }
1838
+ function isPDFVectorUserError(error) {
1839
+ return error instanceof PDFVectorError && error.userError;
1840
+ }
1841
+ // ../instance-client/lib/map-client-error.ts
1842
+ async function mapClientError({ next }) {
1843
+ try {
1844
+ return await next();
1845
+ } catch (error) {
1846
+ throw fromORPCError(error) ?? error;
1847
+ }
1848
+ }
1849
+ // ../instance-client/lib/index.ts
1850
+ const DEFAULT_DOMAIN = "global.pdfvector.com";
1851
+ function createClient(options) {
1852
+ const domain = options?.domain ?? DEFAULT_DOMAIN;
1853
+ const baseUrl = `${domain.startsWith("localhost") || domain.startsWith("127.0.0.1") ? "http" : "https"}://${domain}`;
1854
+ const token = options?.apiKey;
1855
+ const source = options?.source ?? "sdk";
1856
+ return createORPCClient(new RPCLink({
1857
+ url: `${baseUrl}/rpc`,
1858
+ interceptors: [mapClientError],
1859
+ headers: ({ context }) => {
1860
+ const headers = { "x-pdfvector-source": source };
1861
+ if (token) headers["authorization"] = `Bearer ${token}`;
1862
+ if (context?.documentId) headers["x-pdfvector-document-id"] = context.documentId;
1863
+ return headers;
1864
+ },
1865
+ fetch: (input, init) => fetch(input, token ? init : {
1866
+ ...init,
1867
+ credentials: "include"
1868
+ })
1869
+ }));
1870
+ }
1871
+ export { AcademicPaperNotFoundError, BadRequestError, ConflictError, EmptyDocumentError, ExtractionFailedError, FileTooLargeError, InternalServerError, InvalidBase64Error, InvalidDocumentURLError, InvalidSchemaError, NoInputProvidedError, NoPublicPDFError, NoTextDetectedError, NotFoundError, NotImplementedError, ORPCError, PDFVectorError, PageLimitExceededError, PasswordProtectedError, PaymentRequiredError, RPCLink, TierNotSupportedError, TooManyRequestsError, URLFetchError, UnauthorizedError, UnprocessableContentError, UnsupportedFormatError, createClient, createORPCClient, fromORPCError, isPDFVectorError, isPDFVectorUserError, onError };