@ai-sdk/provider-utils 5.0.74 → 5.0.76

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ai-sdk/provider-utils",
3
- "version": "5.0.74",
3
+ "version": "5.0.76",
4
4
  "type": "module",
5
5
  "license": "Apache-2.0",
6
6
  "sideEffects": false,
@@ -42,7 +42,7 @@
42
42
  }
43
43
  },
44
44
  "dependencies": {
45
- "@ai-sdk/provider": "4.0.35",
45
+ "@ai-sdk/provider": "4.0.37",
46
46
  "@standard-schema/spec": "^1.1.0",
47
47
  "@workflow/serde": "4.1.0",
48
48
  "eventsource-parser": "^3.0.8",
@@ -341,13 +341,16 @@ export function detectMediaType({
341
341
  });
342
342
  }
343
343
 
344
- const signatures = topLevelSignatureTables[topLevelType as TopLevelMediaType];
345
-
346
- if (signatures === undefined) {
344
+ if (
345
+ !Object.prototype.hasOwnProperty.call(topLevelSignatureTables, topLevelType)
346
+ ) {
347
347
  return undefined;
348
348
  }
349
349
 
350
- return detectMediaTypeBySignatures({ data, signatures });
350
+ return detectMediaTypeBySignatures({
351
+ data,
352
+ signatures: topLevelSignatureTables[topLevelType as TopLevelMediaType],
353
+ });
351
354
  }
352
355
 
353
356
  /**
@@ -80,6 +80,9 @@ export async function fetchWithValidatedEndpoint({
80
80
  * target (e.g. an internal address) before we ever see its URL, defeating the
81
81
  * guard.
82
82
  *
83
+ * Manually followed redirects from HTTPS to HTTP are rejected before requesting
84
+ * the target.
85
+ *
83
86
  * Request headers are also protected: {@link sanitizeRequestHeaders} strips
84
87
  * proxy/metadata/cookie/hop-by-hop headers before the first request, and all
85
88
  * caller headers except `User-Agent` are dropped on a cross-origin redirect.
@@ -193,6 +196,16 @@ export async function fetchWithValidatedRedirects({
193
196
  void cancelResponseBody(response);
194
197
  const nextUrl = new URL(location, currentUrl).toString();
195
198
 
199
+ if (
200
+ new URL(currentUrl).protocol === 'https:' &&
201
+ new URL(nextUrl).protocol === 'http:'
202
+ ) {
203
+ throw new DownloadError({
204
+ url,
205
+ message: 'Redirect from HTTPS to HTTP was blocked',
206
+ });
207
+ }
208
+
196
209
  // Drop all caller headers except the user-agent before following a
197
210
  // redirect that crosses origin. Only stripping Authorization (as the
198
211
  // fetch spec does) is not enough on the server: providers authenticate
package/src/index.ts CHANGED
@@ -76,6 +76,10 @@ export { normalizeBatchRequestCounts } from './normalize-batch-request-counts';
76
76
  export * from './parse-json';
77
77
  export { parseJsonEventStream } from './parse-json-event-stream';
78
78
  export { parseProviderOptions } from './parse-provider-options';
79
+ export {
80
+ resolveProviderOptions,
81
+ type ProviderOptionsResolution,
82
+ } from './resolve-provider-options';
79
83
  export * from './post-multipart-stream-to-api';
80
84
  export * from './post-to-api';
81
85
  export {
@@ -0,0 +1,457 @@
1
+ import { InvalidArgumentError } from '@ai-sdk/provider';
2
+ import { asSchema, jsonSchema, type FlexibleSchema } from './schema';
3
+ import { convertUint8ArrayToBase64 } from './uint8-utils';
4
+
5
+ /**
6
+ * Streaming extraction of large base64 strings from a JSON response body.
7
+ *
8
+ * A JSON response that carries an image or a file is mostly one very long
9
+ * base64 string. The regular pipeline (collect chunks, concatenate, decode to
10
+ * text, `JSON.parse`, decode base64) holds about four copies of that string at
11
+ * once. The scanner reads the body chunk by chunk instead: strings at the
12
+ * configured paths are decoded to bytes while they stream in, and the text that
13
+ * is handed to `JSON.parse` (the "skeleton") holds a short placeholder in their
14
+ * place.
15
+ *
16
+ * - The skeleton is the original body except for the extracted strings, so
17
+ * `secureJsonParse` still sees every key (a base64 string cannot contain a
18
+ * quote, so it cannot hide one).
19
+ * - A string is extracted only if it is canonical standard-alphabet base64
20
+ * (length divisible by 4, `=` only as the final padding, zero trailing bits,
21
+ * no escape sequences or whitespace). The bytes are then exactly what `atob`
22
+ * gives for it. Everything else stays a string. What was decoded before a
23
+ * string turned out not to qualify is encoded back, which gives the original
24
+ * characters.
25
+ */
26
+
27
+ /** Strings that decode to fewer bytes stay strings. */
28
+ export const DEFAULT_BINARY_FIELD_MIN_BYTES = 64 * 1024;
29
+
30
+ /**
31
+ * The compiled paths, a trie that is walked while scanning. The edges of a node
32
+ * are the bytes of an object key (a key ends with its closing quote), `null`
33
+ * for the items of an array, and `true` for "a path ends here".
34
+ */
35
+ export type BinaryFieldPaths = Map<number | true | null, BinaryFieldPaths>;
36
+
37
+ const QUOTE = 0x22;
38
+ const BACKSLASH = 0x5c;
39
+ const EQUALS = 0x3d;
40
+ const COMMA = 0x2c;
41
+ const COLON = 0x3a;
42
+ const LEFT_BRACE = 0x7b;
43
+ const RIGHT_BRACE = 0x7d;
44
+ const LEFT_BRACKET = 0x5b;
45
+ const RIGHT_BRACKET = 0x5d;
46
+
47
+ // Where the scanner is.
48
+ const OUTSIDE = 0; // between tokens
49
+ const KEY = 1; // in an object key
50
+ const SKIP = 2; // in a string value that stays as it is
51
+ const BLOB = 3; // in a string value that is decoded while it streams in
52
+
53
+ /**
54
+ * Compiles paths such as `images[*]` or `content[*].data.data`: plain object
55
+ * keys (letters, digits, `_` and `-`) joined by `.`, and `[*]` for every
56
+ * element of an array. Keys are compared with the raw bytes of the key in the
57
+ * body, so a key written with an escape sequence never matches.
58
+ */
59
+ export function compileBinaryFieldPaths(
60
+ paths: readonly string[],
61
+ ): BinaryFieldPaths {
62
+ const root: BinaryFieldPaths = new Map();
63
+
64
+ for (const path of paths) {
65
+ if (!/^(?:[\w-]+|\[\*])(?:\.[\w-]+|\[\*])*$/.test(path)) {
66
+ throw new InvalidArgumentError({
67
+ argument: 'experimental_binaryFields',
68
+ message: `Invalid binary field path "${path}"`,
69
+ });
70
+ }
71
+
72
+ let node = root;
73
+ for (const segment of path.match(/\[\*]|[\w-]+/g)!) {
74
+ const edges =
75
+ segment === '[*]' ? [null] : new TextEncoder().encode(`${segment}"`);
76
+ for (const edge of edges) {
77
+ let next = node.get(edge);
78
+ if (next === undefined) {
79
+ node.set(edge, (next = new Map()));
80
+ }
81
+ node = next;
82
+ }
83
+ }
84
+ node.set(true, node);
85
+ }
86
+
87
+ return root;
88
+ }
89
+
90
+ export interface JsonBinaryFieldScanResult {
91
+ /** The body with extracted strings replaced by placeholders. */
92
+ text: string;
93
+ /** The extracted bytes by the placeholder text that stands in for them. */
94
+ binaries: ReadonlyMap<string, Uint8Array>;
95
+ }
96
+
97
+ function join(parts: Uint8Array[], length: number): Uint8Array {
98
+ const bytes = new Uint8Array(length);
99
+ let at = 0;
100
+ for (const part of parts) {
101
+ bytes.set(part, at);
102
+ at += part.length;
103
+ }
104
+ return bytes;
105
+ }
106
+
107
+ export function createJsonBinaryFieldScanner(
108
+ paths: BinaryFieldPaths,
109
+ minBytes = DEFAULT_BINARY_FIELD_MIN_BYTES,
110
+ ) {
111
+ // Six-bit value of each base64 character, 64 for everything else.
112
+ const sextet = new Uint8Array(256).fill(64);
113
+ for (let index = 0; index < 64; index++) {
114
+ sextet[
115
+ 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'.charCodeAt(
116
+ index,
117
+ )
118
+ ] = index;
119
+ }
120
+ const encoder = new TextEncoder();
121
+
122
+ // The skeleton, as bytes: it is decoded once at the end, like the regular
123
+ // path decodes the whole body.
124
+ const pieces: Uint8Array[] = [];
125
+ let piece = new Uint8Array(64 * 1024);
126
+ let pieceLength = 0;
127
+ let size = 0;
128
+ const binaries = new Map<string, Uint8Array>();
129
+
130
+ // JSON structure. Only the containers on a path get a frame; the ones that
131
+ // are not are counted in `skipped`.
132
+ // - keys: the node whose edges match the next key; null in an array
133
+ // - next: the node of the value that is read next
134
+ const frames: Array<{
135
+ keys: BinaryFieldPaths | null;
136
+ next?: BinaryFieldPaths;
137
+ }> = [];
138
+ let skipped = 0;
139
+ let mode = OUTSIDE;
140
+ let escaped = false;
141
+ let last = 0; // the last `{`, `,` or `:` outside of strings
142
+ let key: BinaryFieldPaths | undefined;
143
+
144
+ // The candidate string: whole groups of four characters are decoded into
145
+ // segments, the characters of an unfinished group are kept in `bits`.
146
+ let segments: Uint8Array[] = [];
147
+ let segment = new Uint8Array(0);
148
+ let at = 0; // bytes used in `segment`
149
+ let total = 0; // bytes decoded
150
+ let bits = 0;
151
+ let chars = 0; // characters in `bits`
152
+ let padding = 0; // `=` characters seen
153
+
154
+ const add = (bytes: Uint8Array) => {
155
+ // Coalesce small fragments: retaining a buffer for each matched string
156
+ // would make metadata grow with the number of values, even empty ones.
157
+ for (let offset = 0; offset < bytes.length; ) {
158
+ const length = Math.min(
159
+ piece.length - pieceLength,
160
+ bytes.length - offset,
161
+ );
162
+ piece.set(bytes.subarray(offset, offset + length), pieceLength);
163
+ pieceLength += length;
164
+ offset += length;
165
+ size += length;
166
+ if (pieceLength === piece.length) {
167
+ pieces.push(piece);
168
+ piece = new Uint8Array(64 * 1024);
169
+ pieceLength = 0;
170
+ }
171
+ }
172
+ };
173
+
174
+ // Adds the part of a chunk to the skeleton. It is copied: a view on the
175
+ // chunk would retain all of it.
176
+ const emit = (chunk: Uint8Array, start: number, end: number) =>
177
+ add(chunk.subarray(start, end));
178
+
179
+ const reset = () => {
180
+ segments = [];
181
+ segment = new Uint8Array(0);
182
+ at = 0;
183
+ total = 0;
184
+ bits = 0;
185
+ chars = 0;
186
+ padding = 0;
187
+ };
188
+
189
+ // Segments grow with the string, so that a short string does not pin a large
190
+ // buffer.
191
+ const grow = () => {
192
+ if (at > 0) {
193
+ segments.push(segment.subarray(0, at));
194
+ }
195
+ segment = new Uint8Array(Math.min(Math.max(total, 4096), 4 << 20));
196
+ at = 0;
197
+ };
198
+
199
+ // The unfinished group, as bytes of a group of three padded with zeros.
200
+ const rest = () => bits << ((4 - chars) * 6);
201
+
202
+ // The string was not extracted: its characters go back into the skeleton.
203
+ const restore = () => {
204
+ for (const part of [...segments, segment.subarray(0, at)]) {
205
+ add(encoder.encode(convertUint8ArrayToBase64(part)));
206
+ }
207
+ const group = rest();
208
+ add(
209
+ encoder.encode(
210
+ convertUint8ArrayToBase64(
211
+ Uint8Array.of(group >> 16, group >> 8, group),
212
+ ).slice(0, chars) + '='.repeat(padding),
213
+ ),
214
+ );
215
+ reset();
216
+ };
217
+
218
+ // The closing quote of a candidate string was reached.
219
+ const closeBlob = () => {
220
+ mode = OUTSIDE;
221
+ const tail = chars && chars - 1;
222
+
223
+ if (
224
+ padding === (4 - chars) % 4 &&
225
+ !(bits & ((1 << ((4 - chars) * 2)) - 1)) &&
226
+ total + tail >= minBytes
227
+ ) {
228
+ const group = rest();
229
+ const bytes = join([...segments, segment.subarray(0, at)], total + tail);
230
+ for (let index = 0; index < tail; index++) {
231
+ bytes[total + index] = group >> (16 - 8 * index);
232
+ }
233
+ const placeholder = `[binary data: ${bytes.length} bytes; ref ${crypto.getRandomValues(new Uint32Array(2)).join('-')}]`;
234
+ binaries.set(placeholder, bytes);
235
+ add(encoder.encode(placeholder));
236
+ reset();
237
+ } else {
238
+ restore();
239
+ }
240
+ };
241
+
242
+ const push = (chunk: Uint8Array) => {
243
+ // The first byte of the chunk that is not in the skeleton yet.
244
+ let from = 0;
245
+ const { length } = chunk;
246
+
247
+ for (let index = 0; index < length; index++) {
248
+ let byte = chunk[index];
249
+
250
+ if (mode === BLOB) {
251
+ // The characters of the string, with the unfinished group in local
252
+ // variables. The loop ends at the first byte that is not one.
253
+ if (padding === 0) {
254
+ let pending = bits;
255
+ let count = chars;
256
+ for (
257
+ let value;
258
+ index < length && (value = sextet[chunk[index]]) < 64;
259
+ index++
260
+ ) {
261
+ pending = (pending << 6) | value;
262
+ if (++count === 4) {
263
+ if (at + 3 > segment.length) {
264
+ grow();
265
+ }
266
+ segment[at++] = pending >> 16;
267
+ segment[at++] = pending >> 8;
268
+ segment[at++] = pending;
269
+ total += 3;
270
+ pending = 0;
271
+ count = 0;
272
+ }
273
+ }
274
+ bits = pending;
275
+ chars = count;
276
+ }
277
+
278
+ if (index >= length) {
279
+ break;
280
+ }
281
+
282
+ byte = chunk[index];
283
+ if (byte === QUOTE) {
284
+ closeBlob();
285
+ from = index;
286
+ } else if (byte === EQUALS && chars > 1 && padding < 4 - chars) {
287
+ // Padding completes a group of two or three characters.
288
+ padding++;
289
+ } else {
290
+ // Not canonical. The string goes on as a regular string, from this
291
+ // byte.
292
+ restore();
293
+ mode = SKIP;
294
+ from = index--;
295
+ }
296
+ } else if (mode !== OUTSIDE) {
297
+ if (mode === KEY) {
298
+ key = key?.get(byte);
299
+ }
300
+ if (escaped) {
301
+ escaped = false;
302
+ } else if (byte === BACKSLASH) {
303
+ escaped = true;
304
+ } else if (byte === QUOTE) {
305
+ if (mode === KEY) {
306
+ frames.at(-1)!.next = key;
307
+ }
308
+ mode = OUTSIDE;
309
+ }
310
+ } else if (byte === QUOTE) {
311
+ const frame = frames.at(-1);
312
+ if (skipped > 0) {
313
+ mode = SKIP;
314
+ } else if (frame?.keys && (last === LEFT_BRACE || last === COMMA)) {
315
+ mode = KEY;
316
+ key = frame.keys;
317
+ } else if ((frame ? frame.next : paths)?.get(true)) {
318
+ mode = BLOB;
319
+ // The opening quote still belongs to the skeleton.
320
+ emit(chunk, from, index + 1);
321
+ } else {
322
+ mode = SKIP;
323
+ }
324
+ } else if (byte === LEFT_BRACE || byte === LEFT_BRACKET) {
325
+ last = byte;
326
+ const frame = frames.at(-1);
327
+ const node = skipped > 0 ? undefined : frame ? frame.next : paths;
328
+ const items = node?.get(null);
329
+ if (byte === LEFT_BRACE && node) {
330
+ frames.push({ keys: node });
331
+ } else if (byte === LEFT_BRACKET && items) {
332
+ frames.push({ keys: null, next: items });
333
+ } else {
334
+ skipped++;
335
+ }
336
+ } else if (byte === RIGHT_BRACE || byte === RIGHT_BRACKET) {
337
+ if (skipped > 0) {
338
+ skipped--;
339
+ } else {
340
+ frames.pop();
341
+ }
342
+ } else if (byte === COMMA || byte === COLON) {
343
+ last = byte;
344
+ }
345
+ }
346
+
347
+ if (mode !== BLOB) {
348
+ emit(chunk, from, length);
349
+ }
350
+ };
351
+
352
+ const finish = (): JsonBinaryFieldScanResult => {
353
+ // A body that ends inside a candidate string is returned as it was
354
+ // received, so that the regular parser reports the truncation.
355
+ if (mode === BLOB) {
356
+ restore();
357
+ }
358
+ return {
359
+ text: new TextDecoder().decode(
360
+ join([...pieces, piece.subarray(0, pieceLength)], size),
361
+ ),
362
+ binaries,
363
+ };
364
+ };
365
+
366
+ return { push, finish };
367
+ }
368
+
369
+ /**
370
+ * Replaces the placeholders in a parsed value with the bytes they stand for.
371
+ * Objects and arrays are copied, the parsed value is not modified. A
372
+ * placeholder holds a random number, so a string that equals one is ours.
373
+ */
374
+ export function replaceBinaryFieldPlaceholders(
375
+ value: unknown,
376
+ binaries: ReadonlyMap<string, Uint8Array>,
377
+ ): unknown {
378
+ if (typeof value === 'string') {
379
+ return binaries.get(value) ?? value;
380
+ }
381
+ if (Array.isArray(value)) {
382
+ return value.map(item => replaceBinaryFieldPlaceholders(item, binaries));
383
+ }
384
+ if (value != null && typeof value === 'object') {
385
+ return Object.fromEntries(
386
+ Object.entries(value).map(([name, item]) => [
387
+ name,
388
+ replaceBinaryFieldPlaceholders(item, binaries),
389
+ ]),
390
+ );
391
+ }
392
+ return value;
393
+ }
394
+
395
+ /**
396
+ * Makes `JSON.stringify` give the placeholder for each of the arrays, instead
397
+ * of `{"0":…,"1":…}` with an entry for every byte: 24 MiB of bytes would
398
+ * become a string of more than 300 MB. That is what a validator, or the code
399
+ * that reports its issues, does with a value it puts into an error message.
400
+ * The property is not enumerable, so the arrays look the same otherwise.
401
+ * Returns the function that removes it again.
402
+ */
403
+ function maskBinariesInJson(binaries: ReadonlyMap<string, Uint8Array>) {
404
+ for (const [placeholder, bytes] of binaries) {
405
+ Object.defineProperty(bytes, 'toJSON', {
406
+ value: () => placeholder,
407
+ configurable: true,
408
+ });
409
+ }
410
+
411
+ return () => {
412
+ for (const bytes of binaries.values()) {
413
+ Reflect.deleteProperty(bytes, 'toJSON');
414
+ }
415
+ };
416
+ }
417
+
418
+ /**
419
+ * Wraps a schema so that it validates the extracted bytes in place of their
420
+ * placeholders. The value parsed from the skeleton, and the value of the
421
+ * validation error of the response, keep the placeholders: reporting an error
422
+ * never prints the bytes.
423
+ *
424
+ * The errors of the schema itself may hold the bytes: a Standard Schema
425
+ * validator wraps the value it was given into an error, and the issues it
426
+ * reports may carry the offending input. So that their messages do not grow
427
+ * with the image, the arrays stringify as their placeholders, and keep doing
428
+ * so as long as an error can refer to them. When the validation succeeds the
429
+ * arrays are plain again, for whoever receives them.
430
+ */
431
+ export function withBinaryFields<T>(
432
+ schema: FlexibleSchema<T>,
433
+ binaries: ReadonlyMap<string, Uint8Array>,
434
+ ): FlexibleSchema<T> {
435
+ if (binaries.size === 0) {
436
+ return schema;
437
+ }
438
+
439
+ const actualSchema = asSchema(schema);
440
+
441
+ return jsonSchema<T>(
442
+ {},
443
+ {
444
+ validate: async value => {
445
+ const replaced = replaceBinaryFieldPlaceholders(value, binaries);
446
+ const unmask = maskBinariesInJson(binaries);
447
+ const result = actualSchema.validate
448
+ ? await actualSchema.validate(replaced)
449
+ : { success: true as const, value: replaced as T };
450
+ if (result.success) {
451
+ unmask();
452
+ }
453
+ return result;
454
+ },
455
+ },
456
+ );
457
+ }
@@ -24,6 +24,9 @@ export const DEFAULT_MAX_DOWNLOAD_SIZE = 2 * 1024 * 1024 * 1024;
24
24
  * @param response - The fetch Response to read.
25
25
  * @param url - The URL being downloaded (used in error messages).
26
26
  * @param maxBytes - Maximum allowed bytes. Defaults to DEFAULT_MAX_DOWNLOAD_SIZE.
27
+ * @param onChunk - Optional. Receives each chunk instead of the chunks being
28
+ * collected, so the body is not held in memory, and the returned array is empty.
29
+ * The chunk may be a view on a larger buffer, copy what you keep.
27
30
  * @returns A Uint8Array containing the response body.
28
31
  * @throws DownloadError if the response exceeds maxBytes.
29
32
  */
@@ -31,10 +34,12 @@ export async function readResponseWithSizeLimit({
31
34
  response,
32
35
  url,
33
36
  maxBytes = DEFAULT_MAX_DOWNLOAD_SIZE,
37
+ onChunk,
34
38
  }: {
35
39
  response: Response;
36
40
  url: string;
37
41
  maxBytes?: number;
42
+ onChunk?: (chunk: Uint8Array) => void;
38
43
  }): Promise<Uint8Array> {
39
44
  // Early rejection based on Content-Length header
40
45
  const contentLength = response.headers.get('content-length');
@@ -79,6 +84,11 @@ export async function readResponseWithSizeLimit({
79
84
  });
80
85
  }
81
86
 
87
+ if (onChunk != null) {
88
+ onChunk(value);
89
+ continue;
90
+ }
91
+
82
92
  // A small chunk can keep a much larger backing buffer alive. Copy such
83
93
  // views before retaining them. Unlike Uint8Array, Node Buffer's slice()
84
94
  // returns another view, so use the Uint8Array constructor to copy.
@@ -99,7 +109,7 @@ export async function readResponseWithSizeLimit({
99
109
  }
100
110
 
101
111
  // Concatenate chunks into a single Uint8Array
102
- const result = new Uint8Array(totalBytes);
112
+ const result = new Uint8Array(onChunk != null ? 0 : totalBytes);
103
113
  let offset = 0;
104
114
  for (const chunk of chunks) {
105
115
  result.set(chunk, offset);
@@ -0,0 +1,68 @@
1
+ import type { FlexibleSchema } from './schema';
2
+ import { parseProviderOptions } from './parse-provider-options';
3
+
4
+ /**
5
+ * How options found under several `providerOptions` namespaces are combined.
6
+ *
7
+ * - `first`: namespaces are aliases. The first namespace that is present wins
8
+ * as a whole and later namespaces are ignored (no merging).
9
+ * - `merge`: every present namespace is parsed and the results are merged in
10
+ * order, so later namespaces override earlier ones key by key.
11
+ */
12
+ export type ProviderOptionsResolution = 'first' | 'merge';
13
+
14
+ /**
15
+ * Parses provider options that a model accepts under more than one
16
+ * `providerOptions` namespace, e.g. a canonical key plus a provider-specific
17
+ * or legacy alias.
18
+ *
19
+ * Each present namespace is validated against `schema` exactly like
20
+ * `parseProviderOptions` does, so an invalid namespace throws.
21
+ *
22
+ * @returns the resolved options (`undefined` when no namespace is present)
23
+ * and the namespaces that contributed to them, in resolution order.
24
+ */
25
+ export async function resolveProviderOptions<OPTIONS>({
26
+ providerOptions,
27
+ namespaces,
28
+ resolution,
29
+ schema,
30
+ }: {
31
+ providerOptions: Record<string, unknown> | undefined;
32
+ namespaces: readonly string[];
33
+ resolution: ProviderOptionsResolution;
34
+ schema: FlexibleSchema<OPTIONS>;
35
+ }): Promise<{
36
+ options: OPTIONS | undefined;
37
+ namespaces: string[];
38
+ }> {
39
+ const parsed: OPTIONS[] = [];
40
+ const matched: string[] = [];
41
+
42
+ for (const namespace of new Set(namespaces)) {
43
+ const options = await parseProviderOptions({
44
+ provider: namespace,
45
+ providerOptions,
46
+ schema,
47
+ });
48
+
49
+ if (options == null) {
50
+ continue;
51
+ }
52
+
53
+ if (resolution === 'first') {
54
+ return { options, namespaces: [namespace] };
55
+ }
56
+
57
+ parsed.push(options);
58
+ matched.push(namespace);
59
+ }
60
+
61
+ return {
62
+ options:
63
+ parsed.length === 0
64
+ ? undefined
65
+ : (Object.assign({}, ...parsed) as OPTIONS),
66
+ namespaces: matched,
67
+ };
68
+ }