solid-translate 0.2.0 → 1.0.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.
@@ -0,0 +1,1005 @@
1
+ #!/usr/bin/env node
2
+ import {
3
+ __commonJS,
4
+ __toESM
5
+ } from "./chunk-FYS2JH42.js";
6
+
7
+ // node_modules/secure-json-parse/index.js
8
+ var require_secure_json_parse = __commonJS({
9
+ "node_modules/secure-json-parse/index.js"(exports, module) {
10
+ "use strict";
11
+ var hasBuffer = typeof Buffer !== "undefined";
12
+ var suspectProtoRx = /"(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])"\s*:/;
13
+ var suspectConstructorRx = /"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/;
14
+ function _parse(text, reviver, options) {
15
+ if (options == null) {
16
+ if (reviver !== null && typeof reviver === "object") {
17
+ options = reviver;
18
+ reviver = void 0;
19
+ }
20
+ }
21
+ if (hasBuffer && Buffer.isBuffer(text)) {
22
+ text = text.toString();
23
+ }
24
+ if (text && text.charCodeAt(0) === 65279) {
25
+ text = text.slice(1);
26
+ }
27
+ const obj = JSON.parse(text, reviver);
28
+ if (obj === null || typeof obj !== "object") {
29
+ return obj;
30
+ }
31
+ const protoAction = options && options.protoAction || "error";
32
+ const constructorAction = options && options.constructorAction || "error";
33
+ if (protoAction === "ignore" && constructorAction === "ignore") {
34
+ return obj;
35
+ }
36
+ if (protoAction !== "ignore" && constructorAction !== "ignore") {
37
+ if (suspectProtoRx.test(text) === false && suspectConstructorRx.test(text) === false) {
38
+ return obj;
39
+ }
40
+ } else if (protoAction !== "ignore" && constructorAction === "ignore") {
41
+ if (suspectProtoRx.test(text) === false) {
42
+ return obj;
43
+ }
44
+ } else {
45
+ if (suspectConstructorRx.test(text) === false) {
46
+ return obj;
47
+ }
48
+ }
49
+ return filter(obj, { protoAction, constructorAction, safe: options && options.safe });
50
+ }
51
+ function filter(obj, { protoAction = "error", constructorAction = "error", safe } = {}) {
52
+ let next = [obj];
53
+ while (next.length) {
54
+ const nodes = next;
55
+ next = [];
56
+ for (const node of nodes) {
57
+ if (protoAction !== "ignore" && Object.prototype.hasOwnProperty.call(node, "__proto__")) {
58
+ if (safe === true) {
59
+ return null;
60
+ } else if (protoAction === "error") {
61
+ throw new SyntaxError("Object contains forbidden prototype property");
62
+ }
63
+ delete node.__proto__;
64
+ }
65
+ if (constructorAction !== "ignore" && Object.prototype.hasOwnProperty.call(node, "constructor") && Object.prototype.hasOwnProperty.call(node.constructor, "prototype")) {
66
+ if (safe === true) {
67
+ return null;
68
+ } else if (constructorAction === "error") {
69
+ throw new SyntaxError("Object contains forbidden prototype property");
70
+ }
71
+ delete node.constructor;
72
+ }
73
+ for (const key in node) {
74
+ const value = node[key];
75
+ if (value && typeof value === "object") {
76
+ next.push(value);
77
+ }
78
+ }
79
+ }
80
+ }
81
+ return obj;
82
+ }
83
+ function parse(text, reviver, options) {
84
+ const stackTraceLimit = Error.stackTraceLimit;
85
+ Error.stackTraceLimit = 0;
86
+ try {
87
+ return _parse(text, reviver, options);
88
+ } finally {
89
+ Error.stackTraceLimit = stackTraceLimit;
90
+ }
91
+ }
92
+ function safeParse(text, reviver) {
93
+ const stackTraceLimit = Error.stackTraceLimit;
94
+ Error.stackTraceLimit = 0;
95
+ try {
96
+ return _parse(text, reviver, { safe: true });
97
+ } catch (_e) {
98
+ return null;
99
+ } finally {
100
+ Error.stackTraceLimit = stackTraceLimit;
101
+ }
102
+ }
103
+ module.exports = parse;
104
+ module.exports.default = parse;
105
+ module.exports.parse = parse;
106
+ module.exports.safeParse = safeParse;
107
+ module.exports.scan = filter;
108
+ }
109
+ });
110
+
111
+ // node_modules/@ai-sdk/provider/dist/index.mjs
112
+ var marker = "vercel.ai.error";
113
+ var symbol = Symbol.for(marker);
114
+ var _a;
115
+ var _AISDKError = class _AISDKError2 extends Error {
116
+ /**
117
+ * Creates an AI SDK Error.
118
+ *
119
+ * @param {Object} params - The parameters for creating the error.
120
+ * @param {string} params.name - The name of the error.
121
+ * @param {string} params.message - The error message.
122
+ * @param {unknown} [params.cause] - The underlying cause of the error.
123
+ */
124
+ constructor({
125
+ name: name14,
126
+ message,
127
+ cause
128
+ }) {
129
+ super(message);
130
+ this[_a] = true;
131
+ this.name = name14;
132
+ this.cause = cause;
133
+ }
134
+ /**
135
+ * Checks if the given error is an AI SDK Error.
136
+ * @param {unknown} error - The error to check.
137
+ * @returns {boolean} True if the error is an AI SDK Error, false otherwise.
138
+ */
139
+ static isInstance(error) {
140
+ return _AISDKError2.hasMarker(error, marker);
141
+ }
142
+ static hasMarker(error, marker15) {
143
+ const markerSymbol = Symbol.for(marker15);
144
+ return error != null && typeof error === "object" && markerSymbol in error && typeof error[markerSymbol] === "boolean" && error[markerSymbol] === true;
145
+ }
146
+ };
147
+ _a = symbol;
148
+ var AISDKError = _AISDKError;
149
+ var name = "AI_APICallError";
150
+ var marker2 = `vercel.ai.error.${name}`;
151
+ var symbol2 = Symbol.for(marker2);
152
+ var _a2;
153
+ var APICallError = class extends AISDKError {
154
+ constructor({
155
+ message,
156
+ url,
157
+ requestBodyValues,
158
+ statusCode,
159
+ responseHeaders,
160
+ responseBody,
161
+ cause,
162
+ isRetryable = statusCode != null && (statusCode === 408 || // request timeout
163
+ statusCode === 409 || // conflict
164
+ statusCode === 429 || // too many requests
165
+ statusCode >= 500),
166
+ // server error
167
+ data
168
+ }) {
169
+ super({ name, message, cause });
170
+ this[_a2] = true;
171
+ this.url = url;
172
+ this.requestBodyValues = requestBodyValues;
173
+ this.statusCode = statusCode;
174
+ this.responseHeaders = responseHeaders;
175
+ this.responseBody = responseBody;
176
+ this.isRetryable = isRetryable;
177
+ this.data = data;
178
+ }
179
+ static isInstance(error) {
180
+ return AISDKError.hasMarker(error, marker2);
181
+ }
182
+ };
183
+ _a2 = symbol2;
184
+ var name2 = "AI_EmptyResponseBodyError";
185
+ var marker3 = `vercel.ai.error.${name2}`;
186
+ var symbol3 = Symbol.for(marker3);
187
+ var _a3;
188
+ var EmptyResponseBodyError = class extends AISDKError {
189
+ // used in isInstance
190
+ constructor({ message = "Empty response body" } = {}) {
191
+ super({ name: name2, message });
192
+ this[_a3] = true;
193
+ }
194
+ static isInstance(error) {
195
+ return AISDKError.hasMarker(error, marker3);
196
+ }
197
+ };
198
+ _a3 = symbol3;
199
+ function getErrorMessage(error) {
200
+ if (error == null) {
201
+ return "unknown error";
202
+ }
203
+ if (typeof error === "string") {
204
+ return error;
205
+ }
206
+ if (error instanceof Error) {
207
+ return error.message;
208
+ }
209
+ return JSON.stringify(error);
210
+ }
211
+ var name3 = "AI_InvalidArgumentError";
212
+ var marker4 = `vercel.ai.error.${name3}`;
213
+ var symbol4 = Symbol.for(marker4);
214
+ var _a4;
215
+ var InvalidArgumentError = class extends AISDKError {
216
+ constructor({
217
+ message,
218
+ cause,
219
+ argument
220
+ }) {
221
+ super({ name: name3, message, cause });
222
+ this[_a4] = true;
223
+ this.argument = argument;
224
+ }
225
+ static isInstance(error) {
226
+ return AISDKError.hasMarker(error, marker4);
227
+ }
228
+ };
229
+ _a4 = symbol4;
230
+ var name4 = "AI_InvalidPromptError";
231
+ var marker5 = `vercel.ai.error.${name4}`;
232
+ var symbol5 = Symbol.for(marker5);
233
+ var _a5;
234
+ var InvalidPromptError = class extends AISDKError {
235
+ constructor({
236
+ prompt,
237
+ message,
238
+ cause
239
+ }) {
240
+ super({ name: name4, message: `Invalid prompt: ${message}`, cause });
241
+ this[_a5] = true;
242
+ this.prompt = prompt;
243
+ }
244
+ static isInstance(error) {
245
+ return AISDKError.hasMarker(error, marker5);
246
+ }
247
+ };
248
+ _a5 = symbol5;
249
+ var name5 = "AI_InvalidResponseDataError";
250
+ var marker6 = `vercel.ai.error.${name5}`;
251
+ var symbol6 = Symbol.for(marker6);
252
+ var _a6;
253
+ var InvalidResponseDataError = class extends AISDKError {
254
+ constructor({
255
+ data,
256
+ message = `Invalid response data: ${JSON.stringify(data)}.`
257
+ }) {
258
+ super({ name: name5, message });
259
+ this[_a6] = true;
260
+ this.data = data;
261
+ }
262
+ static isInstance(error) {
263
+ return AISDKError.hasMarker(error, marker6);
264
+ }
265
+ };
266
+ _a6 = symbol6;
267
+ var name6 = "AI_JSONParseError";
268
+ var marker7 = `vercel.ai.error.${name6}`;
269
+ var symbol7 = Symbol.for(marker7);
270
+ var _a7;
271
+ var JSONParseError = class extends AISDKError {
272
+ constructor({ text, cause }) {
273
+ super({
274
+ name: name6,
275
+ message: `JSON parsing failed: Text: ${text}.
276
+ Error message: ${getErrorMessage(cause)}`,
277
+ cause
278
+ });
279
+ this[_a7] = true;
280
+ this.text = text;
281
+ }
282
+ static isInstance(error) {
283
+ return AISDKError.hasMarker(error, marker7);
284
+ }
285
+ };
286
+ _a7 = symbol7;
287
+ var name7 = "AI_LoadAPIKeyError";
288
+ var marker8 = `vercel.ai.error.${name7}`;
289
+ var symbol8 = Symbol.for(marker8);
290
+ var _a8;
291
+ var LoadAPIKeyError = class extends AISDKError {
292
+ // used in isInstance
293
+ constructor({ message }) {
294
+ super({ name: name7, message });
295
+ this[_a8] = true;
296
+ }
297
+ static isInstance(error) {
298
+ return AISDKError.hasMarker(error, marker8);
299
+ }
300
+ };
301
+ _a8 = symbol8;
302
+ var name8 = "AI_LoadSettingError";
303
+ var marker9 = `vercel.ai.error.${name8}`;
304
+ var symbol9 = Symbol.for(marker9);
305
+ var _a9;
306
+ _a9 = symbol9;
307
+ var name9 = "AI_NoContentGeneratedError";
308
+ var marker10 = `vercel.ai.error.${name9}`;
309
+ var symbol10 = Symbol.for(marker10);
310
+ var _a10;
311
+ _a10 = symbol10;
312
+ var name10 = "AI_NoSuchModelError";
313
+ var marker11 = `vercel.ai.error.${name10}`;
314
+ var symbol11 = Symbol.for(marker11);
315
+ var _a11;
316
+ var NoSuchModelError = class extends AISDKError {
317
+ constructor({
318
+ errorName = name10,
319
+ modelId,
320
+ modelType,
321
+ message = `No such ${modelType}: ${modelId}`
322
+ }) {
323
+ super({ name: errorName, message });
324
+ this[_a11] = true;
325
+ this.modelId = modelId;
326
+ this.modelType = modelType;
327
+ }
328
+ static isInstance(error) {
329
+ return AISDKError.hasMarker(error, marker11);
330
+ }
331
+ };
332
+ _a11 = symbol11;
333
+ var name11 = "AI_TooManyEmbeddingValuesForCallError";
334
+ var marker12 = `vercel.ai.error.${name11}`;
335
+ var symbol12 = Symbol.for(marker12);
336
+ var _a12;
337
+ var TooManyEmbeddingValuesForCallError = class extends AISDKError {
338
+ constructor(options) {
339
+ super({
340
+ name: name11,
341
+ message: `Too many values for a single embedding call. The ${options.provider} model "${options.modelId}" can only embed up to ${options.maxEmbeddingsPerCall} values per call, but ${options.values.length} values were provided.`
342
+ });
343
+ this[_a12] = true;
344
+ this.provider = options.provider;
345
+ this.modelId = options.modelId;
346
+ this.maxEmbeddingsPerCall = options.maxEmbeddingsPerCall;
347
+ this.values = options.values;
348
+ }
349
+ static isInstance(error) {
350
+ return AISDKError.hasMarker(error, marker12);
351
+ }
352
+ };
353
+ _a12 = symbol12;
354
+ var name12 = "AI_TypeValidationError";
355
+ var marker13 = `vercel.ai.error.${name12}`;
356
+ var symbol13 = Symbol.for(marker13);
357
+ var _a13;
358
+ var _TypeValidationError = class _TypeValidationError2 extends AISDKError {
359
+ constructor({ value, cause }) {
360
+ super({
361
+ name: name12,
362
+ message: `Type validation failed: Value: ${JSON.stringify(value)}.
363
+ Error message: ${getErrorMessage(cause)}`,
364
+ cause
365
+ });
366
+ this[_a13] = true;
367
+ this.value = value;
368
+ }
369
+ static isInstance(error) {
370
+ return AISDKError.hasMarker(error, marker13);
371
+ }
372
+ /**
373
+ * Wraps an error into a TypeValidationError.
374
+ * If the cause is already a TypeValidationError with the same value, it returns the cause.
375
+ * Otherwise, it creates a new TypeValidationError.
376
+ *
377
+ * @param {Object} params - The parameters for wrapping the error.
378
+ * @param {unknown} params.value - The value that failed validation.
379
+ * @param {unknown} params.cause - The original error or cause of the validation failure.
380
+ * @returns {TypeValidationError} A TypeValidationError instance.
381
+ */
382
+ static wrap({
383
+ value,
384
+ cause
385
+ }) {
386
+ return _TypeValidationError2.isInstance(cause) && cause.value === value ? cause : new _TypeValidationError2({ value, cause });
387
+ }
388
+ };
389
+ _a13 = symbol13;
390
+ var TypeValidationError = _TypeValidationError;
391
+ var name13 = "AI_UnsupportedFunctionalityError";
392
+ var marker14 = `vercel.ai.error.${name13}`;
393
+ var symbol14 = Symbol.for(marker14);
394
+ var _a14;
395
+ var UnsupportedFunctionalityError = class extends AISDKError {
396
+ constructor({
397
+ functionality,
398
+ message = `'${functionality}' functionality not supported.`
399
+ }) {
400
+ super({ name: name13, message });
401
+ this[_a14] = true;
402
+ this.functionality = functionality;
403
+ }
404
+ static isInstance(error) {
405
+ return AISDKError.hasMarker(error, marker14);
406
+ }
407
+ };
408
+ _a14 = symbol14;
409
+
410
+ // node_modules/nanoid/non-secure/index.js
411
+ var customAlphabet = (alphabet, defaultSize = 21) => {
412
+ return (size = defaultSize) => {
413
+ let id = "";
414
+ let i = size | 0;
415
+ while (i--) {
416
+ id += alphabet[Math.random() * alphabet.length | 0];
417
+ }
418
+ return id;
419
+ };
420
+ };
421
+
422
+ // node_modules/@ai-sdk/provider-utils/dist/index.mjs
423
+ var import_secure_json_parse = __toESM(require_secure_json_parse(), 1);
424
+ function combineHeaders(...headers) {
425
+ return headers.reduce(
426
+ (combinedHeaders, currentHeaders) => ({
427
+ ...combinedHeaders,
428
+ ...currentHeaders != null ? currentHeaders : {}
429
+ }),
430
+ {}
431
+ );
432
+ }
433
+ function createEventSourceParserStream() {
434
+ let buffer = "";
435
+ let event = void 0;
436
+ let data = [];
437
+ let lastEventId = void 0;
438
+ let retry = void 0;
439
+ function parseLine(line, controller) {
440
+ if (line === "") {
441
+ dispatchEvent(controller);
442
+ return;
443
+ }
444
+ if (line.startsWith(":")) {
445
+ return;
446
+ }
447
+ const colonIndex = line.indexOf(":");
448
+ if (colonIndex === -1) {
449
+ handleField(line, "");
450
+ return;
451
+ }
452
+ const field = line.slice(0, colonIndex);
453
+ const valueStart = colonIndex + 1;
454
+ const value = valueStart < line.length && line[valueStart] === " " ? line.slice(valueStart + 1) : line.slice(valueStart);
455
+ handleField(field, value);
456
+ }
457
+ function dispatchEvent(controller) {
458
+ if (data.length > 0) {
459
+ controller.enqueue({
460
+ event,
461
+ data: data.join("\n"),
462
+ id: lastEventId,
463
+ retry
464
+ });
465
+ data = [];
466
+ event = void 0;
467
+ retry = void 0;
468
+ }
469
+ }
470
+ function handleField(field, value) {
471
+ switch (field) {
472
+ case "event":
473
+ event = value;
474
+ break;
475
+ case "data":
476
+ data.push(value);
477
+ break;
478
+ case "id":
479
+ lastEventId = value;
480
+ break;
481
+ case "retry":
482
+ const parsedRetry = parseInt(value, 10);
483
+ if (!isNaN(parsedRetry)) {
484
+ retry = parsedRetry;
485
+ }
486
+ break;
487
+ }
488
+ }
489
+ return new TransformStream({
490
+ transform(chunk, controller) {
491
+ const { lines, incompleteLine } = splitLines(buffer, chunk);
492
+ buffer = incompleteLine;
493
+ for (let i = 0; i < lines.length; i++) {
494
+ parseLine(lines[i], controller);
495
+ }
496
+ },
497
+ flush(controller) {
498
+ parseLine(buffer, controller);
499
+ dispatchEvent(controller);
500
+ }
501
+ });
502
+ }
503
+ function splitLines(buffer, chunk) {
504
+ const lines = [];
505
+ let currentLine = buffer;
506
+ for (let i = 0; i < chunk.length; ) {
507
+ const char = chunk[i++];
508
+ if (char === "\n") {
509
+ lines.push(currentLine);
510
+ currentLine = "";
511
+ } else if (char === "\r") {
512
+ lines.push(currentLine);
513
+ currentLine = "";
514
+ if (chunk[i] === "\n") {
515
+ i++;
516
+ }
517
+ } else {
518
+ currentLine += char;
519
+ }
520
+ }
521
+ return { lines, incompleteLine: currentLine };
522
+ }
523
+ function extractResponseHeaders(response) {
524
+ const headers = {};
525
+ response.headers.forEach((value, key) => {
526
+ headers[key] = value;
527
+ });
528
+ return headers;
529
+ }
530
+ var createIdGenerator = ({
531
+ prefix,
532
+ size: defaultSize = 16,
533
+ alphabet = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",
534
+ separator = "-"
535
+ } = {}) => {
536
+ const generator = customAlphabet(alphabet, defaultSize);
537
+ if (prefix == null) {
538
+ return generator;
539
+ }
540
+ if (alphabet.includes(separator)) {
541
+ throw new InvalidArgumentError({
542
+ argument: "separator",
543
+ message: `The separator "${separator}" must not be part of the alphabet "${alphabet}".`
544
+ });
545
+ }
546
+ return (size) => `${prefix}${separator}${generator(size)}`;
547
+ };
548
+ var generateId = createIdGenerator();
549
+ function removeUndefinedEntries(record) {
550
+ return Object.fromEntries(
551
+ Object.entries(record).filter(([_key, value]) => value != null)
552
+ );
553
+ }
554
+ function isAbortError(error) {
555
+ return error instanceof Error && (error.name === "AbortError" || error.name === "TimeoutError");
556
+ }
557
+ function loadApiKey({
558
+ apiKey,
559
+ environmentVariableName,
560
+ apiKeyParameterName = "apiKey",
561
+ description
562
+ }) {
563
+ if (typeof apiKey === "string") {
564
+ return apiKey;
565
+ }
566
+ if (apiKey != null) {
567
+ throw new LoadAPIKeyError({
568
+ message: `${description} API key must be a string.`
569
+ });
570
+ }
571
+ if (typeof process === "undefined") {
572
+ throw new LoadAPIKeyError({
573
+ message: `${description} API key is missing. Pass it using the '${apiKeyParameterName}' parameter. Environment variables is not supported in this environment.`
574
+ });
575
+ }
576
+ apiKey = process.env[environmentVariableName];
577
+ if (apiKey == null) {
578
+ throw new LoadAPIKeyError({
579
+ message: `${description} API key is missing. Pass it using the '${apiKeyParameterName}' parameter or the ${environmentVariableName} environment variable.`
580
+ });
581
+ }
582
+ if (typeof apiKey !== "string") {
583
+ throw new LoadAPIKeyError({
584
+ message: `${description} API key must be a string. The value of the ${environmentVariableName} environment variable is not a string.`
585
+ });
586
+ }
587
+ return apiKey;
588
+ }
589
+ var validatorSymbol = /* @__PURE__ */ Symbol.for("vercel.ai.validator");
590
+ function validator(validate) {
591
+ return { [validatorSymbol]: true, validate };
592
+ }
593
+ function isValidator(value) {
594
+ return typeof value === "object" && value !== null && validatorSymbol in value && value[validatorSymbol] === true && "validate" in value;
595
+ }
596
+ function asValidator(value) {
597
+ return isValidator(value) ? value : zodValidator(value);
598
+ }
599
+ function zodValidator(zodSchema) {
600
+ return validator((value) => {
601
+ const result = zodSchema.safeParse(value);
602
+ return result.success ? { success: true, value: result.data } : { success: false, error: result.error };
603
+ });
604
+ }
605
+ function validateTypes({
606
+ value,
607
+ schema: inputSchema
608
+ }) {
609
+ const result = safeValidateTypes({ value, schema: inputSchema });
610
+ if (!result.success) {
611
+ throw TypeValidationError.wrap({ value, cause: result.error });
612
+ }
613
+ return result.value;
614
+ }
615
+ function safeValidateTypes({
616
+ value,
617
+ schema
618
+ }) {
619
+ const validator2 = asValidator(schema);
620
+ try {
621
+ if (validator2.validate == null) {
622
+ return { success: true, value };
623
+ }
624
+ const result = validator2.validate(value);
625
+ if (result.success) {
626
+ return result;
627
+ }
628
+ return {
629
+ success: false,
630
+ error: TypeValidationError.wrap({ value, cause: result.error })
631
+ };
632
+ } catch (error) {
633
+ return {
634
+ success: false,
635
+ error: TypeValidationError.wrap({ value, cause: error })
636
+ };
637
+ }
638
+ }
639
+ function parseJSON({
640
+ text,
641
+ schema
642
+ }) {
643
+ try {
644
+ const value = import_secure_json_parse.default.parse(text);
645
+ if (schema == null) {
646
+ return value;
647
+ }
648
+ return validateTypes({ value, schema });
649
+ } catch (error) {
650
+ if (JSONParseError.isInstance(error) || TypeValidationError.isInstance(error)) {
651
+ throw error;
652
+ }
653
+ throw new JSONParseError({ text, cause: error });
654
+ }
655
+ }
656
+ function safeParseJSON({
657
+ text,
658
+ schema
659
+ }) {
660
+ try {
661
+ const value = import_secure_json_parse.default.parse(text);
662
+ if (schema == null) {
663
+ return { success: true, value, rawValue: value };
664
+ }
665
+ const validationResult = safeValidateTypes({ value, schema });
666
+ return validationResult.success ? { ...validationResult, rawValue: value } : validationResult;
667
+ } catch (error) {
668
+ return {
669
+ success: false,
670
+ error: JSONParseError.isInstance(error) ? error : new JSONParseError({ text, cause: error })
671
+ };
672
+ }
673
+ }
674
+ function isParsableJson(input) {
675
+ try {
676
+ import_secure_json_parse.default.parse(input);
677
+ return true;
678
+ } catch (e) {
679
+ return false;
680
+ }
681
+ }
682
+ function parseProviderOptions({
683
+ provider,
684
+ providerOptions,
685
+ schema
686
+ }) {
687
+ if ((providerOptions == null ? void 0 : providerOptions[provider]) == null) {
688
+ return void 0;
689
+ }
690
+ const parsedProviderOptions = safeValidateTypes({
691
+ value: providerOptions[provider],
692
+ schema
693
+ });
694
+ if (!parsedProviderOptions.success) {
695
+ throw new InvalidArgumentError({
696
+ argument: "providerOptions",
697
+ message: `invalid ${provider} provider options`,
698
+ cause: parsedProviderOptions.error
699
+ });
700
+ }
701
+ return parsedProviderOptions.value;
702
+ }
703
+ var getOriginalFetch2 = () => globalThis.fetch;
704
+ var postJsonToApi = async ({
705
+ url,
706
+ headers,
707
+ body,
708
+ failedResponseHandler,
709
+ successfulResponseHandler,
710
+ abortSignal,
711
+ fetch
712
+ }) => postToApi({
713
+ url,
714
+ headers: {
715
+ "Content-Type": "application/json",
716
+ ...headers
717
+ },
718
+ body: {
719
+ content: JSON.stringify(body),
720
+ values: body
721
+ },
722
+ failedResponseHandler,
723
+ successfulResponseHandler,
724
+ abortSignal,
725
+ fetch
726
+ });
727
+ var postFormDataToApi = async ({
728
+ url,
729
+ headers,
730
+ formData,
731
+ failedResponseHandler,
732
+ successfulResponseHandler,
733
+ abortSignal,
734
+ fetch
735
+ }) => postToApi({
736
+ url,
737
+ headers,
738
+ body: {
739
+ content: formData,
740
+ values: Object.fromEntries(formData.entries())
741
+ },
742
+ failedResponseHandler,
743
+ successfulResponseHandler,
744
+ abortSignal,
745
+ fetch
746
+ });
747
+ var postToApi = async ({
748
+ url,
749
+ headers = {},
750
+ body,
751
+ successfulResponseHandler,
752
+ failedResponseHandler,
753
+ abortSignal,
754
+ fetch = getOriginalFetch2()
755
+ }) => {
756
+ try {
757
+ const response = await fetch(url, {
758
+ method: "POST",
759
+ headers: removeUndefinedEntries(headers),
760
+ body: body.content,
761
+ signal: abortSignal
762
+ });
763
+ const responseHeaders = extractResponseHeaders(response);
764
+ if (!response.ok) {
765
+ let errorInformation;
766
+ try {
767
+ errorInformation = await failedResponseHandler({
768
+ response,
769
+ url,
770
+ requestBodyValues: body.values
771
+ });
772
+ } catch (error) {
773
+ if (isAbortError(error) || APICallError.isInstance(error)) {
774
+ throw error;
775
+ }
776
+ throw new APICallError({
777
+ message: "Failed to process error response",
778
+ cause: error,
779
+ statusCode: response.status,
780
+ url,
781
+ responseHeaders,
782
+ requestBodyValues: body.values
783
+ });
784
+ }
785
+ throw errorInformation.value;
786
+ }
787
+ try {
788
+ return await successfulResponseHandler({
789
+ response,
790
+ url,
791
+ requestBodyValues: body.values
792
+ });
793
+ } catch (error) {
794
+ if (error instanceof Error) {
795
+ if (isAbortError(error) || APICallError.isInstance(error)) {
796
+ throw error;
797
+ }
798
+ }
799
+ throw new APICallError({
800
+ message: "Failed to process successful response",
801
+ cause: error,
802
+ statusCode: response.status,
803
+ url,
804
+ responseHeaders,
805
+ requestBodyValues: body.values
806
+ });
807
+ }
808
+ } catch (error) {
809
+ if (isAbortError(error)) {
810
+ throw error;
811
+ }
812
+ if (error instanceof TypeError && error.message === "fetch failed") {
813
+ const cause = error.cause;
814
+ if (cause != null) {
815
+ throw new APICallError({
816
+ message: `Cannot connect to API: ${cause.message}`,
817
+ cause,
818
+ url,
819
+ requestBodyValues: body.values,
820
+ isRetryable: true
821
+ // retry when network error
822
+ });
823
+ }
824
+ }
825
+ throw error;
826
+ }
827
+ };
828
+ async function resolve(value) {
829
+ if (typeof value === "function") {
830
+ value = value();
831
+ }
832
+ return Promise.resolve(value);
833
+ }
834
+ var createJsonErrorResponseHandler = ({
835
+ errorSchema,
836
+ errorToMessage,
837
+ isRetryable
838
+ }) => async ({ response, url, requestBodyValues }) => {
839
+ const responseBody = await response.text();
840
+ const responseHeaders = extractResponseHeaders(response);
841
+ if (responseBody.trim() === "") {
842
+ return {
843
+ responseHeaders,
844
+ value: new APICallError({
845
+ message: response.statusText,
846
+ url,
847
+ requestBodyValues,
848
+ statusCode: response.status,
849
+ responseHeaders,
850
+ responseBody,
851
+ isRetryable: isRetryable == null ? void 0 : isRetryable(response)
852
+ })
853
+ };
854
+ }
855
+ try {
856
+ const parsedError = parseJSON({
857
+ text: responseBody,
858
+ schema: errorSchema
859
+ });
860
+ return {
861
+ responseHeaders,
862
+ value: new APICallError({
863
+ message: errorToMessage(parsedError),
864
+ url,
865
+ requestBodyValues,
866
+ statusCode: response.status,
867
+ responseHeaders,
868
+ responseBody,
869
+ data: parsedError,
870
+ isRetryable: isRetryable == null ? void 0 : isRetryable(response, parsedError)
871
+ })
872
+ };
873
+ } catch (parseError) {
874
+ return {
875
+ responseHeaders,
876
+ value: new APICallError({
877
+ message: response.statusText,
878
+ url,
879
+ requestBodyValues,
880
+ statusCode: response.status,
881
+ responseHeaders,
882
+ responseBody,
883
+ isRetryable: isRetryable == null ? void 0 : isRetryable(response)
884
+ })
885
+ };
886
+ }
887
+ };
888
+ var createEventSourceResponseHandler = (chunkSchema) => async ({ response }) => {
889
+ const responseHeaders = extractResponseHeaders(response);
890
+ if (response.body == null) {
891
+ throw new EmptyResponseBodyError({});
892
+ }
893
+ return {
894
+ responseHeaders,
895
+ value: response.body.pipeThrough(new TextDecoderStream()).pipeThrough(createEventSourceParserStream()).pipeThrough(
896
+ new TransformStream({
897
+ transform({ data }, controller) {
898
+ if (data === "[DONE]") {
899
+ return;
900
+ }
901
+ controller.enqueue(
902
+ safeParseJSON({
903
+ text: data,
904
+ schema: chunkSchema
905
+ })
906
+ );
907
+ }
908
+ })
909
+ )
910
+ };
911
+ };
912
+ var createJsonResponseHandler = (responseSchema) => async ({ response, url, requestBodyValues }) => {
913
+ const responseBody = await response.text();
914
+ const parsedResult = safeParseJSON({
915
+ text: responseBody,
916
+ schema: responseSchema
917
+ });
918
+ const responseHeaders = extractResponseHeaders(response);
919
+ if (!parsedResult.success) {
920
+ throw new APICallError({
921
+ message: "Invalid JSON response",
922
+ cause: parsedResult.error,
923
+ statusCode: response.status,
924
+ responseHeaders,
925
+ responseBody,
926
+ url,
927
+ requestBodyValues
928
+ });
929
+ }
930
+ return {
931
+ responseHeaders,
932
+ value: parsedResult.value,
933
+ rawValue: parsedResult.rawValue
934
+ };
935
+ };
936
+ var createBinaryResponseHandler = () => async ({ response, url, requestBodyValues }) => {
937
+ const responseHeaders = extractResponseHeaders(response);
938
+ if (!response.body) {
939
+ throw new APICallError({
940
+ message: "Response body is empty",
941
+ url,
942
+ requestBodyValues,
943
+ statusCode: response.status,
944
+ responseHeaders,
945
+ responseBody: void 0
946
+ });
947
+ }
948
+ try {
949
+ const buffer = await response.arrayBuffer();
950
+ return {
951
+ responseHeaders,
952
+ value: new Uint8Array(buffer)
953
+ };
954
+ } catch (error) {
955
+ throw new APICallError({
956
+ message: "Failed to read response as array buffer",
957
+ url,
958
+ requestBodyValues,
959
+ statusCode: response.status,
960
+ responseHeaders,
961
+ responseBody: void 0,
962
+ cause: error
963
+ });
964
+ }
965
+ };
966
+ var { btoa, atob } = globalThis;
967
+ function convertBase64ToUint8Array(base64String) {
968
+ const base64Url = base64String.replace(/-/g, "+").replace(/_/g, "/");
969
+ const latin1string = atob(base64Url);
970
+ return Uint8Array.from(latin1string, (byte) => byte.codePointAt(0));
971
+ }
972
+ function convertUint8ArrayToBase64(array) {
973
+ let latin1string = "";
974
+ for (let i = 0; i < array.length; i++) {
975
+ latin1string += String.fromCodePoint(array[i]);
976
+ }
977
+ return btoa(latin1string);
978
+ }
979
+ function withoutTrailingSlash(url) {
980
+ return url == null ? void 0 : url.replace(/\/$/, "");
981
+ }
982
+
983
+ export {
984
+ APICallError,
985
+ InvalidPromptError,
986
+ InvalidResponseDataError,
987
+ NoSuchModelError,
988
+ TooManyEmbeddingValuesForCallError,
989
+ UnsupportedFunctionalityError,
990
+ combineHeaders,
991
+ generateId,
992
+ loadApiKey,
993
+ isParsableJson,
994
+ parseProviderOptions,
995
+ postJsonToApi,
996
+ postFormDataToApi,
997
+ resolve,
998
+ createJsonErrorResponseHandler,
999
+ createEventSourceResponseHandler,
1000
+ createJsonResponseHandler,
1001
+ createBinaryResponseHandler,
1002
+ convertBase64ToUint8Array,
1003
+ convertUint8ArrayToBase64,
1004
+ withoutTrailingSlash
1005
+ };