blink 1.1.32 → 1.1.34
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/browser/control/index.d.cts +28 -20
- package/dist/browser/control/index.d.ts +28 -20
- package/dist/cli/chat-manager-bMAuoSb5.js +21 -0
- package/dist/cli/chat-mj0wnV3_.js +1 -0
- package/dist/cli/compute-server-BFNeHOmk.js +1 -0
- package/dist/cli/{connect-t56RPJRB.js → connect-BnhWpzRI.js} +1 -1
- package/dist/cli/connect-Cd-0O7Uu.js +1 -0
- package/dist/cli/create-github-app-Dld06QIC.js +16 -0
- package/dist/cli/{dev-1VmtF950.js → dev-9EzQCNmd.js} +159 -180
- package/dist/cli/{getMachineId-bsd-BECgXpZb.js → getMachineId-bsd-BfwVPdTh.js} +1 -1
- package/dist/cli/{getMachineId-bsd-BgAyii4H.js → getMachineId-bsd-BmhpEQU_.js} +1 -1
- package/dist/cli/{getMachineId-bsd-Cc73dhdJ.js → getMachineId-bsd-C1eeoY31.js} +1 -1
- package/dist/cli/{getMachineId-bsd-DJn61I3m.js → getMachineId-bsd-CO9ne--Y.js} +1 -1
- package/dist/cli/{getMachineId-bsd-Doah6QJP.js → getMachineId-bsd-D4uBPoNF.js} +1 -1
- package/dist/cli/getMachineId-bsd-DVGtITCk.js +1 -0
- package/dist/cli/getMachineId-bsd-MA4oFaCa.js +1 -0
- package/dist/cli/getMachineId-bsd-dbToLPez.js +1 -0
- package/dist/cli/{getMachineId-darwin-BMnMBte0.js → getMachineId-darwin-C0EZ3sY3.js} +1 -1
- package/dist/cli/{getMachineId-darwin-BP9BSYcd.js → getMachineId-darwin-CSfD7gS4.js} +1 -1
- package/dist/cli/{getMachineId-darwin-Bs3mlKrs.js → getMachineId-darwin-CgQ9n4TU.js} +1 -1
- package/dist/cli/{getMachineId-darwin-DFronuaU.js → getMachineId-darwin-Cpq0Lloc.js} +1 -1
- package/dist/cli/{getMachineId-darwin-D-l4_nyT.js → getMachineId-darwin-CuAzoP7O.js} +1 -1
- package/dist/cli/getMachineId-darwin-D6_tdcZj.js +2 -0
- package/dist/cli/getMachineId-darwin-DkExT2qu.js +2 -0
- package/dist/cli/getMachineId-darwin-xoAzTD7x.js +2 -0
- package/dist/cli/{getMachineId-linux-B2r_HEgX.js → getMachineId-linux-B1XJTHUh.js} +1 -1
- package/dist/cli/{getMachineId-linux-Bj52Hdvy.js → getMachineId-linux-CRUR6LbQ.js} +1 -1
- package/dist/cli/{getMachineId-linux-C9o1dYwI.js → getMachineId-linux-CVQNNGui.js} +1 -1
- package/dist/cli/{getMachineId-linux-CGcBOg7J.js → getMachineId-linux-CtdZRCaX.js} +1 -1
- package/dist/cli/getMachineId-linux-DMILcDJR.js +1 -0
- package/dist/cli/getMachineId-linux-Deja7F2k.js +1 -0
- package/dist/cli/getMachineId-linux-DqOGXYgv.js +1 -0
- package/dist/cli/getMachineId-linux-FRx9q8NV.js +1 -0
- package/dist/cli/{getMachineId-unsupported-BtmyS2eg.js → getMachineId-unsupported-B-xvzil1.js} +1 -1
- package/dist/cli/{getMachineId-unsupported-C8az6JKm.js → getMachineId-unsupported-BA3eQjiV.js} +1 -1
- package/dist/cli/{getMachineId-unsupported-CBS2qXAs.js → getMachineId-unsupported-BZCOxs7n.js} +1 -1
- package/dist/cli/{getMachineId-unsupported-Cu0DvxaU.js → getMachineId-unsupported-BjGFauqb.js} +1 -1
- package/dist/cli/getMachineId-unsupported-CLWxRb7f.js +1 -0
- package/dist/cli/getMachineId-unsupported-CSVFDvWp.js +1 -0
- package/dist/cli/getMachineId-unsupported-Cp_95R-6.js +1 -0
- package/dist/cli/getMachineId-unsupported-Nd0_Z7NT.js +1 -0
- package/dist/cli/{getMachineId-win-BCAO7ld1.js → getMachineId-win-AW-Mv9PG.js} +1 -1
- package/dist/cli/{getMachineId-win-BDQszRKi.js → getMachineId-win-B_2C1cwE.js} +1 -1
- package/dist/cli/{getMachineId-win-BOnF6rL7.js → getMachineId-win-BbYxddZ9.js} +1 -1
- package/dist/cli/{getMachineId-win-BOuIHcz_.js → getMachineId-win-BkozcdSh.js} +1 -1
- package/dist/cli/getMachineId-win-CPhFagnx.js +1 -0
- package/dist/cli/{getMachineId-win-pnMl0wak.js → getMachineId-win-CUeKGXdr.js} +1 -1
- package/dist/cli/getMachineId-win-D3-sMfSu.js +1 -0
- package/dist/cli/getMachineId-win-DFVpvzl3.js +1 -0
- package/dist/cli/index.js +7 -7
- package/dist/cli/init-CByRT25U.js +23 -0
- package/dist/cli/{init-templates-D4lwX_8M.js → init-templates-jGRvqLQ6.js} +614 -1
- package/dist/cli/run-Lp28Ogb_.js +1 -0
- package/dist/cli/setup-github-app-D-K7e6al.js +9 -0
- package/dist/cli/{token-Bk68OrJt.js → token-ClGOahUF.js} +1 -1
- package/dist/cli/token-util-DIx5k-1f.js +1 -0
- package/dist/cli/{token-util-BKLboTb2.js → token-util-h1hcKvQX.js} +1 -1
- package/dist/cli/undici-JD4hDNWZ.js +1 -0
- package/dist/cli/utils-B3iC7vdW.js +1 -0
- package/dist/node/agent/index.node.cjs +1 -1
- package/dist/node/agent/index.node.js +1 -1
- package/dist/node/{index.node-Bvp48I1R.cjs → index.node-Btg8Ii_o.cjs} +2 -2
- package/dist/node/{index.node-ppzOWVGE.js → index.node-xL4mvvNL.js} +2 -2
- package/dist/node/react/index.node.cjs +620 -7
- package/dist/node/react/index.node.js +620 -7
- package/package.json +1 -1
- package/dist/cli/chat-C_rQ9SRr.js +0 -1
- package/dist/cli/chat-manager-bLgTuAnK.js +0 -21
- package/dist/cli/compute-server-BDrjNQ0q.js +0 -1
- package/dist/cli/connect-CgLoRyDv.js +0 -1
- package/dist/cli/create-slack-app-CyVPwWsG.js +0 -1
- package/dist/cli/events-DKgZ2LNM.js +0 -1
- package/dist/cli/getMachineId-bsd-aoAkh_W6.js +0 -1
- package/dist/cli/getMachineId-bsd-iPOb0TqF.js +0 -1
- package/dist/cli/getMachineId-bsd-io5tPlFg.js +0 -1
- package/dist/cli/getMachineId-darwin-DJO6fOdc.js +0 -2
- package/dist/cli/getMachineId-darwin-DlRRGl6M.js +0 -2
- package/dist/cli/getMachineId-darwin-Wp0usMIp.js +0 -2
- package/dist/cli/getMachineId-linux-CV2HmJXY.js +0 -1
- package/dist/cli/getMachineId-linux-Cv44Y8ZY.js +0 -1
- package/dist/cli/getMachineId-linux-CzNEh3DJ.js +0 -1
- package/dist/cli/getMachineId-linux-_RiwpX2J.js +0 -1
- package/dist/cli/getMachineId-unsupported-Dni2ujA-.js +0 -1
- package/dist/cli/getMachineId-unsupported-MPNVP8rP.js +0 -1
- package/dist/cli/getMachineId-unsupported-mBJd3oBN.js +0 -1
- package/dist/cli/getMachineId-unsupported-rdNf8ej6.js +0 -1
- package/dist/cli/getMachineId-win-BQ_C7kS3.js +0 -1
- package/dist/cli/getMachineId-win-Bw0-Mlkn.js +0 -1
- package/dist/cli/getMachineId-win-DrJTv2qi.js +0 -1
- package/dist/cli/init-DXBledyD.js +0 -23
- package/dist/cli/run-CRrWbMEw.js +0 -1
- package/dist/cli/setup-slack-app-C9L0iIDZ.js +0 -1
- package/dist/cli/token-util-Dui5nOLw.js +0 -1
- package/dist/cli/undici-mM2IfLwA.js +0 -1
- /package/dist/cli/{devtools-CS3ukAFj.js → devtools-CwQnB6v7.js} +0 -0
- /package/dist/cli/{esm-CYkSi8_o.js → esm-BiWxO8S7.js} +0 -0
- /package/dist/cli/{execAsync-9jtK4I3l.js → execAsync-4IyNgpoN.js} +0 -0
- /package/dist/cli/{execAsync-B4_pEoEJ.js → execAsync-B6xSGvuk.js} +0 -0
- /package/dist/cli/{execAsync-BdK7RB6d.js → execAsync-B8_ZTafx.js} +0 -0
- /package/dist/cli/{execAsync-Bjxs-bO2.js → execAsync-B8nelpRN.js} +0 -0
- /package/dist/cli/{execAsync-CM_C8SBr.js → execAsync-Cj_jF8MF.js} +0 -0
- /package/dist/cli/{execAsync-CNFaXJjR.js → execAsync-Ckbi9Yqe.js} +0 -0
- /package/dist/cli/{execAsync-Dl3hbWiU.js → execAsync-CvOpnFex.js} +0 -0
- /package/dist/cli/{execAsync-qGIZ8XA8.js → execAsync-DDBH3pWg.js} +0 -0
- /package/dist/cli/{token-error-CGIVaIg6.js → token-error-BHDo_48c.js} +0 -0
- /package/dist/cli/{undici-BiTrd9-R.js → undici-B5tM_IT9.js} +0 -0
|
@@ -4,7 +4,7 @@ Error message: ${getErrorMessage(cause)}`,cause}),this[_a13]=!0,this.value=value
|
|
|
4
4
|
`;break;case`id`:id=value.includes(`\0`)?void 0:value;break;case`retry`:/^\d+$/.test(value)?onRetry(parseInt(value,10)):onError(new ParseError(`Invalid \`retry\` value: "${value}"`,{type:`invalid-retry`,value,line}));break;default:onError(new ParseError(`Unknown field "${field.length>20?`${field.slice(0,20)}\u2026`:field}"`,{type:`unknown-field`,field,value,line}));break}}function dispatchEvent(){data.length>0&&onEvent({id,event:eventType||void 0,data:data.endsWith(`
|
|
5
5
|
`)?data.slice(0,-1):data}),id=void 0,data=``,eventType=``}function reset(options={}){incompleteLine&&options.consume&&parseLine(incompleteLine),isFirstChunk=!0,id=void 0,data=``,eventType=``,incompleteLine=``}return{feed,reset}}function splitLines(chunk){let lines=[],incompleteLine=``,searchIndex=0;for(;searchIndex<chunk.length;){let crIndex=chunk.indexOf(`\r`,searchIndex),lfIndex=chunk.indexOf(`
|
|
6
6
|
`,searchIndex),lineEnd=-1;if(crIndex!==-1&&lfIndex!==-1?lineEnd=Math.min(crIndex,lfIndex):crIndex===-1?lfIndex!==-1&&(lineEnd=lfIndex):lineEnd=crIndex===chunk.length-1?-1:crIndex,lineEnd===-1){incompleteLine=chunk.slice(searchIndex);break}else{let line=chunk.slice(searchIndex,lineEnd);lines.push(line),searchIndex=lineEnd+1,chunk[searchIndex-1]===`\r`&&chunk[searchIndex]===`
|
|
7
|
-
`&&searchIndex++}}return[lines,incompleteLine]}var EventSourceParserStream=class extends TransformStream{constructor({onError,onRetry,onComment}={}){let parser;super({start(controller){parser=createParser({onEvent:event=>{controller.enqueue(event)},onError(error){onError===`terminate`?controller.error(error):typeof onError==`function`&&onError(error)},onRetry,onComment})},transform(chunk){parser.feed(chunk)}})}};function combineHeaders(...headers){return headers.reduce((combinedHeaders,currentHeaders)=>({...combinedHeaders,...currentHeaders??{}}),{})}function extractResponseHeaders(response){return Object.fromEntries([...response.headers])}var generateId=(({prefix,size=16,alphabet=`0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz`,separator=`-`}={})=>{let generator=()=>{let alphabetLength=alphabet.length,chars=Array(size);for(let i$1=0;i$1<size;i$1++)chars[i$1]=alphabet[Math.random()*alphabetLength|0];return chars.join(``)};if(prefix==null)return generator;if(alphabet.includes(separator))throw new InvalidArgumentError({argument:`separator`,message:`The separator "${separator}" must not be part of the alphabet "${alphabet}".`});return()=>`${prefix}${separator}${generator()}`})();function isAbortError(error){return(error instanceof Error||error instanceof DOMException)&&(error.name===`AbortError`||error.name===`ResponseAborted`||error.name===`TimeoutError`)}var FETCH_FAILED_ERROR_MESSAGES=[`fetch failed`,`failed to fetch`];function handleFetchError({error,url,requestBodyValues}){if(isAbortError(error))return error;if(error instanceof TypeError&&FETCH_FAILED_ERROR_MESSAGES.includes(error.message.toLowerCase())){let cause=error.cause;if(cause!=null)return new APICallError({message:`Cannot connect to API: ${cause.message}`,cause,url,requestBodyValues,isRetryable:!0})}return error}function getRuntimeEnvironmentUserAgent(globalThisAny=globalThis){var _a$2,_b$1,_c;return globalThisAny.window?`runtime/browser`:globalThisAny.navigator?.userAgent?`runtime/${globalThisAny.navigator.userAgent.toLowerCase()}`:globalThisAny.process?.versions?.node?`runtime/node.js/${globalThisAny.process.version.substring(0)}`:globalThisAny.EdgeRuntime?`runtime/vercel-edge`:`runtime/unknown`}function removeUndefinedEntries(record){return Object.fromEntries(Object.entries(record).filter(([_key,value])=>value!=null))}function withUserAgentSuffix(headers,...userAgentSuffixParts){let cleanedHeaders=removeUndefinedEntries(headers??{}),normalizedHeaders=new Headers(cleanedHeaders),currentUserAgentHeader=normalizedHeaders.get(`user-agent`)||``;return normalizedHeaders.set(`user-agent`,[currentUserAgentHeader,...userAgentSuffixParts].filter(Boolean).join(` `)),Object.fromEntries(normalizedHeaders)}var VERSION$2=`3.0.12`,getOriginalFetch=()=>globalThis.fetch,getFromApi=async({url,headers={},successfulResponseHandler,failedResponseHandler,abortSignal,fetch:fetch$1=getOriginalFetch()})=>{try{let response=await fetch$1(url,{method:`GET`,headers:withUserAgentSuffix(headers,`ai-sdk/provider-utils/${VERSION$2}`,getRuntimeEnvironmentUserAgent()),signal:abortSignal}),responseHeaders=extractResponseHeaders(response);if(!response.ok){let errorInformation;try{errorInformation=await failedResponseHandler({response,url,requestBodyValues:{}})}catch(error){throw isAbortError(error)||APICallError.isInstance(error)?error:new APICallError({message:`Failed to process error response`,cause:error,statusCode:response.status,url,responseHeaders,requestBodyValues:{}})}throw errorInformation.value}try{return await successfulResponseHandler({response,url,requestBodyValues:{}})}catch(error){throw error instanceof Error&&(isAbortError(error)||APICallError.isInstance(error))?error:new APICallError({message:`Failed to process successful response`,cause:error,statusCode:response.status,url,responseHeaders,requestBodyValues:{}})}}catch(error){throw handleFetchError({error,url,requestBodyValues:{}})}};function loadOptionalSetting({settingValue,environmentVariableName}){if(typeof settingValue==`string`||!(settingValue!=null||typeof process>`u`)&&(settingValue=process.env[environmentVariableName],!(settingValue==null||typeof settingValue!=`string`)))return settingValue}var suspectProtoRx=/"__proto__"\s*:/,suspectConstructorRx=/"constructor"\s*:/;function _parse(text){let obj=JSON.parse(text);return typeof obj!=`object`||!obj||suspectProtoRx.test(text)===!1&&suspectConstructorRx.test(text)===!1?obj:filter(obj)}function filter(obj){let next=[obj];for(;next.length;){let nodes=next;next=[];for(let node of nodes){if(Object.prototype.hasOwnProperty.call(node,`__proto__`)||Object.prototype.hasOwnProperty.call(node,`constructor`)&&Object.prototype.hasOwnProperty.call(node.constructor,`prototype`))throw SyntaxError(`Object contains forbidden prototype property`);for(let key in node){let value=node[key];value&&typeof value==`object`&&next.push(value)}}}return obj}function secureJsonParse(text){let{stackTraceLimit}=Error;Error.stackTraceLimit=0;try{return _parse(text)}finally{Error.stackTraceLimit=stackTraceLimit}}var validatorSymbol=Symbol.for(`vercel.ai.validator`);function validator$1(validate){return{[validatorSymbol]:!0,validate}}function isValidator(value){return typeof value==`object`&&!!value&&validatorSymbol in value&&value[validatorSymbol]===!0&&`validate`in value}function lazyValidator(createValidator){let validator2;return()=>(validator2??=createValidator(),validator2)}function asValidator(value){return isValidator(value)?value:typeof value==`function`?value():standardSchemaValidator(value)}function standardSchemaValidator(standardSchema){return validator$1(async value=>{let result=await standardSchema[`~standard`].validate(value);return result.issues==null?{success:!0,value:result.value}:{success:!1,error:new TypeValidationError({value,cause:result.issues})}})}async function validateTypes({value,schema}){let result=await safeValidateTypes({value,schema});if(!result.success)throw TypeValidationError.wrap({value,cause:result.error});return result.value}async function safeValidateTypes({value,schema}){let validator2=asValidator(schema);try{if(validator2.validate==null)return{success:!0,value,rawValue:value};let result=await validator2.validate(value);return result.success?{success:!0,value:result.value,rawValue:value}:{success:!1,error:TypeValidationError.wrap({value,cause:result.error}),rawValue:value}}catch(error){return{success:!1,error:TypeValidationError.wrap({value,cause:error}),rawValue:value}}}async function parseJSON({text,schema}){try{let value=secureJsonParse(text);return schema==null?value:validateTypes({value,schema})}catch(error){throw JSONParseError.isInstance(error)||TypeValidationError.isInstance(error)?error:new JSONParseError({text,cause:error})}}async function safeParseJSON({text,schema}){try{let value=secureJsonParse(text);return schema==null?{success:!0,value,rawValue:value}:await safeValidateTypes({value,schema})}catch(error){return{success:!1,error:JSONParseError.isInstance(error)?error:new JSONParseError({text,cause:error}),rawValue:void 0}}}function parseJsonEventStream({stream,schema}){return stream.pipeThrough(new TextDecoderStream).pipeThrough(new EventSourceParserStream).pipeThrough(new TransformStream({async transform({data},controller){data!==`[DONE]`&&controller.enqueue(await safeParseJSON({text:data,schema}))}}))}var getOriginalFetch2=()=>globalThis.fetch,postJsonToApi=async({url,headers,body,failedResponseHandler,successfulResponseHandler,abortSignal,fetch:fetch$1})=>postToApi({url,headers:{"Content-Type":`application/json`,...headers},body:{content:JSON.stringify(body),values:body},failedResponseHandler,successfulResponseHandler,abortSignal,fetch:fetch$1}),postToApi=async({url,headers={},body,successfulResponseHandler,failedResponseHandler,abortSignal,fetch:fetch$1=getOriginalFetch2()})=>{try{let response=await fetch$1(url,{method:`POST`,headers:withUserAgentSuffix(headers,`ai-sdk/provider-utils/${VERSION$2}`,getRuntimeEnvironmentUserAgent()),body:body.content,signal:abortSignal}),responseHeaders=extractResponseHeaders(response);if(!response.ok){let errorInformation;try{errorInformation=await failedResponseHandler({response,url,requestBodyValues:body.values})}catch(error){throw isAbortError(error)||APICallError.isInstance(error)?error:new APICallError({message:`Failed to process error response`,cause:error,statusCode:response.status,url,responseHeaders,requestBodyValues:body.values})}throw errorInformation.value}try{return await successfulResponseHandler({response,url,requestBodyValues:body.values})}catch(error){throw error instanceof Error&&(isAbortError(error)||APICallError.isInstance(error))?error:new APICallError({message:`Failed to process successful response`,cause:error,statusCode:response.status,url,responseHeaders,requestBodyValues:body.values})}}catch(error){throw handleFetchError({error,url,requestBodyValues:body.values})}};async function resolve(value){return typeof value==`function`&&(value=value()),Promise.resolve(value)}var createJsonErrorResponseHandler=({errorSchema,errorToMessage,isRetryable})=>async({response,url,requestBodyValues})=>{let responseBody=await response.text(),responseHeaders=extractResponseHeaders(response);if(responseBody.trim()===``)return{responseHeaders,value:new APICallError({message:response.statusText,url,requestBodyValues,statusCode:response.status,responseHeaders,responseBody,isRetryable:isRetryable?.(response)})};try{let parsedError=await parseJSON({text:responseBody,schema:errorSchema});return{responseHeaders,value:new APICallError({message:errorToMessage(parsedError),url,requestBodyValues,statusCode:response.status,responseHeaders,responseBody,data:parsedError,isRetryable:isRetryable?.(response,parsedError)})}}catch{return{responseHeaders,value:new APICallError({message:response.statusText,url,requestBodyValues,statusCode:response.status,responseHeaders,responseBody,isRetryable:isRetryable?.(response)})}}},createEventSourceResponseHandler=chunkSchema=>async({response})=>{let responseHeaders=extractResponseHeaders(response);if(response.body==null)throw new EmptyResponseBodyError({});return{responseHeaders,value:parseJsonEventStream({stream:response.body,schema:chunkSchema})}},createJsonResponseHandler=responseSchema=>async({response,url,requestBodyValues})=>{let responseBody=await response.text(),parsedResult=await safeParseJSON({text:responseBody,schema:responseSchema}),responseHeaders=extractResponseHeaders(response);if(!parsedResult.success)throw new APICallError({message:`Invalid JSON response`,cause:parsedResult.error,statusCode:response.status,responseHeaders,responseBody,url,requestBodyValues});return{responseHeaders,value:parsedResult.value,rawValue:parsedResult.rawValue}},getRelativePath=(pathA,pathB)=>{let i$1=0;for(;i$1<pathA.length&&i$1<pathB.length&&pathA[i$1]===pathB[i$1];i$1++);return[(pathA.length-i$1).toString(),...pathB.slice(i$1)].join(`/`)},ignoreOverride=Symbol(`Let zodToJsonSchema decide on which parser to use`),defaultOptions={name:void 0,$refStrategy:`root`,basePath:[`#`],effectStrategy:`input`,pipeStrategy:`all`,dateStrategy:`format:date-time`,mapStrategy:`entries`,removeAdditionalStrategy:`passthrough`,allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:`definitions`,strictUnions:!1,definitions:{},errorMessages:!1,patternStrategy:`escape`,applyRegexFlags:!1,emailStrategy:`format:email`,base64Strategy:`contentEncoding:base64`,nameStrategy:`ref`},getDefaultOptions=options=>typeof options==`string`?{...defaultOptions,name:options}:{...defaultOptions,...options};function parseAnyDef(){return{}}function parseArrayDef(def,refs){var _a$2,_b$1,_c;let res={type:`array`};return def.type?._def&&def.type?._def?.typeName!==ZodFirstPartyTypeKind.ZodAny&&(res.items=parseDef(def.type._def,{...refs,currentPath:[...refs.currentPath,`items`]})),def.minLength&&(res.minItems=def.minLength.value),def.maxLength&&(res.maxItems=def.maxLength.value),def.exactLength&&(res.minItems=def.exactLength.value,res.maxItems=def.exactLength.value),res}function parseBigintDef(def){let res={type:`integer`,format:`int64`};if(!def.checks)return res;for(let check of def.checks)switch(check.kind){case`min`:check.inclusive?res.minimum=check.value:res.exclusiveMinimum=check.value;break;case`max`:check.inclusive?res.maximum=check.value:res.exclusiveMaximum=check.value;break;case`multipleOf`:res.multipleOf=check.value;break}return res}function parseBooleanDef(){return{type:`boolean`}}function parseBrandedDef(_def,refs){return parseDef(_def.type._def,refs)}var parseCatchDef=(def,refs)=>parseDef(def.innerType._def,refs);function parseDateDef(def,refs,overrideDateStrategy){let strategy=overrideDateStrategy??refs.dateStrategy;if(Array.isArray(strategy))return{anyOf:strategy.map((item,i$1)=>parseDateDef(def,refs,item))};switch(strategy){case`string`:case`format:date-time`:return{type:`string`,format:`date-time`};case`format:date`:return{type:`string`,format:`date`};case`integer`:return integerDateParser(def)}}var integerDateParser=def=>{let res={type:`integer`,format:`unix-time`};for(let check of def.checks)switch(check.kind){case`min`:res.minimum=check.value;break;case`max`:res.maximum=check.value;break}return res};function parseDefaultDef(_def,refs){return{...parseDef(_def.innerType._def,refs),default:_def.defaultValue()}}function parseEffectsDef(_def,refs){return refs.effectStrategy===`input`?parseDef(_def.schema._def,refs):parseAnyDef()}function parseEnumDef(def){return{type:`string`,enum:Array.from(def.values)}}var isJsonSchema7AllOfType=type=>`type`in type&&type.type===`string`?!1:`allOf`in type;function parseIntersectionDef(def,refs){let allOf=[parseDef(def.left._def,{...refs,currentPath:[...refs.currentPath,`allOf`,`0`]}),parseDef(def.right._def,{...refs,currentPath:[...refs.currentPath,`allOf`,`1`]})].filter(x$1=>!!x$1),mergedAllOf=[];return allOf.forEach(schema=>{if(isJsonSchema7AllOfType(schema))mergedAllOf.push(...schema.allOf);else{let nestedSchema=schema;if(`additionalProperties`in schema&&schema.additionalProperties===!1){let{additionalProperties,...rest}=schema;nestedSchema=rest}mergedAllOf.push(nestedSchema)}}),mergedAllOf.length?{allOf:mergedAllOf}:void 0}function parseLiteralDef(def){let parsedType=typeof def.value;return parsedType!==`bigint`&&parsedType!==`number`&&parsedType!==`boolean`&&parsedType!==`string`?{type:Array.isArray(def.value)?`array`:`object`}:{type:parsedType===`bigint`?`integer`:parsedType,const:def.value}}var emojiRegex=void 0,zodPatterns={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>(emojiRegex===void 0&&(emojiRegex=RegExp(`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`,`u`)),emojiRegex),uuid:/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,ipv4:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv4Cidr:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ipv6Cidr:/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};function parseStringDef(def,refs){let res={type:`string`};if(def.checks)for(let check of def.checks)switch(check.kind){case`min`:res.minLength=typeof res.minLength==`number`?Math.max(res.minLength,check.value):check.value;break;case`max`:res.maxLength=typeof res.maxLength==`number`?Math.min(res.maxLength,check.value):check.value;break;case`email`:switch(refs.emailStrategy){case`format:email`:addFormat(res,`email`,check.message,refs);break;case`format:idn-email`:addFormat(res,`idn-email`,check.message,refs);break;case`pattern:zod`:addPattern(res,zodPatterns.email,check.message,refs);break}break;case`url`:addFormat(res,`uri`,check.message,refs);break;case`uuid`:addFormat(res,`uuid`,check.message,refs);break;case`regex`:addPattern(res,check.regex,check.message,refs);break;case`cuid`:addPattern(res,zodPatterns.cuid,check.message,refs);break;case`cuid2`:addPattern(res,zodPatterns.cuid2,check.message,refs);break;case`startsWith`:addPattern(res,RegExp(`^${escapeLiteralCheckValue(check.value,refs)}`),check.message,refs);break;case`endsWith`:addPattern(res,RegExp(`${escapeLiteralCheckValue(check.value,refs)}$`),check.message,refs);break;case`datetime`:addFormat(res,`date-time`,check.message,refs);break;case`date`:addFormat(res,`date`,check.message,refs);break;case`time`:addFormat(res,`time`,check.message,refs);break;case`duration`:addFormat(res,`duration`,check.message,refs);break;case`length`:res.minLength=typeof res.minLength==`number`?Math.max(res.minLength,check.value):check.value,res.maxLength=typeof res.maxLength==`number`?Math.min(res.maxLength,check.value):check.value;break;case`includes`:addPattern(res,RegExp(escapeLiteralCheckValue(check.value,refs)),check.message,refs);break;case`ip`:check.version!==`v6`&&addFormat(res,`ipv4`,check.message,refs),check.version!==`v4`&&addFormat(res,`ipv6`,check.message,refs);break;case`base64url`:addPattern(res,zodPatterns.base64url,check.message,refs);break;case`jwt`:addPattern(res,zodPatterns.jwt,check.message,refs);break;case`cidr`:check.version!==`v6`&&addPattern(res,zodPatterns.ipv4Cidr,check.message,refs),check.version!==`v4`&&addPattern(res,zodPatterns.ipv6Cidr,check.message,refs);break;case`emoji`:addPattern(res,zodPatterns.emoji(),check.message,refs);break;case`ulid`:addPattern(res,zodPatterns.ulid,check.message,refs);break;case`base64`:switch(refs.base64Strategy){case`format:binary`:addFormat(res,`binary`,check.message,refs);break;case`contentEncoding:base64`:res.contentEncoding=`base64`;break;case`pattern:zod`:addPattern(res,zodPatterns.base64,check.message,refs);break}break;case`nanoid`:addPattern(res,zodPatterns.nanoid,check.message,refs);case`toLowerCase`:case`toUpperCase`:case`trim`:break;default:}return res}function escapeLiteralCheckValue(literal,refs){return refs.patternStrategy===`escape`?escapeNonAlphaNumeric(literal):literal}var ALPHA_NUMERIC=new Set(`ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789`);function escapeNonAlphaNumeric(source){let result=``;for(let i$1=0;i$1<source.length;i$1++)ALPHA_NUMERIC.has(source[i$1])||(result+=`\\`),result+=source[i$1];return result}function addFormat(schema,value,message,refs){var _a$2;schema.format||schema.anyOf?.some(x$1=>x$1.format)?(schema.anyOf||=[],schema.format&&(schema.anyOf.push({format:schema.format}),delete schema.format),schema.anyOf.push({format:value,...message&&refs.errorMessages&&{errorMessage:{format:message}}})):schema.format=value}function addPattern(schema,regex,message,refs){var _a$2;schema.pattern||schema.allOf?.some(x$1=>x$1.pattern)?(schema.allOf||=[],schema.pattern&&(schema.allOf.push({pattern:schema.pattern}),delete schema.pattern),schema.allOf.push({pattern:stringifyRegExpWithFlags(regex,refs),...message&&refs.errorMessages&&{errorMessage:{pattern:message}}})):schema.pattern=stringifyRegExpWithFlags(regex,refs)}function stringifyRegExpWithFlags(regex,refs){var _a$2;if(!refs.applyRegexFlags||!regex.flags)return regex.source;let flags={i:regex.flags.includes(`i`),m:regex.flags.includes(`m`),s:regex.flags.includes(`s`)},source=flags.i?regex.source.toLowerCase():regex.source,pattern=``,isEscaped=!1,inCharGroup=!1,inCharRange=!1;for(let i$1=0;i$1<source.length;i$1++){if(isEscaped){pattern+=source[i$1],isEscaped=!1;continue}if(flags.i){if(inCharGroup){if(source[i$1].match(/[a-z]/)){inCharRange?(pattern+=source[i$1],pattern+=`${source[i$1-2]}-${source[i$1]}`.toUpperCase(),inCharRange=!1):source[i$1+1]===`-`&&source[i$1+2]?.match(/[a-z]/)?(pattern+=source[i$1],inCharRange=!0):pattern+=`${source[i$1]}${source[i$1].toUpperCase()}`;continue}}else if(source[i$1].match(/[a-z]/)){pattern+=`[${source[i$1]}${source[i$1].toUpperCase()}]`;continue}}if(flags.m){if(source[i$1]===`^`){pattern+=`(^|(?<=[\r
|
|
7
|
+
`&&searchIndex++}}return[lines,incompleteLine]}var EventSourceParserStream=class extends TransformStream{constructor({onError,onRetry,onComment}={}){let parser;super({start(controller){parser=createParser({onEvent:event=>{controller.enqueue(event)},onError(error){onError===`terminate`?controller.error(error):typeof onError==`function`&&onError(error)},onRetry,onComment})},transform(chunk){parser.feed(chunk)}})}};function combineHeaders(...headers){return headers.reduce((combinedHeaders,currentHeaders)=>({...combinedHeaders,...currentHeaders??{}}),{})}function extractResponseHeaders(response){return Object.fromEntries([...response.headers])}var generateId=(({prefix,size=16,alphabet=`0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz`,separator=`-`}={})=>{let generator=()=>{let alphabetLength=alphabet.length,chars=Array(size);for(let i$1=0;i$1<size;i$1++)chars[i$1]=alphabet[Math.random()*alphabetLength|0];return chars.join(``)};if(prefix==null)return generator;if(alphabet.includes(separator))throw new InvalidArgumentError({argument:`separator`,message:`The separator "${separator}" must not be part of the alphabet "${alphabet}".`});return()=>`${prefix}${separator}${generator()}`})();function isAbortError(error){return(error instanceof Error||error instanceof DOMException)&&(error.name===`AbortError`||error.name===`ResponseAborted`||error.name===`TimeoutError`)}var FETCH_FAILED_ERROR_MESSAGES=[`fetch failed`,`failed to fetch`];function handleFetchError({error,url,requestBodyValues}){if(isAbortError(error))return error;if(error instanceof TypeError&&FETCH_FAILED_ERROR_MESSAGES.includes(error.message.toLowerCase())){let cause=error.cause;if(cause!=null)return new APICallError({message:`Cannot connect to API: ${cause.message}`,cause,url,requestBodyValues,isRetryable:!0})}return error}function getRuntimeEnvironmentUserAgent(globalThisAny=globalThis){var _a$2,_b$1,_c;return globalThisAny.window?`runtime/browser`:globalThisAny.navigator?.userAgent?`runtime/${globalThisAny.navigator.userAgent.toLowerCase()}`:globalThisAny.process?.versions?.node?`runtime/node.js/${globalThisAny.process.version.substring(0)}`:globalThisAny.EdgeRuntime?`runtime/vercel-edge`:`runtime/unknown`}function normalizeHeaders(headers){if(headers==null)return{};let normalized={};if(headers instanceof Headers)headers.forEach((value,key)=>{normalized[key.toLowerCase()]=value});else{Array.isArray(headers)||(headers=Object.entries(headers));for(let[key,value]of headers)value!=null&&(normalized[key.toLowerCase()]=value)}return normalized}function withUserAgentSuffix(headers,...userAgentSuffixParts){let normalizedHeaders=new Headers(normalizeHeaders(headers)),currentUserAgentHeader=normalizedHeaders.get(`user-agent`)||``;return normalizedHeaders.set(`user-agent`,[currentUserAgentHeader,...userAgentSuffixParts].filter(Boolean).join(` `)),Object.fromEntries(normalizedHeaders.entries())}var VERSION$2=`3.0.17`,getOriginalFetch=()=>globalThis.fetch,getFromApi=async({url,headers={},successfulResponseHandler,failedResponseHandler,abortSignal,fetch:fetch$1=getOriginalFetch()})=>{try{let response=await fetch$1(url,{method:`GET`,headers:withUserAgentSuffix(headers,`ai-sdk/provider-utils/${VERSION$2}`,getRuntimeEnvironmentUserAgent()),signal:abortSignal}),responseHeaders=extractResponseHeaders(response);if(!response.ok){let errorInformation;try{errorInformation=await failedResponseHandler({response,url,requestBodyValues:{}})}catch(error){throw isAbortError(error)||APICallError.isInstance(error)?error:new APICallError({message:`Failed to process error response`,cause:error,statusCode:response.status,url,responseHeaders,requestBodyValues:{}})}throw errorInformation.value}try{return await successfulResponseHandler({response,url,requestBodyValues:{}})}catch(error){throw error instanceof Error&&(isAbortError(error)||APICallError.isInstance(error))?error:new APICallError({message:`Failed to process successful response`,cause:error,statusCode:response.status,url,responseHeaders,requestBodyValues:{}})}}catch(error){throw handleFetchError({error,url,requestBodyValues:{}})}};function loadOptionalSetting({settingValue,environmentVariableName}){if(typeof settingValue==`string`||!(settingValue!=null||typeof process>`u`)&&(settingValue=process.env[environmentVariableName],!(settingValue==null||typeof settingValue!=`string`)))return settingValue}var suspectProtoRx=/"__proto__"\s*:/,suspectConstructorRx=/"constructor"\s*:/;function _parse(text){let obj=JSON.parse(text);return typeof obj!=`object`||!obj||suspectProtoRx.test(text)===!1&&suspectConstructorRx.test(text)===!1?obj:filter(obj)}function filter(obj){let next=[obj];for(;next.length;){let nodes=next;next=[];for(let node of nodes){if(Object.prototype.hasOwnProperty.call(node,`__proto__`)||Object.prototype.hasOwnProperty.call(node,`constructor`)&&Object.prototype.hasOwnProperty.call(node.constructor,`prototype`))throw SyntaxError(`Object contains forbidden prototype property`);for(let key in node){let value=node[key];value&&typeof value==`object`&&next.push(value)}}}return obj}function secureJsonParse(text){let{stackTraceLimit}=Error;try{Error.stackTraceLimit=0}catch{return _parse(text)}try{return _parse(text)}finally{Error.stackTraceLimit=stackTraceLimit}}var validatorSymbol=Symbol.for(`vercel.ai.validator`);function validator$1(validate){return{[validatorSymbol]:!0,validate}}function isValidator(value){return typeof value==`object`&&!!value&&validatorSymbol in value&&value[validatorSymbol]===!0&&`validate`in value}function lazyValidator(createValidator){let validator2;return()=>(validator2??=createValidator(),validator2)}function asValidator(value){return isValidator(value)?value:typeof value==`function`?value():standardSchemaValidator(value)}function standardSchemaValidator(standardSchema){return validator$1(async value=>{let result=await standardSchema[`~standard`].validate(value);return result.issues==null?{success:!0,value:result.value}:{success:!1,error:new TypeValidationError({value,cause:result.issues})}})}async function validateTypes({value,schema}){let result=await safeValidateTypes({value,schema});if(!result.success)throw TypeValidationError.wrap({value,cause:result.error});return result.value}async function safeValidateTypes({value,schema}){let validator2=asValidator(schema);try{if(validator2.validate==null)return{success:!0,value,rawValue:value};let result=await validator2.validate(value);return result.success?{success:!0,value:result.value,rawValue:value}:{success:!1,error:TypeValidationError.wrap({value,cause:result.error}),rawValue:value}}catch(error){return{success:!1,error:TypeValidationError.wrap({value,cause:error}),rawValue:value}}}async function parseJSON({text,schema}){try{let value=secureJsonParse(text);return schema==null?value:validateTypes({value,schema})}catch(error){throw JSONParseError.isInstance(error)||TypeValidationError.isInstance(error)?error:new JSONParseError({text,cause:error})}}async function safeParseJSON({text,schema}){try{let value=secureJsonParse(text);return schema==null?{success:!0,value,rawValue:value}:await safeValidateTypes({value,schema})}catch(error){return{success:!1,error:JSONParseError.isInstance(error)?error:new JSONParseError({text,cause:error}),rawValue:void 0}}}function parseJsonEventStream({stream,schema}){return stream.pipeThrough(new TextDecoderStream).pipeThrough(new EventSourceParserStream).pipeThrough(new TransformStream({async transform({data},controller){data!==`[DONE]`&&controller.enqueue(await safeParseJSON({text:data,schema}))}}))}var getOriginalFetch2=()=>globalThis.fetch,postJsonToApi=async({url,headers,body,failedResponseHandler,successfulResponseHandler,abortSignal,fetch:fetch$1})=>postToApi({url,headers:{"Content-Type":`application/json`,...headers},body:{content:JSON.stringify(body),values:body},failedResponseHandler,successfulResponseHandler,abortSignal,fetch:fetch$1}),postToApi=async({url,headers={},body,successfulResponseHandler,failedResponseHandler,abortSignal,fetch:fetch$1=getOriginalFetch2()})=>{try{let response=await fetch$1(url,{method:`POST`,headers:withUserAgentSuffix(headers,`ai-sdk/provider-utils/${VERSION$2}`,getRuntimeEnvironmentUserAgent()),body:body.content,signal:abortSignal}),responseHeaders=extractResponseHeaders(response);if(!response.ok){let errorInformation;try{errorInformation=await failedResponseHandler({response,url,requestBodyValues:body.values})}catch(error){throw isAbortError(error)||APICallError.isInstance(error)?error:new APICallError({message:`Failed to process error response`,cause:error,statusCode:response.status,url,responseHeaders,requestBodyValues:body.values})}throw errorInformation.value}try{return await successfulResponseHandler({response,url,requestBodyValues:body.values})}catch(error){throw error instanceof Error&&(isAbortError(error)||APICallError.isInstance(error))?error:new APICallError({message:`Failed to process successful response`,cause:error,statusCode:response.status,url,responseHeaders,requestBodyValues:body.values})}}catch(error){throw handleFetchError({error,url,requestBodyValues:body.values})}};async function resolve(value){return typeof value==`function`&&(value=value()),Promise.resolve(value)}var createJsonErrorResponseHandler=({errorSchema,errorToMessage,isRetryable})=>async({response,url,requestBodyValues})=>{let responseBody=await response.text(),responseHeaders=extractResponseHeaders(response);if(responseBody.trim()===``)return{responseHeaders,value:new APICallError({message:response.statusText,url,requestBodyValues,statusCode:response.status,responseHeaders,responseBody,isRetryable:isRetryable?.(response)})};try{let parsedError=await parseJSON({text:responseBody,schema:errorSchema});return{responseHeaders,value:new APICallError({message:errorToMessage(parsedError),url,requestBodyValues,statusCode:response.status,responseHeaders,responseBody,data:parsedError,isRetryable:isRetryable?.(response,parsedError)})}}catch{return{responseHeaders,value:new APICallError({message:response.statusText,url,requestBodyValues,statusCode:response.status,responseHeaders,responseBody,isRetryable:isRetryable?.(response)})}}},createEventSourceResponseHandler=chunkSchema=>async({response})=>{let responseHeaders=extractResponseHeaders(response);if(response.body==null)throw new EmptyResponseBodyError({});return{responseHeaders,value:parseJsonEventStream({stream:response.body,schema:chunkSchema})}},createJsonResponseHandler=responseSchema=>async({response,url,requestBodyValues})=>{let responseBody=await response.text(),parsedResult=await safeParseJSON({text:responseBody,schema:responseSchema}),responseHeaders=extractResponseHeaders(response);if(!parsedResult.success)throw new APICallError({message:`Invalid JSON response`,cause:parsedResult.error,statusCode:response.status,responseHeaders,responseBody,url,requestBodyValues});return{responseHeaders,value:parsedResult.value,rawValue:parsedResult.rawValue}},getRelativePath=(pathA,pathB)=>{let i$1=0;for(;i$1<pathA.length&&i$1<pathB.length&&pathA[i$1]===pathB[i$1];i$1++);return[(pathA.length-i$1).toString(),...pathB.slice(i$1)].join(`/`)},ignoreOverride=Symbol(`Let zodToJsonSchema decide on which parser to use`),defaultOptions={name:void 0,$refStrategy:`root`,basePath:[`#`],effectStrategy:`input`,pipeStrategy:`all`,dateStrategy:`format:date-time`,mapStrategy:`entries`,removeAdditionalStrategy:`passthrough`,allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:`definitions`,strictUnions:!1,definitions:{},errorMessages:!1,patternStrategy:`escape`,applyRegexFlags:!1,emailStrategy:`format:email`,base64Strategy:`contentEncoding:base64`,nameStrategy:`ref`},getDefaultOptions=options=>typeof options==`string`?{...defaultOptions,name:options}:{...defaultOptions,...options};function parseAnyDef(){return{}}function parseArrayDef(def,refs){var _a$2,_b$1,_c;let res={type:`array`};return def.type?._def&&def.type?._def?.typeName!==ZodFirstPartyTypeKind.ZodAny&&(res.items=parseDef(def.type._def,{...refs,currentPath:[...refs.currentPath,`items`]})),def.minLength&&(res.minItems=def.minLength.value),def.maxLength&&(res.maxItems=def.maxLength.value),def.exactLength&&(res.minItems=def.exactLength.value,res.maxItems=def.exactLength.value),res}function parseBigintDef(def){let res={type:`integer`,format:`int64`};if(!def.checks)return res;for(let check of def.checks)switch(check.kind){case`min`:check.inclusive?res.minimum=check.value:res.exclusiveMinimum=check.value;break;case`max`:check.inclusive?res.maximum=check.value:res.exclusiveMaximum=check.value;break;case`multipleOf`:res.multipleOf=check.value;break}return res}function parseBooleanDef(){return{type:`boolean`}}function parseBrandedDef(_def,refs){return parseDef(_def.type._def,refs)}var parseCatchDef=(def,refs)=>parseDef(def.innerType._def,refs);function parseDateDef(def,refs,overrideDateStrategy){let strategy=overrideDateStrategy??refs.dateStrategy;if(Array.isArray(strategy))return{anyOf:strategy.map((item,i$1)=>parseDateDef(def,refs,item))};switch(strategy){case`string`:case`format:date-time`:return{type:`string`,format:`date-time`};case`format:date`:return{type:`string`,format:`date`};case`integer`:return integerDateParser(def)}}var integerDateParser=def=>{let res={type:`integer`,format:`unix-time`};for(let check of def.checks)switch(check.kind){case`min`:res.minimum=check.value;break;case`max`:res.maximum=check.value;break}return res};function parseDefaultDef(_def,refs){return{...parseDef(_def.innerType._def,refs),default:_def.defaultValue()}}function parseEffectsDef(_def,refs){return refs.effectStrategy===`input`?parseDef(_def.schema._def,refs):parseAnyDef()}function parseEnumDef(def){return{type:`string`,enum:Array.from(def.values)}}var isJsonSchema7AllOfType=type=>`type`in type&&type.type===`string`?!1:`allOf`in type;function parseIntersectionDef(def,refs){let allOf=[parseDef(def.left._def,{...refs,currentPath:[...refs.currentPath,`allOf`,`0`]}),parseDef(def.right._def,{...refs,currentPath:[...refs.currentPath,`allOf`,`1`]})].filter(x$1=>!!x$1),mergedAllOf=[];return allOf.forEach(schema=>{if(isJsonSchema7AllOfType(schema))mergedAllOf.push(...schema.allOf);else{let nestedSchema=schema;if(`additionalProperties`in schema&&schema.additionalProperties===!1){let{additionalProperties,...rest}=schema;nestedSchema=rest}mergedAllOf.push(nestedSchema)}}),mergedAllOf.length?{allOf:mergedAllOf}:void 0}function parseLiteralDef(def){let parsedType=typeof def.value;return parsedType!==`bigint`&&parsedType!==`number`&&parsedType!==`boolean`&&parsedType!==`string`?{type:Array.isArray(def.value)?`array`:`object`}:{type:parsedType===`bigint`?`integer`:parsedType,const:def.value}}var emojiRegex=void 0,zodPatterns={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>(emojiRegex===void 0&&(emojiRegex=RegExp(`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`,`u`)),emojiRegex),uuid:/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,ipv4:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv4Cidr:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ipv6Cidr:/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};function parseStringDef(def,refs){let res={type:`string`};if(def.checks)for(let check of def.checks)switch(check.kind){case`min`:res.minLength=typeof res.minLength==`number`?Math.max(res.minLength,check.value):check.value;break;case`max`:res.maxLength=typeof res.maxLength==`number`?Math.min(res.maxLength,check.value):check.value;break;case`email`:switch(refs.emailStrategy){case`format:email`:addFormat(res,`email`,check.message,refs);break;case`format:idn-email`:addFormat(res,`idn-email`,check.message,refs);break;case`pattern:zod`:addPattern(res,zodPatterns.email,check.message,refs);break}break;case`url`:addFormat(res,`uri`,check.message,refs);break;case`uuid`:addFormat(res,`uuid`,check.message,refs);break;case`regex`:addPattern(res,check.regex,check.message,refs);break;case`cuid`:addPattern(res,zodPatterns.cuid,check.message,refs);break;case`cuid2`:addPattern(res,zodPatterns.cuid2,check.message,refs);break;case`startsWith`:addPattern(res,RegExp(`^${escapeLiteralCheckValue(check.value,refs)}`),check.message,refs);break;case`endsWith`:addPattern(res,RegExp(`${escapeLiteralCheckValue(check.value,refs)}$`),check.message,refs);break;case`datetime`:addFormat(res,`date-time`,check.message,refs);break;case`date`:addFormat(res,`date`,check.message,refs);break;case`time`:addFormat(res,`time`,check.message,refs);break;case`duration`:addFormat(res,`duration`,check.message,refs);break;case`length`:res.minLength=typeof res.minLength==`number`?Math.max(res.minLength,check.value):check.value,res.maxLength=typeof res.maxLength==`number`?Math.min(res.maxLength,check.value):check.value;break;case`includes`:addPattern(res,RegExp(escapeLiteralCheckValue(check.value,refs)),check.message,refs);break;case`ip`:check.version!==`v6`&&addFormat(res,`ipv4`,check.message,refs),check.version!==`v4`&&addFormat(res,`ipv6`,check.message,refs);break;case`base64url`:addPattern(res,zodPatterns.base64url,check.message,refs);break;case`jwt`:addPattern(res,zodPatterns.jwt,check.message,refs);break;case`cidr`:check.version!==`v6`&&addPattern(res,zodPatterns.ipv4Cidr,check.message,refs),check.version!==`v4`&&addPattern(res,zodPatterns.ipv6Cidr,check.message,refs);break;case`emoji`:addPattern(res,zodPatterns.emoji(),check.message,refs);break;case`ulid`:addPattern(res,zodPatterns.ulid,check.message,refs);break;case`base64`:switch(refs.base64Strategy){case`format:binary`:addFormat(res,`binary`,check.message,refs);break;case`contentEncoding:base64`:res.contentEncoding=`base64`;break;case`pattern:zod`:addPattern(res,zodPatterns.base64,check.message,refs);break}break;case`nanoid`:addPattern(res,zodPatterns.nanoid,check.message,refs);case`toLowerCase`:case`toUpperCase`:case`trim`:break;default:}return res}function escapeLiteralCheckValue(literal,refs){return refs.patternStrategy===`escape`?escapeNonAlphaNumeric(literal):literal}var ALPHA_NUMERIC=new Set(`ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789`);function escapeNonAlphaNumeric(source){let result=``;for(let i$1=0;i$1<source.length;i$1++)ALPHA_NUMERIC.has(source[i$1])||(result+=`\\`),result+=source[i$1];return result}function addFormat(schema,value,message,refs){var _a$2;schema.format||schema.anyOf?.some(x$1=>x$1.format)?(schema.anyOf||=[],schema.format&&(schema.anyOf.push({format:schema.format}),delete schema.format),schema.anyOf.push({format:value,...message&&refs.errorMessages&&{errorMessage:{format:message}}})):schema.format=value}function addPattern(schema,regex,message,refs){var _a$2;schema.pattern||schema.allOf?.some(x$1=>x$1.pattern)?(schema.allOf||=[],schema.pattern&&(schema.allOf.push({pattern:schema.pattern}),delete schema.pattern),schema.allOf.push({pattern:stringifyRegExpWithFlags(regex,refs),...message&&refs.errorMessages&&{errorMessage:{pattern:message}}})):schema.pattern=stringifyRegExpWithFlags(regex,refs)}function stringifyRegExpWithFlags(regex,refs){var _a$2;if(!refs.applyRegexFlags||!regex.flags)return regex.source;let flags={i:regex.flags.includes(`i`),m:regex.flags.includes(`m`),s:regex.flags.includes(`s`)},source=flags.i?regex.source.toLowerCase():regex.source,pattern=``,isEscaped=!1,inCharGroup=!1,inCharRange=!1;for(let i$1=0;i$1<source.length;i$1++){if(isEscaped){pattern+=source[i$1],isEscaped=!1;continue}if(flags.i){if(inCharGroup){if(source[i$1].match(/[a-z]/)){inCharRange?(pattern+=source[i$1],pattern+=`${source[i$1-2]}-${source[i$1]}`.toUpperCase(),inCharRange=!1):source[i$1+1]===`-`&&source[i$1+2]?.match(/[a-z]/)?(pattern+=source[i$1],inCharRange=!0):pattern+=`${source[i$1]}${source[i$1].toUpperCase()}`;continue}}else if(source[i$1].match(/[a-z]/)){pattern+=`[${source[i$1]}${source[i$1].toUpperCase()}]`;continue}}if(flags.m){if(source[i$1]===`^`){pattern+=`(^|(?<=[\r
|
|
8
8
|
]))`;continue}else if(source[i$1]===`$`){pattern+=`($|(?=[\r
|
|
9
9
|
]))`;continue}}if(flags.s&&source[i$1]===`.`){pattern+=inCharGroup?`${source[i$1]}\r
|
|
10
10
|
`:`[${source[i$1]}\r
|
|
@@ -24,7 +24,7 @@ Create an API key: https://vercel.com/d?to=%2F%5Bteam%5D%2F%7E%2Fai%2Fapi-keys
|
|
|
24
24
|
Provide via 'apiKey' option or 'AI_GATEWAY_API_KEY' environment variable.
|
|
25
25
|
|
|
26
26
|
Option 2 - OIDC token:
|
|
27
|
-
Run 'npx vercel link' to link your project, then 'vc env pull' to fetch the token.`,new _GatewayAuthenticationError({message:contextualMessage,statusCode,cause})}},name2=`GatewayInvalidRequestError`,marker3=`vercel.ai.gateway.error.${name2}`,symbol3=Symbol.for(marker3),_a3,_b3,GatewayInvalidRequestError=class extends (_b3=GatewayError,_a3=symbol3,_b3){constructor({message=`Invalid request`,statusCode=400,cause}={}){super({message,statusCode,cause}),this[_a3]=!0,this.name=name2,this.type=`invalid_request_error`}static isInstance(error){return GatewayError.hasMarker(error)&&symbol3 in error}},name3=`GatewayRateLimitError`,marker4=`vercel.ai.gateway.error.${name3}`,symbol4=Symbol.for(marker4),_a4,_b4,GatewayRateLimitError=class extends (_b4=GatewayError,_a4=symbol4,_b4){constructor({message=`Rate limit exceeded`,statusCode=429,cause}={}){super({message,statusCode,cause}),this[_a4]=!0,this.name=name3,this.type=`rate_limit_exceeded`}static isInstance(error){return GatewayError.hasMarker(error)&&symbol4 in error}},name4=`GatewayModelNotFoundError`,marker5=`vercel.ai.gateway.error.${name4}`,symbol5=Symbol.for(marker5),modelNotFoundParamSchema=lazyValidator(()=>zodSchema(z.object({modelId:z.string()}))),_a5,_b5,GatewayModelNotFoundError=class extends (_b5=GatewayError,_a5=symbol5,_b5){constructor({message=`Model not found`,statusCode=404,modelId,cause}={}){super({message,statusCode,cause}),this[_a5]=!0,this.name=name4,this.type=`model_not_found`,this.modelId=modelId}static isInstance(error){return GatewayError.hasMarker(error)&&symbol5 in error}},name5=`GatewayInternalServerError`,marker6=`vercel.ai.gateway.error.${name5}`,symbol6=Symbol.for(marker6),_a6,_b6,GatewayInternalServerError=class extends (_b6=GatewayError,_a6=symbol6,_b6){constructor({message=`Internal server error`,statusCode=500,cause}={}){super({message,statusCode,cause}),this[_a6]=!0,this.name=name5,this.type=`internal_server_error`}static isInstance(error){return GatewayError.hasMarker(error)&&symbol6 in error}},name6=`GatewayResponseError`,marker7=`vercel.ai.gateway.error.${name6}`,symbol7=Symbol.for(marker7),_a7,_b7,GatewayResponseError=class extends (_b7=GatewayError,_a7=symbol7,_b7){constructor({message=`Invalid response from Gateway`,statusCode=502,response,validationError,cause}={}){super({message,statusCode,cause}),this[_a7]=!0,this.name=name6,this.type=`response_error`,this.response=response,this.validationError=validationError}static isInstance(error){return GatewayError.hasMarker(error)&&symbol7 in error}};async function createGatewayErrorFromResponse({response,statusCode,defaultMessage=`Gateway request failed`,cause,authMethod}){let parseResult=await safeValidateTypes({value:response,schema:gatewayErrorResponseSchema});if(!parseResult.success)return new GatewayResponseError({message:`Invalid error response format: ${defaultMessage}`,statusCode,response,validationError:parseResult.error,cause});let validatedResponse=parseResult.value,errorType=validatedResponse.error.type,message=validatedResponse.error.message;switch(errorType){case`authentication_error`:return GatewayAuthenticationError.createContextualError({apiKeyProvided:authMethod===`api-key`,oidcTokenProvided:authMethod===`oidc`,statusCode,cause});case`invalid_request_error`:return new GatewayInvalidRequestError({message,statusCode,cause});case`rate_limit_exceeded`:return new GatewayRateLimitError({message,statusCode,cause});case`model_not_found`:{let modelResult=await safeValidateTypes({value:validatedResponse.error.param,schema:modelNotFoundParamSchema});return new GatewayModelNotFoundError({message,statusCode,modelId:modelResult.success?modelResult.value.modelId:void 0,cause})}case`internal_server_error`:return new GatewayInternalServerError({message,statusCode,cause});default:return new GatewayInternalServerError({message,statusCode,cause})}}var gatewayErrorResponseSchema=lazyValidator(()=>zodSchema(z.object({error:z.object({message:z.string(),type:z.string().nullish(),param:z.unknown().nullish(),code:z.union([z.string(),z.number()]).nullish()})})));function asGatewayError(error,authMethod){var _a8$1;return GatewayError.isInstance(error)?error:APICallError.isInstance(error)?createGatewayErrorFromResponse({response:extractApiCallResponse(error),statusCode:error.statusCode??500,defaultMessage:`Gateway request failed`,cause:error,authMethod}):createGatewayErrorFromResponse({response:{},statusCode:500,defaultMessage:error instanceof Error?`Gateway request failed: ${error.message}`:`Unknown Gateway error`,cause:error,authMethod})}function extractApiCallResponse(error){if(error.data!==void 0)return error.data;if(error.responseBody!=null)try{return JSON.parse(error.responseBody)}catch{return error.responseBody}return{}}var GATEWAY_AUTH_METHOD_HEADER=`ai-gateway-auth-method`;async function parseAuthMethod(headers){let result=await safeValidateTypes({value:headers[GATEWAY_AUTH_METHOD_HEADER],schema:gatewayAuthMethodSchema});return result.success?result.value:void 0}var gatewayAuthMethodSchema=lazyValidator(()=>zodSchema(z.union([z.literal(`api-key`),z.literal(`oidc`)]))),GatewayFetchMetadata=class{constructor(config){this.config=config}async getAvailableModels(){try{let{value}=await getFromApi({url:`${this.config.baseURL}/config`,headers:await resolve(this.config.headers()),successfulResponseHandler:createJsonResponseHandler(gatewayAvailableModelsResponseSchema),failedResponseHandler:createJsonErrorResponseHandler({errorSchema:z.any(),errorToMessage:data=>data}),fetch:this.config.fetch});return value}catch(error){throw await asGatewayError(error)}}async getCredits(){try{let baseUrl=new URL(this.config.baseURL),{value}=await getFromApi({url:`${baseUrl.origin}/v1/credits`,headers:await resolve(this.config.headers()),successfulResponseHandler:createJsonResponseHandler(gatewayCreditsResponseSchema),failedResponseHandler:createJsonErrorResponseHandler({errorSchema:z.any(),errorToMessage:data=>data}),fetch:this.config.fetch});return value}catch(error){throw await asGatewayError(error)}}},gatewayAvailableModelsResponseSchema=lazyValidator(()=>zodSchema(z.object({models:z.array(z.object({id:z.string(),name:z.string(),description:z.string().nullish(),pricing:z.object({input:z.string(),output:z.string(),input_cache_read:z.string().nullish(),input_cache_write:z.string().nullish()}).transform(({input,output,input_cache_read,input_cache_write})=>({input,output,...input_cache_read?{cachedInputTokens:input_cache_read}:{},...input_cache_write?{cacheCreationInputTokens:input_cache_write}:{}})).nullish(),specification:z.object({specificationVersion:z.literal(`v2`),provider:z.string(),modelId:z.string()}),modelType:z.enum([`language`,`embedding`,`image`]).nullish()}))}))),gatewayCreditsResponseSchema=lazyValidator(()=>zodSchema(z.object({balance:z.string(),total_used:z.string()}).transform(({balance,total_used})=>({balance,totalUsed:total_used})))),GatewayLanguageModel=class{constructor(modelId,config){this.modelId=modelId,this.config=config,this.specificationVersion=`v2`,this.supportedUrls={"*/*":[/.*/]}}get provider(){return this.config.provider}async getArgs(options){let{abortSignal:_abortSignal,...optionsWithoutSignal}=options;return{args:this.maybeEncodeFileParts(optionsWithoutSignal),warnings:[]}}async doGenerate(options){let{args,warnings}=await this.getArgs(options),{abortSignal}=options,resolvedHeaders=await resolve(this.config.headers());try{let{responseHeaders,value:responseBody,rawValue:rawResponse}=await postJsonToApi({url:this.getUrl(),headers:combineHeaders(resolvedHeaders,options.headers,this.getModelConfigHeaders(this.modelId,!1),await resolve(this.config.o11yHeaders)),body:args,successfulResponseHandler:createJsonResponseHandler(z.any()),failedResponseHandler:createJsonErrorResponseHandler({errorSchema:z.any(),errorToMessage:data=>data}),...abortSignal&&{abortSignal},fetch:this.config.fetch});return{...responseBody,request:{body:args},response:{headers:responseHeaders,body:rawResponse},warnings}}catch(error){throw await asGatewayError(error,await parseAuthMethod(resolvedHeaders))}}async doStream(options){let{args,warnings}=await this.getArgs(options),{abortSignal}=options,resolvedHeaders=await resolve(this.config.headers());try{let{value:response,responseHeaders}=await postJsonToApi({url:this.getUrl(),headers:combineHeaders(resolvedHeaders,options.headers,this.getModelConfigHeaders(this.modelId,!0),await resolve(this.config.o11yHeaders)),body:args,successfulResponseHandler:createEventSourceResponseHandler(z.any()),failedResponseHandler:createJsonErrorResponseHandler({errorSchema:z.any(),errorToMessage:data=>data}),...abortSignal&&{abortSignal},fetch:this.config.fetch});return{stream:response.pipeThrough(new TransformStream({start(controller){warnings.length>0&&controller.enqueue({type:`stream-start`,warnings})},transform(chunk,controller){if(chunk.success){let streamPart=chunk.value;if(streamPart.type===`raw`&&!options.includeRawChunks)return;streamPart.type===`response-metadata`&&streamPart.timestamp&&typeof streamPart.timestamp==`string`&&(streamPart.timestamp=new Date(streamPart.timestamp)),controller.enqueue(streamPart)}else controller.error(chunk.error)}})),request:{body:args},response:{headers:responseHeaders}}}catch(error){throw await asGatewayError(error,await parseAuthMethod(resolvedHeaders))}}isFilePart(part){return part&&typeof part==`object`&&`type`in part&&part.type===`file`}maybeEncodeFileParts(options){for(let message of options.prompt)for(let part of message.content)if(this.isFilePart(part)){let filePart=part;if(filePart.data instanceof Uint8Array){let buffer=Uint8Array.from(filePart.data),base64Data=Buffer.from(buffer).toString(`base64`);filePart.data=new URL(`data:${filePart.mediaType||`application/octet-stream`};base64,${base64Data}`)}}return options}getUrl(){return`${this.config.baseURL}/language-model`}getModelConfigHeaders(modelId,streaming){return{"ai-language-model-specification-version":`2`,"ai-language-model-id":modelId,"ai-language-model-streaming":String(streaming)}}},GatewayEmbeddingModel=class{constructor(modelId,config){this.modelId=modelId,this.config=config,this.specificationVersion=`v2`,this.maxEmbeddingsPerCall=2048,this.supportsParallelCalls=!0}get provider(){return this.config.provider}async doEmbed({values,headers,abortSignal,providerOptions}){var _a8$1;let resolvedHeaders=await resolve(this.config.headers());try{let{responseHeaders,value:responseBody,rawValue}=await postJsonToApi({url:this.getUrl(),headers:combineHeaders(resolvedHeaders,headers??{},this.getModelConfigHeaders(),await resolve(this.config.o11yHeaders)),body:{input:values.length===1?values[0]:values,...providerOptions?{providerOptions}:{}},successfulResponseHandler:createJsonResponseHandler(gatewayEmbeddingResponseSchema),failedResponseHandler:createJsonErrorResponseHandler({errorSchema:z.any(),errorToMessage:data=>data}),...abortSignal&&{abortSignal},fetch:this.config.fetch});return{embeddings:responseBody.embeddings,usage:responseBody.usage??void 0,providerMetadata:responseBody.providerMetadata,response:{headers:responseHeaders,body:rawValue}}}catch(error){throw await asGatewayError(error,await parseAuthMethod(resolvedHeaders))}}getUrl(){return`${this.config.baseURL}/embedding-model`}getModelConfigHeaders(){return{"ai-embedding-model-specification-version":`2`,"ai-model-id":this.modelId}}},gatewayEmbeddingResponseSchema=lazyValidator(()=>zodSchema(z.object({embeddings:z.array(z.array(z.number())),usage:z.object({tokens:z.number()}).nullish(),providerMetadata:z.record(z.string(),z.record(z.string(),z.unknown())).optional()})));async function getVercelRequestId(){var _a8$1;return(0,import_dist.getContext)().headers?.[`x-vercel-id`]}var VERSION$1=`2.0.0`,AI_GATEWAY_PROTOCOL_VERSION=`0.0.1`;function createGatewayProvider(options={}){var _a8$1,_b8;let pendingMetadata=null,metadataCache=null,cacheRefreshMillis=options.metadataCacheRefreshMillis??1e3*60*5,lastFetchTime=0,baseURL=withoutTrailingSlash(options.baseURL)??`https://ai-gateway.vercel.sh/v1/ai`,getHeaders=async()=>{let auth=await getGatewayAuthToken(options);if(auth)return withUserAgentSuffix({Authorization:`Bearer ${auth.token}`,"ai-gateway-protocol-version":AI_GATEWAY_PROTOCOL_VERSION,[GATEWAY_AUTH_METHOD_HEADER]:auth.authMethod,...options.headers},`ai-sdk/gateway/${VERSION$1}`);throw GatewayAuthenticationError.createContextualError({apiKeyProvided:!1,oidcTokenProvided:!1,statusCode:401})},createO11yHeaders=()=>{let deploymentId=loadOptionalSetting({settingValue:void 0,environmentVariableName:`VERCEL_DEPLOYMENT_ID`}),environment=loadOptionalSetting({settingValue:void 0,environmentVariableName:`VERCEL_ENV`}),region=loadOptionalSetting({settingValue:void 0,environmentVariableName:`VERCEL_REGION`});return async()=>{let requestId=await getVercelRequestId();return{...deploymentId&&{"ai-o11y-deployment-id":deploymentId},...environment&&{"ai-o11y-environment":environment},...region&&{"ai-o11y-region":region},...requestId&&{"ai-o11y-request-id":requestId}}}},createLanguageModel=modelId=>new GatewayLanguageModel(modelId,{provider:`gateway`,baseURL,headers:getHeaders,fetch:options.fetch,o11yHeaders:createO11yHeaders()}),getAvailableModels=async()=>{var _a9$1,_b9,_c;let now=((_a9$1=options._internal)?.currentDate)?.call(_a9$1).getTime()??Date.now();return(!pendingMetadata||now-lastFetchTime>cacheRefreshMillis)&&(lastFetchTime=now,pendingMetadata=new GatewayFetchMetadata({baseURL,headers:getHeaders,fetch:options.fetch}).getAvailableModels().then(metadata=>(metadataCache=metadata,metadata)).catch(async error=>{throw await asGatewayError(error,await parseAuthMethod(await getHeaders()))})),metadataCache?Promise.resolve(metadataCache):pendingMetadata},getCredits=async()=>new GatewayFetchMetadata({baseURL,headers:getHeaders,fetch:options.fetch}).getCredits().catch(async error=>{throw await asGatewayError(error,await parseAuthMethod(await getHeaders()))}),provider=function(modelId){if(new.target)throw Error(`The Gateway Provider model function cannot be called with the new keyword.`);return createLanguageModel(modelId)};return provider.getAvailableModels=getAvailableModels,provider.getCredits=getCredits,provider.imageModel=modelId=>{throw new NoSuchModelError({modelId,modelType:`imageModel`})},provider.languageModel=createLanguageModel,provider.textEmbeddingModel=modelId=>new GatewayEmbeddingModel(modelId,{provider:`gateway`,baseURL,headers:getHeaders,fetch:options.fetch,o11yHeaders:createO11yHeaders()}),provider}var gateway=createGatewayProvider();async function getGatewayAuthToken(options){let apiKey=loadOptionalSetting({settingValue:options.apiKey,environmentVariableName:`AI_GATEWAY_API_KEY`});if(apiKey)return{token:apiKey,authMethod:`api-key`};try{return{token:await(0,import_dist$1.getVercelOidcToken)(),authMethod:`oidc`}}catch{return null}}function isPromise(value){return value?.then!=null}function isActualPromise(value){let maybePromise=value;return maybePromise&&maybePromise.then&&maybePromise.catch&&maybePromise.finally}function handleMaybePromise(inputFactory,outputSuccessFactory,outputErrorFactory,finallyFactory){let result$=fakePromise().then(inputFactory).then(outputSuccessFactory,outputErrorFactory);return finallyFactory&&(result$=result$.finally(finallyFactory)),unfakePromise(result$)}function fakePromise(value){return value&&isActualPromise(value)?value:isPromise(value)?{then:(resolve$1,reject)=>fakePromise(value.then(resolve$1,reject)),catch:reject=>fakePromise(value.then(res=>res,reject)),finally:cb=>fakePromise(cb?promiseLikeFinally(value,cb):value),[Symbol.toStringTag]:`Promise`}:{then(resolve$1){if(resolve$1)try{return fakePromise(resolve$1(value))}catch(err){return fakeRejectPromise(err)}return this},catch(){return this},finally(cb){if(cb)try{return fakePromise(cb()).then(()=>value,()=>value)}catch(err){return fakeRejectPromise(err)}return this},[Symbol.toStringTag]:`Promise`,__fakePromiseValue:value,[kFakePromise]:`resolved`}}function createDeferredPromise(){if(Promise.withResolvers)return Promise.withResolvers();let resolveFn,rejectFn;return{promise:new Promise(function(resolve$1,reject){resolveFn=resolve$1,rejectFn=reject}),get resolve(){return resolveFn},get reject(){return rejectFn}}}function iterateAsync(iterable,callback,results){if(iterable?.length===0)return;let iterator=iterable[Symbol.iterator](),index=0;function iterate(){let{done:endOfIterator,value}=iterator.next();if(endOfIterator)return;let endedEarly=!1;function endEarly(){endedEarly=!0}return handleMaybePromise(function(){return callback(value,endEarly,index++)},function(result){if(result&&results?.push(result),!endedEarly)return iterate()})}return iterate()}function fakeRejectPromise(error){return{then(_resolve,reject){if(reject)try{return fakePromise(reject(error))}catch(err){return fakeRejectPromise(err)}return this},catch(reject){if(reject)try{return fakePromise(reject(error))}catch(err){return fakeRejectPromise(err)}return this},finally(cb){if(cb)try{cb()}catch(err){return fakeRejectPromise(err)}return this},__fakeRejectError:error,[Symbol.toStringTag]:`Promise`,[kFakePromise]:`rejected`}}function isFakePromise(value){return value?.[kFakePromise]===`resolved`}function isFakeRejectPromise(value){return value?.[kFakePromise]===`rejected`}function promiseLikeFinally(value,onFinally){return`finally`in value?value.finally(onFinally):value.then(res=>{let finallyRes=onFinally();return isPromise(finallyRes)?finallyRes.then(()=>res):res},err=>{let finallyRes=onFinally();if(isPromise(finallyRes))return finallyRes.then(()=>{throw err});throw err})}function unfakePromise(promise){if(isFakePromise(promise))return promise.__fakePromiseValue;if(isFakeRejectPromise(promise))throw promise.__fakeRejectError;return promise}var kFakePromise,init_esm$4=__esmMin((()=>{kFakePromise=Symbol.for(`@whatwg-node/promise-helpers/FakePromise`)}));init_esm$4();function chain(first,next){let merged={...next,...first};for(let key of Object.keys(merged))key in first&&key in next&&(merged[key]=(payload,wrapped)=>first[key](payload,()=>next[key](payload,wrapped)));return merged}const getInstrumented=payload=>({fn(instrument,wrapped){return instrument?(...args)=>{let result;return instrument(payload,()=>{result=wrapped(...args)}),result}:wrapped},asyncFn(instrument,wrapped){return instrument?(...args)=>{let result;return handleMaybePromise(()=>instrument(payload,()=>(result=wrapped(...args),isPromise(result)?result.then(()=>void 0):void 0)),()=>result)}:wrapped}});var PonyfillSuppressedError,init_SupressedError=__esmMin((()=>{PonyfillSuppressedError=class extends Error{error;suppressed;constructor(error,suppressed,message){super(message),this.error=error,this.suppressed=suppressed,this.name=`SuppressedError`,Error.captureStackTrace(this,this.constructor)}}})),DisposableSymbols,init_symbols=__esmMin((()=>{DisposableSymbols={get dispose(){return Symbol.dispose||Symbol.for(`dispose`)},get asyncDispose(){return Symbol.asyncDispose||Symbol.for(`asyncDispose`)}}}));function isSyncDisposable(obj){return obj?.[DisposableSymbols.dispose]!=null}function isAsyncDisposable(obj){return obj?.[DisposableSymbols.asyncDispose]!=null}var init_utils$2=__esmMin((()=>{init_symbols()})),SuppressedError$2,PonyfillAsyncDisposableStack,init_AsyncDisposableStack=__esmMin((()=>{init_esm$4(),init_SupressedError(),init_symbols(),init_utils$2(),SuppressedError$2=globalThis.SuppressedError||PonyfillSuppressedError,PonyfillAsyncDisposableStack=class PonyfillAsyncDisposableStack{callbacks=[];get disposed(){return this.callbacks.length===0}use(value){return isAsyncDisposable(value)?this.callbacks.push(()=>value[DisposableSymbols.asyncDispose]()):isSyncDisposable(value)&&this.callbacks.push(()=>value[DisposableSymbols.dispose]()),value}adopt(value,onDisposeAsync){return onDisposeAsync&&this.callbacks.push(()=>onDisposeAsync(value)),value}defer(onDisposeAsync){onDisposeAsync&&this.callbacks.push(onDisposeAsync)}move(){let stack=new PonyfillAsyncDisposableStack;return stack.callbacks=this.callbacks,this.callbacks=[],stack}disposeAsync(){return this[DisposableSymbols.asyncDispose]()}_error;_iterateCallbacks(){let cb=this.callbacks.pop();if(cb)return handleMaybePromise(cb,()=>this._iterateCallbacks(),error=>(this._error=this._error?new SuppressedError$2(error,this._error):error,this._iterateCallbacks()))}[DisposableSymbols.asyncDispose](){let res$=this._iterateCallbacks();if(res$?.then)return res$.then(()=>{if(this._error){let error=this._error;throw this._error=void 0,error}});if(this._error){let error=this._error;throw this._error=void 0,error}}[Symbol.toStringTag]=`AsyncDisposableStack`}})),SuppressedError$1,PonyfillDisposableStack,init_DisposableStack=__esmMin((()=>{init_SupressedError(),init_symbols(),init_utils$2(),globalThis.SuppressedError,DisposableSymbols.dispose,Symbol.toStringTag})),DisposableStack,AsyncDisposableStack,SuppressedError,init_esm$3=__esmMin((()=>{init_AsyncDisposableStack(),init_DisposableStack(),init_SupressedError(),init_symbols(),globalThis.DisposableStack,AsyncDisposableStack=globalThis.AsyncDisposableStack||PonyfillAsyncDisposableStack,globalThis.SuppressedError})),require_shouldSkipPonyfill=__commonJSMin(((exports,module)=>{function isNextJs(){return Object.keys(globalThis).some(key=>key.startsWith(`__NEXT`))}module.exports=function(){return!!(globalThis.Deno||globalThis.Bun||isNextJs())}}));function Oe(e,t){return(t?/^[\x00-\xFF]*$/:/^[\x00-\x7F]*$/).test(e)}function D(e,t=!1){let r=[],n=0;for(;n<e.length;){let c=e[n],l=a(function(f){if(!t)throw TypeError(f);r.push({type:`INVALID_CHAR`,index:n,value:e[n++]})},`ErrorOrInvalid`);if(c===`*`){r.push({type:`ASTERISK`,index:n,value:e[n++]});continue}if(c===`+`||c===`?`){r.push({type:`OTHER_MODIFIER`,index:n,value:e[n++]});continue}if(c===`\\`){r.push({type:`ESCAPED_CHAR`,index:n++,value:e[n++]});continue}if(c===`{`){r.push({type:`OPEN`,index:n,value:e[n++]});continue}if(c===`}`){r.push({type:`CLOSE`,index:n,value:e[n++]});continue}if(c===`:`){let f=``,s$1=n+1;for(;s$1<e.length;){let i$1=e.substr(s$1,1);if(s$1===n+1&&Re.test(i$1)||s$1!==n+1&&Ee.test(i$1)){f+=e[s$1++];continue}break}if(!f){l(`Missing parameter name at ${n}`);continue}r.push({type:`NAME`,index:n,value:f}),n=s$1;continue}if(c===`(`){let f=1,s$1=``,i$1=n+1,o=!1;if(e[i$1]===`?`){l(`Pattern cannot start with "?" at ${i$1}`);continue}for(;i$1<e.length;){if(!Oe(e[i$1],!1)){l(`Invalid character '${e[i$1]}' at ${i$1}.`),o=!0;break}if(e[i$1]===`\\`){s$1+=e[i$1++]+e[i$1++];continue}if(e[i$1]===`)`){if(f--,f===0){i$1++;break}}else if(e[i$1]===`(`&&(f++,e[i$1+1]!==`?`)){l(`Capturing groups are not allowed at ${i$1}`),o=!0;break}s$1+=e[i$1++]}if(o)continue;if(f){l(`Unbalanced pattern at ${n}`);continue}if(!s$1){l(`Missing pattern at ${n}`);continue}r.push({type:`REGEX`,index:n,value:s$1}),n=i$1;continue}r.push({type:`CHAR`,index:n,value:e[n++]})}return r.push({type:`END`,index:n,value:``}),r}function F(e,t={}){let r=D(e);t.delimiter??=`/#?`,t.prefixes??=`./`;let n=`[^${x(t.delimiter)}]+?`,c=[],l=0,f=0,i$1=new Set,o=a(u=>{if(f<r.length&&r[f].type===u)return r[f++].value},`tryConsume`),h$1=a(()=>o(`OTHER_MODIFIER`)??o(`ASTERISK`),`tryConsumeModifier`),p=a(u=>{let d$1=o(u);if(d$1!==void 0)return d$1;let{type:g,index:y$1}=r[f];throw TypeError(`Unexpected ${g} at ${y$1}, expected ${u}`)},`mustConsume`),A=a(()=>{let u=``,d$1;for(;d$1=o(`CHAR`)??o(`ESCAPED_CHAR`);)u+=d$1;return u},`consumeText`),xe=a(u=>u,`DefaultEncodePart`),N=t.encodePart||xe,H=``,$=a(u=>{H+=u},`appendToPendingFixedValue`),M=a(()=>{H.length&&(c.push(new P(3,``,``,N(H),``,3)),H=``)},`maybeAddPartFromPendingFixedValue`),X=a((u,d$1,g,y$1,Z)=>{let m$1=3;switch(Z){case`?`:m$1=1;break;case`*`:m$1=0;break;case`+`:m$1=2;break}if(!d$1&&!g&&m$1===3){$(u);return}if(M(),!d$1&&!g){if(!u)return;c.push(new P(3,``,``,N(u),``,m$1));return}let S;S=g?g===`*`?v:g:n;let k=2;S===n?(k=1,S=``):S===v&&(k=0,S=``);let E;if(d$1?E=d$1:g&&(E=l++),i$1.has(E))throw TypeError(`Duplicate name '${E}'.`);i$1.add(E),c.push(new P(k,E,N(u),S,N(y$1),m$1))},`addPart`);for(;f<r.length;){let u=o(`CHAR`),d$1=o(`NAME`),g=o(`REGEX`);if(!d$1&&!g&&(g=o(`ASTERISK`)),d$1||g){let m$1=u??``;t.prefixes.indexOf(m$1)===-1&&($(m$1),m$1=``),M();let S=h$1();X(m$1,d$1,g,``,S);continue}let y$1=u??o(`ESCAPED_CHAR`);if(y$1){$(y$1);continue}if(o(`OPEN`)){let m$1=A(),S=o(`NAME`),k=o(`REGEX`);!S&&!k&&(k=o(`ASTERISK`));let E=A();p(`CLOSE`);let be=h$1();X(m$1,S,k,E,be);continue}M(),p(`END`)}return c}function x(e){return e.replace(/([.+*?^${}()[\]|/\\])/g,`\\$1`)}function B(e){return e&&e.ignoreCase?`ui`:`u`}function q(e,t,r){return W(F(e,r),t,r)}function T(e){switch(e){case 0:return`*`;case 1:return`?`;case 2:return`+`;case 3:return``}}function W(e,t,r={}){r.delimiter??=`/#?`,r.prefixes??=`./`,r.sensitive??=!1,r.strict??=!1,r.end??=!0,r.start??=!0,r.endsWith=``;let n=r.start?`^`:``;for(let s$1 of e){if(s$1.type===3){s$1.modifier===3?n+=x(s$1.value):n+=`(?:${x(s$1.value)})${T(s$1.modifier)}`;continue}t&&t.push(s$1.name);let i$1=`[^${x(r.delimiter)}]+?`,o=s$1.value;if(s$1.type===1?o=i$1:s$1.type===0&&(o=v),!s$1.prefix.length&&!s$1.suffix.length){s$1.modifier===3||s$1.modifier===1?n+=`(${o})${T(s$1.modifier)}`:n+=`((?:${o})${T(s$1.modifier)})`;continue}if(s$1.modifier===3||s$1.modifier===1){n+=`(?:${x(s$1.prefix)}(${o})${x(s$1.suffix)})`,n+=T(s$1.modifier);continue}n+=`(?:${x(s$1.prefix)}`,n+=`((?:${o})(?:`,n+=x(s$1.suffix),n+=x(s$1.prefix),n+=`(?:${o}))*)${x(s$1.suffix)})`,s$1.modifier===0&&(n+=`?`)}let c=`[${x(r.endsWith)}]|$`,l=`[${x(r.delimiter)}]`;if(r.end)return r.strict||(n+=`${l}?`),r.endsWith.length?n+=`(?=${c})`:n+=`$`,new RegExp(n,B(r));r.strict||(n+=`(?:${l}(?=${c}))?`);let f=!1;if(e.length){let s$1=e[e.length-1];s$1.type===3&&s$1.modifier===3&&(f=r.delimiter.indexOf(s$1)>-1)}return f||(n+=`(?=${l}|${c})`),new RegExp(n,B(r))}function ee(e,t){return e.length?e[0]===`/`?!0:!t||e.length<2?!1:(e[0]==`\\`||e[0]==`{`)&&e[1]==`/`:!1}function te(e,t){return e.startsWith(t)?e.substring(t.length,e.length):e}function ke(e,t){return e.endsWith(t)?e.substr(0,e.length-t.length):e}function _(e){return!e||e.length<2?!1:e[0]===`[`||(e[0]===`\\`||e[0]===`{`)&&e[1]===`[`}function U(e){if(!e)return!0;for(let t of re)if(e.test(t))return!0;return!1}function ne(e,t){if(e=te(e,`#`),t||e===``)return e;let r=new URL(`https://example.com`);return r.hash=e,r.hash?r.hash.substring(1,r.hash.length):``}function se(e,t){if(e=te(e,`?`),t||e===``)return e;let r=new URL(`https://example.com`);return r.search=e,r.search?r.search.substring(1,r.search.length):``}function ie(e,t){return t||e===``?e:_(e)?K(e):j(e)}function ae(e,t){if(t||e===``)return e;let r=new URL(`https://example.com`);return r.password=e,r.password}function oe(e,t){if(t||e===``)return e;let r=new URL(`https://example.com`);return r.username=e,r.username}function ce(e,t,r){if(r||e===``)return e;if(t&&!re.includes(t))return new URL(`${t}:${e}`).pathname;let n=e[0]==`/`;return e=new URL(n?e:`/-`+e,`https://example.com`).pathname,n||(e=e.substring(2,e.length)),e}function le(e,t,r){return z$1(t)===e&&(e=``),r||e===``?e:G(e)}function fe(e,t){return e=ke(e,`:`),t||e===``?e:w$1(e)}function z$1(e){switch(e){case`ws`:case`http`:return`80`;case`wws`:case`https`:return`443`;case`ftp`:return`21`;default:return``}}function w$1(e){if(e===``)return e;if(/^[-+.A-Za-z0-9]*$/.test(e))return e.toLowerCase();throw TypeError(`Invalid protocol '${e}'.`)}function he(e){if(e===``)return e;let t=new URL(`https://example.com`);return t.username=e,t.username}function ue(e){if(e===``)return e;let t=new URL(`https://example.com`);return t.password=e,t.password}function j(e){if(e===``)return e;if(/[\t\n\r #%/:<>?@[\]^\\|]/g.test(e))throw TypeError(`Invalid hostname '${e}'`);let t=new URL(`https://example.com`);return t.hostname=e,t.hostname}function K(e){if(e===``)return e;if(/[^0-9a-fA-F[\]:]/g.test(e))throw TypeError(`Invalid IPv6 hostname '${e}'`);return e.toLowerCase()}function G(e){if(e===``||/^[0-9]*$/.test(e)&&parseInt(e)<=65535)return e;throw TypeError(`Invalid port '${e}'.`)}function de(e){if(e===``)return e;let t=new URL(`https://example.com`);return t.pathname=e[0]===`/`?e:`/-`+e,e[0]===`/`?t.pathname:t.pathname.substring(2,t.pathname.length)}function pe(e){return e===``?e:new URL(`data:${e}`).pathname}function ge(e){if(e===``)return e;let t=new URL(`https://example.com`);return t.search=e,t.search.substring(1,t.search.length)}function me(e){if(e===``)return e;let t=new URL(`https://example.com`);return t.hash=e,t.hash.substring(1,t.hash.length)}function Se(e,t){if(typeof e!=`string`)throw TypeError(`parameter 1 is not of type 'string'.`);let r=new URL(e,t);return{protocol:r.protocol.substring(0,r.protocol.length-1),username:r.username,password:r.password,hostname:r.hostname,port:r.port,pathname:r.pathname,search:r.search===``?void 0:r.search.substring(1,r.search.length),hash:r.hash===``?void 0:r.hash.substring(1,r.hash.length)}}function R(e,t){return t?I(e):e}function L(e,t,r){let n;if(typeof t.baseURL==`string`)try{n=new URL(t.baseURL),t.protocol===void 0&&(e.protocol=R(n.protocol.substring(0,n.protocol.length-1),r)),!r&&t.protocol===void 0&&t.hostname===void 0&&t.port===void 0&&t.username===void 0&&(e.username=R(n.username,r)),!r&&t.protocol===void 0&&t.hostname===void 0&&t.port===void 0&&t.username===void 0&&t.password===void 0&&(e.password=R(n.password,r)),t.protocol===void 0&&t.hostname===void 0&&(e.hostname=R(n.hostname,r)),t.protocol===void 0&&t.hostname===void 0&&t.port===void 0&&(e.port=R(n.port,r)),t.protocol===void 0&&t.hostname===void 0&&t.port===void 0&&t.pathname===void 0&&(e.pathname=R(n.pathname,r)),t.protocol===void 0&&t.hostname===void 0&&t.port===void 0&&t.pathname===void 0&&t.search===void 0&&(e.search=R(n.search.substring(1,n.search.length),r)),t.protocol===void 0&&t.hostname===void 0&&t.port===void 0&&t.pathname===void 0&&t.search===void 0&&t.hash===void 0&&(e.hash=R(n.hash.substring(1,n.hash.length),r))}catch{throw TypeError(`invalid baseURL '${t.baseURL}'.`)}if(typeof t.protocol==`string`&&(e.protocol=fe(t.protocol,r)),typeof t.username==`string`&&(e.username=oe(t.username,r)),typeof t.password==`string`&&(e.password=ae(t.password,r)),typeof t.hostname==`string`&&(e.hostname=ie(t.hostname,r)),typeof t.port==`string`&&(e.port=le(t.port,e.protocol,r)),typeof t.pathname==`string`){if(e.pathname=t.pathname,n&&!ee(e.pathname,r)){let c=n.pathname.lastIndexOf(`/`);c>=0&&(e.pathname=R(n.pathname.substring(0,c+1),r)+e.pathname)}e.pathname=ce(e.pathname,e.protocol,r)}return typeof t.search==`string`&&(e.search=se(t.search,r)),typeof t.hash==`string`&&(e.hash=ne(t.hash,r)),e}function I(e){return e.replace(/([+*?:{}()\\])/g,`\\$1`)}function Te(e){return e.replace(/([.+*?^${}()[\]|/\\])/g,`\\$1`)}function Ae(e,t){t.delimiter??=`/#?`,t.prefixes??=`./`,t.sensitive??=!1,t.strict??=!1,t.end??=!0,t.start??=!0,t.endsWith=``;let r=`.*`,n=`[^${Te(t.delimiter)}]+?`,c=/[$_\u200C\u200D\p{ID_Continue}]/u,l=``;for(let f=0;f<e.length;++f){let s$1=e[f];if(s$1.type===3){if(s$1.modifier===3){l+=I(s$1.value);continue}l+=`{${I(s$1.value)}}${T(s$1.modifier)}`;continue}let i$1=s$1.hasCustomName(),o=!!s$1.suffix.length||!!s$1.prefix.length&&(s$1.prefix.length!==1||!t.prefixes.includes(s$1.prefix)),h$1=f>0?e[f-1]:null,p=f<e.length-1?e[f+1]:null;if(!o&&i$1&&s$1.type===1&&s$1.modifier===3&&p&&!p.prefix.length&&!p.suffix.length)if(p.type===3){let A=p.value.length>0?p.value[0]:``;o=c.test(A)}else o=!p.hasCustomName();if(!o&&!s$1.prefix.length&&h$1&&h$1.type===3){let A=h$1.value[h$1.value.length-1];o=t.prefixes.includes(A)}o&&(l+=`{`),l+=I(s$1.prefix),i$1&&(l+=`:${s$1.name}`),s$1.type===2?l+=`(${s$1.value})`:s$1.type===1?i$1||(l+=`(${n})`):s$1.type===0&&(!i$1&&(!h$1||h$1.type===3||h$1.modifier!==3||o||s$1.prefix!==``)?l+=`*`:l+=`(.*)`),s$1.type===1&&i$1&&s$1.suffix.length&&c.test(s$1.suffix[0])&&(l+=`\\`),l+=I(s$1.suffix),o&&(l+=`}`),s$1.modifier!==3&&(l+=T(s$1.modifier))}return l}var Pe,a,P,Re,Ee,v,b,J,Q,re,C,V,O,Y,init_urlpattern=__esmMin((()=>{Pe=Object.defineProperty,a=(e,t)=>Pe(e,`name`,{value:t,configurable:!0}),P=class{type=3;name=``;prefix=``;value=``;suffix=``;modifier=3;constructor(t,r,n,c,l,f){this.type=t,this.name=r,this.prefix=n,this.value=c,this.suffix=l,this.modifier=f}hasCustomName(){return this.name!==``&&typeof this.name!=`number`}},a(P,`Part`),Re=/[$_\p{ID_Start}]/u,Ee=/[$_\u200C\u200D\p{ID_Continue}]/u,v=`.*`,a(Oe,`isASCII`),a(D,`lexer`),a(F,`parse`),a(x,`escapeString`),a(B,`flags`),a(q,`stringToRegexp`),a(T,`modifierToString`),a(W,`partsToRegexp`),b={delimiter:``,prefixes:``,sensitive:!0,strict:!0},J={delimiter:`.`,prefixes:``,sensitive:!0,strict:!0},Q={delimiter:`/`,prefixes:`/`,sensitive:!0,strict:!0},a(ee,`isAbsolutePathname`),a(te,`maybeStripPrefix`),a(ke,`maybeStripSuffix`),a(_,`treatAsIPv6Hostname`),re=[`ftp`,`file`,`http`,`https`,`ws`,`wss`],a(U,`isSpecialScheme`),a(ne,`canonicalizeHash`),a(se,`canonicalizeSearch`),a(ie,`canonicalizeHostname`),a(ae,`canonicalizePassword`),a(oe,`canonicalizeUsername`),a(ce,`canonicalizePathname`),a(le,`canonicalizePort`),a(fe,`canonicalizeProtocol`),a(z$1,`defaultPortForProtocol`),a(w$1,`protocolEncodeCallback`),a(he,`usernameEncodeCallback`),a(ue,`passwordEncodeCallback`),a(j,`hostnameEncodeCallback`),a(K,`ipv6HostnameEncodeCallback`),a(G,`portEncodeCallback`),a(de,`standardURLPathnameEncodeCallback`),a(pe,`pathURLPathnameEncodeCallback`),a(ge,`searchEncodeCallback`),a(me,`hashEncodeCallback`),C=class{#i;#n=[];#t={};#e=0;#s=1;#l=0;#o=0;#d=0;#p=0;#g=!1;constructor(t){this.#i=t}get result(){return this.#t}parse(){for(this.#n=D(this.#i,!0);this.#e<this.#n.length;this.#e+=this.#s){if(this.#s=1,this.#n[this.#e].type===`END`){if(this.#o===0){this.#b(),this.#f()?this.#r(9,1):this.#h()?this.#r(8,1):this.#r(7,0);continue}else if(this.#o===2){this.#u(5);continue}this.#r(10,0);break}if(this.#d>0)if(this.#A())--this.#d;else continue;if(this.#T()){this.#d+=1;continue}switch(this.#o){case 0:this.#P()&&this.#u(1);break;case 1:if(this.#P()){this.#C();let t=7,r=1;this.#E()?(t=2,r=3):this.#g&&(t=2),this.#r(t,r)}break;case 2:this.#S()?this.#u(3):(this.#x()||this.#h()||this.#f())&&this.#u(5);break;case 3:this.#O()?this.#r(4,1):this.#S()&&this.#r(5,1);break;case 4:this.#S()&&this.#r(5,1);break;case 5:this.#y()?this.#p+=1:this.#w()&&--this.#p,this.#k()&&!this.#p?this.#r(6,1):this.#x()?this.#r(7,0):this.#h()?this.#r(8,1):this.#f()&&this.#r(9,1);break;case 6:this.#x()?this.#r(7,0):this.#h()?this.#r(8,1):this.#f()&&this.#r(9,1);break;case 7:this.#h()?this.#r(8,1):this.#f()&&this.#r(9,1);break;case 8:this.#f()&&this.#r(9,1);break;case 9:break;case 10:break}}this.#t.hostname!==void 0&&this.#t.port===void 0&&(this.#t.port=``)}#r(t,r){switch(this.#o){case 0:break;case 1:this.#t.protocol=this.#c();break;case 2:break;case 3:this.#t.username=this.#c();break;case 4:this.#t.password=this.#c();break;case 5:this.#t.hostname=this.#c();break;case 6:this.#t.port=this.#c();break;case 7:this.#t.pathname=this.#c();break;case 8:this.#t.search=this.#c();break;case 9:this.#t.hash=this.#c();break;case 10:break}this.#o!==0&&t!==10&&([1,2,3,4].includes(this.#o)&&[6,7,8,9].includes(t)&&(this.#t.hostname??=``),[1,2,3,4,5,6].includes(this.#o)&&[8,9].includes(t)&&(this.#t.pathname??=this.#g?`/`:``),[1,2,3,4,5,6,7].includes(this.#o)&&t===9&&(this.#t.search??=``)),this.#R(t,r)}#R(t,r){this.#o=t,this.#l=this.#e+r,this.#e+=r,this.#s=0}#b(){this.#e=this.#l,this.#s=0}#u(t){this.#b(),this.#o=t}#m(t){return t<0&&(t=this.#n.length-t),t<this.#n.length?this.#n[t]:this.#n[this.#n.length-1]}#a(t,r){let n=this.#m(t);return n.value===r&&(n.type===`CHAR`||n.type===`ESCAPED_CHAR`||n.type===`INVALID_CHAR`)}#P(){return this.#a(this.#e,`:`)}#E(){return this.#a(this.#e+1,`/`)&&this.#a(this.#e+2,`/`)}#S(){return this.#a(this.#e,`@`)}#O(){return this.#a(this.#e,`:`)}#k(){return this.#a(this.#e,`:`)}#x(){return this.#a(this.#e,`/`)}#h(){if(this.#a(this.#e,`?`))return!0;if(this.#n[this.#e].value!==`?`)return!1;let t=this.#m(this.#e-1);return t.type!==`NAME`&&t.type!==`REGEX`&&t.type!==`CLOSE`&&t.type!==`ASTERISK`}#f(){return this.#a(this.#e,`#`)}#T(){return this.#n[this.#e].type==`OPEN`}#A(){return this.#n[this.#e].type==`CLOSE`}#y(){return this.#a(this.#e,`[`)}#w(){return this.#a(this.#e,`]`)}#c(){let t=this.#n[this.#e],r=this.#m(this.#l).index;return this.#i.substring(r,t.index)}#C(){let t={};Object.assign(t,b),t.encodePart=w$1;let r=q(this.#c(),void 0,t);this.#g=U(r)}},a(C,`Parser`),V=[`protocol`,`username`,`password`,`hostname`,`port`,`pathname`,`search`,`hash`],O=`*`,a(Se,`extractValues`),a(R,`processBaseURLString`),a(L,`applyInit`),a(I,`escapePatternString`),a(Te,`escapeRegexpString`),a(Ae,`partsToPattern`),Y=class{#i;#n={};#t={};#e={};#s={};#l=!1;constructor(t={},r,n){try{let c;if(typeof r==`string`?c=r:n=r,typeof t==`string`){let i$1=new C(t);if(i$1.parse(),t=i$1.result,c===void 0&&typeof t.protocol!=`string`)throw TypeError(`A base URL must be provided for a relative constructor string.`);t.baseURL=c}else{if(!t||typeof t!=`object`)throw TypeError(`parameter 1 is not of type 'string' and cannot convert to dictionary.`);if(c)throw TypeError(`parameter 1 is not of type 'string'.`)}typeof n>`u`&&(n={ignoreCase:!1});let l={ignoreCase:n.ignoreCase===!0};this.#i=L({pathname:O,protocol:O,username:O,password:O,hostname:O,port:O,search:O,hash:O},t,!0),z$1(this.#i.protocol)===this.#i.port&&(this.#i.port=``);let s$1;for(s$1 of V){if(!(s$1 in this.#i))continue;let i$1={},o=this.#i[s$1];switch(this.#t[s$1]=[],s$1){case`protocol`:Object.assign(i$1,b),i$1.encodePart=w$1;break;case`username`:Object.assign(i$1,b),i$1.encodePart=he;break;case`password`:Object.assign(i$1,b),i$1.encodePart=ue;break;case`hostname`:Object.assign(i$1,J),_(o)?i$1.encodePart=K:i$1.encodePart=j;break;case`port`:Object.assign(i$1,b),i$1.encodePart=G;break;case`pathname`:U(this.#n.protocol)?(Object.assign(i$1,Q,l),i$1.encodePart=de):(Object.assign(i$1,b,l),i$1.encodePart=pe);break;case`search`:Object.assign(i$1,b,l),i$1.encodePart=ge;break;case`hash`:Object.assign(i$1,b,l),i$1.encodePart=me;break}try{this.#s[s$1]=F(o,i$1),this.#n[s$1]=W(this.#s[s$1],this.#t[s$1],i$1),this.#e[s$1]=Ae(this.#s[s$1],i$1),this.#l=this.#l||this.#s[s$1].some(h$1=>h$1.type===2)}catch{throw TypeError(`invalid ${s$1} pattern '${this.#i[s$1]}'.`)}}}catch(c){throw TypeError(`Failed to construct 'URLPattern': ${c.message}`)}}get[Symbol.toStringTag](){return`URLPattern`}test(t={},r){let n={pathname:``,protocol:``,username:``,password:``,hostname:``,port:``,search:``,hash:``};if(typeof t!=`string`&&r)throw TypeError(`parameter 1 is not of type 'string'.`);if(typeof t>`u`)return!1;try{n=typeof t==`object`?L(n,t,!1):L(n,Se(t,r),!1)}catch{return!1}let c;for(c of V)if(!this.#n[c].exec(n[c]))return!1;return!0}exec(t={},r){let n={pathname:``,protocol:``,username:``,password:``,hostname:``,port:``,search:``,hash:``};if(typeof t!=`string`&&r)throw TypeError(`parameter 1 is not of type 'string'.`);if(typeof t>`u`)return;try{n=typeof t==`object`?L(n,t,!1):L(n,Se(t,r),!1)}catch{return null}let c={};r?c.inputs=[t,r]:c.inputs=[t];let l;for(l of V){let f=this.#n[l].exec(n[l]);if(!f)return null;let s$1={};for(let[i$1,o]of this.#t[l].entries())(typeof o==`string`||typeof o==`number`)&&(s$1[o]=f[i$1+1]);c[l]={input:n[l]??``,groups:s$1}}return c}static compareComponent(t,r,n){let c=a((i$1,o)=>{for(let h$1 of[`type`,`modifier`,`prefix`,`value`,`suffix`]){if(i$1[h$1]<o[h$1])return-1;if(i$1[h$1]!==o[h$1])return 1}return 0},`comparePart`),l=new P(3,``,``,``,``,3),f=new P(0,``,``,``,``,3),s$1=a((i$1,o)=>{let h$1=0;for(;h$1<Math.min(i$1.length,o.length);++h$1){let p=c(i$1[h$1],o[h$1]);if(p)return p}return i$1.length===o.length?0:c(i$1[h$1]??l,o[h$1]??l)},`comparePartList`);return!r.#e[t]&&!n.#e[t]?0:r.#e[t]&&!n.#e[t]?s$1(r.#s[t],[f]):!r.#e[t]&&n.#e[t]?s$1([f],n.#s[t]):s$1(r.#s[t],n.#s[t])}get protocol(){return this.#e.protocol}get username(){return this.#e.username}get password(){return this.#e.password}get hostname(){return this.#e.hostname}get port(){return this.#e.port}get pathname(){return this.#e.pathname}get search(){return this.#e.search}get hash(){return this.#e.hash}get hasRegExpGroups(){return this.#l}},a(Y,`URLPattern`)})),urlpattern_polyfill_exports=__export$3({URLPattern:()=>Y}),init_urlpattern_polyfill=__esmMin((()=>{init_urlpattern(),globalThis.URLPattern||(globalThis.URLPattern=Y)})),require_sbmh=__commonJSMin(((exports,module)=>{let{EventEmitter:EventEmitter$2}=__require(`node:events`),{inherits:inherits$5}=__require(`node:util`);function SBMH(needle){if(typeof needle==`string`&&(needle=Buffer.from(needle)),!Buffer.isBuffer(needle))throw TypeError(`The needle has to be a String or a Buffer.`);let needleLength=needle.length,needleLastCharIndex=needleLength-1;if(needleLength===0)throw Error(`The needle cannot be an empty String/Buffer.`);if(needleLength>256)throw Error(`The needle cannot have a length bigger than 256.`);this.maxMatches=1/0,this.matches=0,this._occ=new Uint8Array(256).fill(needleLength),this._lookbehind_size=0,this._needle=needle,this._bufpos=0,this._lookbehind=Buffer.alloc(needleLastCharIndex);for(var i$1=0;i$1<needleLastCharIndex;++i$1)this._occ[needle[i$1]]=needleLastCharIndex-i$1}inherits$5(SBMH,EventEmitter$2),SBMH.prototype.reset=function(){this._lookbehind_size=0,this.matches=0,this._bufpos=0},SBMH.prototype.push=function(chunk,pos){Buffer.isBuffer(chunk)||(chunk=Buffer.from(chunk,`binary`));let chlen=chunk.length;this._bufpos=pos||0;let r;for(;r!==chlen&&this.matches<this.maxMatches;)r=this._sbmh_feed(chunk);return r},SBMH.prototype._sbmh_feed=function(data){let len=data.length,needle=this._needle,needleLength=needle.length,needleLastCharIndex=needleLength-1,needleLastChar=needle[needleLastCharIndex],pos=-this._lookbehind_size,ch;if(pos<0){for(;pos<0&&pos<=len-needleLength;){if(ch=data[pos+needleLastCharIndex],ch===needleLastChar&&this._sbmh_memcmp(data,pos,needleLastCharIndex))return this._lookbehind_size=0,++this.matches,this.emit(`info`,!0),this._bufpos=pos+needleLength;pos+=this._occ[ch]}for(;pos<0&&!this._sbmh_memcmp(data,pos,len-pos);)++pos;if(pos>=0)this.emit(`info`,!1,this._lookbehind,0,this._lookbehind_size),this._lookbehind_size=0;else{let bytesToCutOff=this._lookbehind_size+pos;return bytesToCutOff>0&&this.emit(`info`,!1,this._lookbehind,0,bytesToCutOff),this._lookbehind_size-=bytesToCutOff,this._lookbehind.copy(this._lookbehind,0,bytesToCutOff,this._lookbehind_size),data.copy(this._lookbehind,this._lookbehind_size),this._lookbehind_size+=len,this._bufpos=len,len}}if(pos=data.indexOf(needle,pos+this._bufpos),pos!==-1)return++this.matches,pos===0?this.emit(`info`,!0):this.emit(`info`,!0,data,this._bufpos,pos),this._bufpos=pos+needleLength;for(pos=len-needleLastCharIndex,pos<0&&(pos=0);pos!==len&&(data[pos]!==needle[0]||Buffer.compare(data.subarray(pos+1,len),needle.subarray(1,len-pos))!==0);)++pos;return pos!==len&&(data.copy(this._lookbehind,0,pos,len),this._lookbehind_size=len-pos),pos!==0&&this.emit(`info`,!1,data,this._bufpos,pos),this._bufpos=len,len},SBMH.prototype._sbmh_lookup_char=function(data,pos){return pos<0?this._lookbehind[this._lookbehind_size+pos]:data[pos]},SBMH.prototype._sbmh_memcmp=function(data,pos,len){for(var i$1=0;i$1<len;++i$1)if(this._sbmh_lookup_char(data,pos+i$1)!==this._needle[i$1])return!1;return!0},module.exports=SBMH})),require_PartStream=__commonJSMin(((exports,module)=>{let inherits$4=__require(`node:util`).inherits,ReadableStream$1=__require(`node:stream`).Readable;function PartStream$1(opts){ReadableStream$1.call(this,opts)}inherits$4(PartStream$1,ReadableStream$1),PartStream$1.prototype._read=function(n){},module.exports=PartStream$1})),require_getLimit=__commonJSMin(((exports,module)=>{module.exports=function(limits,name$2,defaultLimit){if(!limits||limits[name$2]===void 0||limits[name$2]===null)return defaultLimit;if(typeof limits[name$2]!=`number`||isNaN(limits[name$2]))throw TypeError(`Limit `+name$2+` is not a valid number`);return limits[name$2]}})),require_HeaderParser=__commonJSMin(((exports,module)=>{let EventEmitter$1=__require(`node:events`).EventEmitter,inherits$3=__require(`node:util`).inherits,getLimit$2=require_getLimit(),StreamSearch$1=require_sbmh(),B_DCRLF=Buffer.from(`\r
|
|
27
|
+
Run 'npx vercel link' to link your project, then 'vc env pull' to fetch the token.`,new _GatewayAuthenticationError({message:contextualMessage,statusCode,cause})}},name2=`GatewayInvalidRequestError`,marker3=`vercel.ai.gateway.error.${name2}`,symbol3=Symbol.for(marker3),_a3,_b3,GatewayInvalidRequestError=class extends (_b3=GatewayError,_a3=symbol3,_b3){constructor({message=`Invalid request`,statusCode=400,cause}={}){super({message,statusCode,cause}),this[_a3]=!0,this.name=name2,this.type=`invalid_request_error`}static isInstance(error){return GatewayError.hasMarker(error)&&symbol3 in error}},name3=`GatewayRateLimitError`,marker4=`vercel.ai.gateway.error.${name3}`,symbol4=Symbol.for(marker4),_a4,_b4,GatewayRateLimitError=class extends (_b4=GatewayError,_a4=symbol4,_b4){constructor({message=`Rate limit exceeded`,statusCode=429,cause}={}){super({message,statusCode,cause}),this[_a4]=!0,this.name=name3,this.type=`rate_limit_exceeded`}static isInstance(error){return GatewayError.hasMarker(error)&&symbol4 in error}},name4=`GatewayModelNotFoundError`,marker5=`vercel.ai.gateway.error.${name4}`,symbol5=Symbol.for(marker5),modelNotFoundParamSchema=lazyValidator(()=>zodSchema(z.object({modelId:z.string()}))),_a5,_b5,GatewayModelNotFoundError=class extends (_b5=GatewayError,_a5=symbol5,_b5){constructor({message=`Model not found`,statusCode=404,modelId,cause}={}){super({message,statusCode,cause}),this[_a5]=!0,this.name=name4,this.type=`model_not_found`,this.modelId=modelId}static isInstance(error){return GatewayError.hasMarker(error)&&symbol5 in error}},name5=`GatewayInternalServerError`,marker6=`vercel.ai.gateway.error.${name5}`,symbol6=Symbol.for(marker6),_a6,_b6,GatewayInternalServerError=class extends (_b6=GatewayError,_a6=symbol6,_b6){constructor({message=`Internal server error`,statusCode=500,cause}={}){super({message,statusCode,cause}),this[_a6]=!0,this.name=name5,this.type=`internal_server_error`}static isInstance(error){return GatewayError.hasMarker(error)&&symbol6 in error}},name6=`GatewayResponseError`,marker7=`vercel.ai.gateway.error.${name6}`,symbol7=Symbol.for(marker7),_a7,_b7,GatewayResponseError=class extends (_b7=GatewayError,_a7=symbol7,_b7){constructor({message=`Invalid response from Gateway`,statusCode=502,response,validationError,cause}={}){super({message,statusCode,cause}),this[_a7]=!0,this.name=name6,this.type=`response_error`,this.response=response,this.validationError=validationError}static isInstance(error){return GatewayError.hasMarker(error)&&symbol7 in error}};async function createGatewayErrorFromResponse({response,statusCode,defaultMessage=`Gateway request failed`,cause,authMethod}){let parseResult=await safeValidateTypes({value:response,schema:gatewayErrorResponseSchema});if(!parseResult.success)return new GatewayResponseError({message:`Invalid error response format: ${defaultMessage}`,statusCode,response,validationError:parseResult.error,cause});let validatedResponse=parseResult.value,errorType=validatedResponse.error.type,message=validatedResponse.error.message;switch(errorType){case`authentication_error`:return GatewayAuthenticationError.createContextualError({apiKeyProvided:authMethod===`api-key`,oidcTokenProvided:authMethod===`oidc`,statusCode,cause});case`invalid_request_error`:return new GatewayInvalidRequestError({message,statusCode,cause});case`rate_limit_exceeded`:return new GatewayRateLimitError({message,statusCode,cause});case`model_not_found`:{let modelResult=await safeValidateTypes({value:validatedResponse.error.param,schema:modelNotFoundParamSchema});return new GatewayModelNotFoundError({message,statusCode,modelId:modelResult.success?modelResult.value.modelId:void 0,cause})}case`internal_server_error`:return new GatewayInternalServerError({message,statusCode,cause});default:return new GatewayInternalServerError({message,statusCode,cause})}}var gatewayErrorResponseSchema=lazyValidator(()=>zodSchema(z.object({error:z.object({message:z.string(),type:z.string().nullish(),param:z.unknown().nullish(),code:z.union([z.string(),z.number()]).nullish()})})));function asGatewayError(error,authMethod){var _a8$1;return GatewayError.isInstance(error)?error:APICallError.isInstance(error)?createGatewayErrorFromResponse({response:extractApiCallResponse(error),statusCode:error.statusCode??500,defaultMessage:`Gateway request failed`,cause:error,authMethod}):createGatewayErrorFromResponse({response:{},statusCode:500,defaultMessage:error instanceof Error?`Gateway request failed: ${error.message}`:`Unknown Gateway error`,cause:error,authMethod})}function extractApiCallResponse(error){if(error.data!==void 0)return error.data;if(error.responseBody!=null)try{return JSON.parse(error.responseBody)}catch{return error.responseBody}return{}}var GATEWAY_AUTH_METHOD_HEADER=`ai-gateway-auth-method`;async function parseAuthMethod(headers){let result=await safeValidateTypes({value:headers[GATEWAY_AUTH_METHOD_HEADER],schema:gatewayAuthMethodSchema});return result.success?result.value:void 0}var gatewayAuthMethodSchema=lazyValidator(()=>zodSchema(z.union([z.literal(`api-key`),z.literal(`oidc`)]))),GatewayFetchMetadata=class{constructor(config){this.config=config}async getAvailableModels(){try{let{value}=await getFromApi({url:`${this.config.baseURL}/config`,headers:await resolve(this.config.headers()),successfulResponseHandler:createJsonResponseHandler(gatewayAvailableModelsResponseSchema),failedResponseHandler:createJsonErrorResponseHandler({errorSchema:z.any(),errorToMessage:data=>data}),fetch:this.config.fetch});return value}catch(error){throw await asGatewayError(error)}}async getCredits(){try{let baseUrl=new URL(this.config.baseURL),{value}=await getFromApi({url:`${baseUrl.origin}/v1/credits`,headers:await resolve(this.config.headers()),successfulResponseHandler:createJsonResponseHandler(gatewayCreditsResponseSchema),failedResponseHandler:createJsonErrorResponseHandler({errorSchema:z.any(),errorToMessage:data=>data}),fetch:this.config.fetch});return value}catch(error){throw await asGatewayError(error)}}},gatewayAvailableModelsResponseSchema=lazyValidator(()=>zodSchema(z.object({models:z.array(z.object({id:z.string(),name:z.string(),description:z.string().nullish(),pricing:z.object({input:z.string(),output:z.string(),input_cache_read:z.string().nullish(),input_cache_write:z.string().nullish()}).transform(({input,output,input_cache_read,input_cache_write})=>({input,output,...input_cache_read?{cachedInputTokens:input_cache_read}:{},...input_cache_write?{cacheCreationInputTokens:input_cache_write}:{}})).nullish(),specification:z.object({specificationVersion:z.literal(`v2`),provider:z.string(),modelId:z.string()}),modelType:z.enum([`language`,`embedding`,`image`]).nullish()}))}))),gatewayCreditsResponseSchema=lazyValidator(()=>zodSchema(z.object({balance:z.string(),total_used:z.string()}).transform(({balance,total_used})=>({balance,totalUsed:total_used})))),GatewayLanguageModel=class{constructor(modelId,config){this.modelId=modelId,this.config=config,this.specificationVersion=`v2`,this.supportedUrls={"*/*":[/.*/]}}get provider(){return this.config.provider}async getArgs(options){let{abortSignal:_abortSignal,...optionsWithoutSignal}=options;return{args:this.maybeEncodeFileParts(optionsWithoutSignal),warnings:[]}}async doGenerate(options){let{args,warnings}=await this.getArgs(options),{abortSignal}=options,resolvedHeaders=await resolve(this.config.headers());try{let{responseHeaders,value:responseBody,rawValue:rawResponse}=await postJsonToApi({url:this.getUrl(),headers:combineHeaders(resolvedHeaders,options.headers,this.getModelConfigHeaders(this.modelId,!1),await resolve(this.config.o11yHeaders)),body:args,successfulResponseHandler:createJsonResponseHandler(z.any()),failedResponseHandler:createJsonErrorResponseHandler({errorSchema:z.any(),errorToMessage:data=>data}),...abortSignal&&{abortSignal},fetch:this.config.fetch});return{...responseBody,request:{body:args},response:{headers:responseHeaders,body:rawResponse},warnings}}catch(error){throw await asGatewayError(error,await parseAuthMethod(resolvedHeaders))}}async doStream(options){let{args,warnings}=await this.getArgs(options),{abortSignal}=options,resolvedHeaders=await resolve(this.config.headers());try{let{value:response,responseHeaders}=await postJsonToApi({url:this.getUrl(),headers:combineHeaders(resolvedHeaders,options.headers,this.getModelConfigHeaders(this.modelId,!0),await resolve(this.config.o11yHeaders)),body:args,successfulResponseHandler:createEventSourceResponseHandler(z.any()),failedResponseHandler:createJsonErrorResponseHandler({errorSchema:z.any(),errorToMessage:data=>data}),...abortSignal&&{abortSignal},fetch:this.config.fetch});return{stream:response.pipeThrough(new TransformStream({start(controller){warnings.length>0&&controller.enqueue({type:`stream-start`,warnings})},transform(chunk,controller){if(chunk.success){let streamPart=chunk.value;if(streamPart.type===`raw`&&!options.includeRawChunks)return;streamPart.type===`response-metadata`&&streamPart.timestamp&&typeof streamPart.timestamp==`string`&&(streamPart.timestamp=new Date(streamPart.timestamp)),controller.enqueue(streamPart)}else controller.error(chunk.error)}})),request:{body:args},response:{headers:responseHeaders}}}catch(error){throw await asGatewayError(error,await parseAuthMethod(resolvedHeaders))}}isFilePart(part){return part&&typeof part==`object`&&`type`in part&&part.type===`file`}maybeEncodeFileParts(options){for(let message of options.prompt)for(let part of message.content)if(this.isFilePart(part)){let filePart=part;if(filePart.data instanceof Uint8Array){let buffer=Uint8Array.from(filePart.data),base64Data=Buffer.from(buffer).toString(`base64`);filePart.data=new URL(`data:${filePart.mediaType||`application/octet-stream`};base64,${base64Data}`)}}return options}getUrl(){return`${this.config.baseURL}/language-model`}getModelConfigHeaders(modelId,streaming){return{"ai-language-model-specification-version":`2`,"ai-language-model-id":modelId,"ai-language-model-streaming":String(streaming)}}},GatewayEmbeddingModel=class{constructor(modelId,config){this.modelId=modelId,this.config=config,this.specificationVersion=`v2`,this.maxEmbeddingsPerCall=2048,this.supportsParallelCalls=!0}get provider(){return this.config.provider}async doEmbed({values,headers,abortSignal,providerOptions}){var _a8$1;let resolvedHeaders=await resolve(this.config.headers());try{let{responseHeaders,value:responseBody,rawValue}=await postJsonToApi({url:this.getUrl(),headers:combineHeaders(resolvedHeaders,headers??{},this.getModelConfigHeaders(),await resolve(this.config.o11yHeaders)),body:{input:values.length===1?values[0]:values,...providerOptions?{providerOptions}:{}},successfulResponseHandler:createJsonResponseHandler(gatewayEmbeddingResponseSchema),failedResponseHandler:createJsonErrorResponseHandler({errorSchema:z.any(),errorToMessage:data=>data}),...abortSignal&&{abortSignal},fetch:this.config.fetch});return{embeddings:responseBody.embeddings,usage:responseBody.usage??void 0,providerMetadata:responseBody.providerMetadata,response:{headers:responseHeaders,body:rawValue}}}catch(error){throw await asGatewayError(error,await parseAuthMethod(resolvedHeaders))}}getUrl(){return`${this.config.baseURL}/embedding-model`}getModelConfigHeaders(){return{"ai-embedding-model-specification-version":`2`,"ai-model-id":this.modelId}}},gatewayEmbeddingResponseSchema=lazyValidator(()=>zodSchema(z.object({embeddings:z.array(z.array(z.number())),usage:z.object({tokens:z.number()}).nullish(),providerMetadata:z.record(z.string(),z.record(z.string(),z.unknown())).optional()})));async function getVercelRequestId(){var _a8$1;return(0,import_dist.getContext)().headers?.[`x-vercel-id`]}var VERSION$1=`2.0.9`,AI_GATEWAY_PROTOCOL_VERSION=`0.0.1`;function createGatewayProvider(options={}){var _a8$1,_b8;let pendingMetadata=null,metadataCache=null,cacheRefreshMillis=options.metadataCacheRefreshMillis??1e3*60*5,lastFetchTime=0,baseURL=withoutTrailingSlash(options.baseURL)??`https://ai-gateway.vercel.sh/v1/ai`,getHeaders=async()=>{let auth=await getGatewayAuthToken(options);if(auth)return withUserAgentSuffix({Authorization:`Bearer ${auth.token}`,"ai-gateway-protocol-version":AI_GATEWAY_PROTOCOL_VERSION,[GATEWAY_AUTH_METHOD_HEADER]:auth.authMethod,...options.headers},`ai-sdk/gateway/${VERSION$1}`);throw GatewayAuthenticationError.createContextualError({apiKeyProvided:!1,oidcTokenProvided:!1,statusCode:401})},createO11yHeaders=()=>{let deploymentId=loadOptionalSetting({settingValue:void 0,environmentVariableName:`VERCEL_DEPLOYMENT_ID`}),environment=loadOptionalSetting({settingValue:void 0,environmentVariableName:`VERCEL_ENV`}),region=loadOptionalSetting({settingValue:void 0,environmentVariableName:`VERCEL_REGION`});return async()=>{let requestId=await getVercelRequestId();return{...deploymentId&&{"ai-o11y-deployment-id":deploymentId},...environment&&{"ai-o11y-environment":environment},...region&&{"ai-o11y-region":region},...requestId&&{"ai-o11y-request-id":requestId}}}},createLanguageModel=modelId=>new GatewayLanguageModel(modelId,{provider:`gateway`,baseURL,headers:getHeaders,fetch:options.fetch,o11yHeaders:createO11yHeaders()}),getAvailableModels=async()=>{var _a9$1,_b9,_c;let now=((_a9$1=options._internal)?.currentDate)?.call(_a9$1).getTime()??Date.now();return(!pendingMetadata||now-lastFetchTime>cacheRefreshMillis)&&(lastFetchTime=now,pendingMetadata=new GatewayFetchMetadata({baseURL,headers:getHeaders,fetch:options.fetch}).getAvailableModels().then(metadata=>(metadataCache=metadata,metadata)).catch(async error=>{throw await asGatewayError(error,await parseAuthMethod(await getHeaders()))})),metadataCache?Promise.resolve(metadataCache):pendingMetadata},getCredits=async()=>new GatewayFetchMetadata({baseURL,headers:getHeaders,fetch:options.fetch}).getCredits().catch(async error=>{throw await asGatewayError(error,await parseAuthMethod(await getHeaders()))}),provider=function(modelId){if(new.target)throw Error(`The Gateway Provider model function cannot be called with the new keyword.`);return createLanguageModel(modelId)};return provider.getAvailableModels=getAvailableModels,provider.getCredits=getCredits,provider.imageModel=modelId=>{throw new NoSuchModelError({modelId,modelType:`imageModel`})},provider.languageModel=createLanguageModel,provider.textEmbeddingModel=modelId=>new GatewayEmbeddingModel(modelId,{provider:`gateway`,baseURL,headers:getHeaders,fetch:options.fetch,o11yHeaders:createO11yHeaders()}),provider}var gateway=createGatewayProvider();async function getGatewayAuthToken(options){let apiKey=loadOptionalSetting({settingValue:options.apiKey,environmentVariableName:`AI_GATEWAY_API_KEY`});if(apiKey)return{token:apiKey,authMethod:`api-key`};try{return{token:await(0,import_dist$1.getVercelOidcToken)(),authMethod:`oidc`}}catch{return null}}function isPromise(value){return value?.then!=null}function isActualPromise(value){let maybePromise=value;return maybePromise&&maybePromise.then&&maybePromise.catch&&maybePromise.finally}function handleMaybePromise(inputFactory,outputSuccessFactory,outputErrorFactory,finallyFactory){let result$=fakePromise().then(inputFactory).then(outputSuccessFactory,outputErrorFactory);return finallyFactory&&(result$=result$.finally(finallyFactory)),unfakePromise(result$)}function fakePromise(value){return value&&isActualPromise(value)?value:isPromise(value)?{then:(resolve$1,reject)=>fakePromise(value.then(resolve$1,reject)),catch:reject=>fakePromise(value.then(res=>res,reject)),finally:cb=>fakePromise(cb?promiseLikeFinally(value,cb):value),[Symbol.toStringTag]:`Promise`}:{then(resolve$1){if(resolve$1)try{return fakePromise(resolve$1(value))}catch(err){return fakeRejectPromise(err)}return this},catch(){return this},finally(cb){if(cb)try{return fakePromise(cb()).then(()=>value,()=>value)}catch(err){return fakeRejectPromise(err)}return this},[Symbol.toStringTag]:`Promise`,__fakePromiseValue:value,[kFakePromise]:`resolved`}}function createDeferredPromise(){if(Promise.withResolvers)return Promise.withResolvers();let resolveFn,rejectFn;return{promise:new Promise(function(resolve$1,reject){resolveFn=resolve$1,rejectFn=reject}),get resolve(){return resolveFn},get reject(){return rejectFn}}}function iterateAsync(iterable,callback,results){if(iterable?.length===0)return;let iterator=iterable[Symbol.iterator](),index=0;function iterate(){let{done:endOfIterator,value}=iterator.next();if(endOfIterator)return;let endedEarly=!1;function endEarly(){endedEarly=!0}return handleMaybePromise(function(){return callback(value,endEarly,index++)},function(result){if(result&&results?.push(result),!endedEarly)return iterate()})}return iterate()}function fakeRejectPromise(error){return{then(_resolve,reject){if(reject)try{return fakePromise(reject(error))}catch(err){return fakeRejectPromise(err)}return this},catch(reject){if(reject)try{return fakePromise(reject(error))}catch(err){return fakeRejectPromise(err)}return this},finally(cb){if(cb)try{cb()}catch(err){return fakeRejectPromise(err)}return this},__fakeRejectError:error,[Symbol.toStringTag]:`Promise`,[kFakePromise]:`rejected`}}function isFakePromise(value){return value?.[kFakePromise]===`resolved`}function isFakeRejectPromise(value){return value?.[kFakePromise]===`rejected`}function promiseLikeFinally(value,onFinally){return`finally`in value?value.finally(onFinally):value.then(res=>{let finallyRes=onFinally();return isPromise(finallyRes)?finallyRes.then(()=>res):res},err=>{let finallyRes=onFinally();if(isPromise(finallyRes))return finallyRes.then(()=>{throw err});throw err})}function unfakePromise(promise){if(isFakePromise(promise))return promise.__fakePromiseValue;if(isFakeRejectPromise(promise))throw promise.__fakeRejectError;return promise}var kFakePromise,init_esm$4=__esmMin((()=>{kFakePromise=Symbol.for(`@whatwg-node/promise-helpers/FakePromise`)}));init_esm$4();function chain(first,next){let merged={...next,...first};for(let key of Object.keys(merged))key in first&&key in next&&(merged[key]=(payload,wrapped)=>first[key](payload,()=>next[key](payload,wrapped)));return merged}const getInstrumented=payload=>({fn(instrument,wrapped){return instrument?(...args)=>{let result;return instrument(payload,()=>{result=wrapped(...args)}),result}:wrapped},asyncFn(instrument,wrapped){return instrument?(...args)=>{let result;return handleMaybePromise(()=>instrument(payload,()=>(result=wrapped(...args),isPromise(result)?result.then(()=>void 0):void 0)),()=>result)}:wrapped}});var PonyfillSuppressedError,init_SupressedError=__esmMin((()=>{PonyfillSuppressedError=class extends Error{error;suppressed;constructor(error,suppressed,message){super(message),this.error=error,this.suppressed=suppressed,this.name=`SuppressedError`,Error.captureStackTrace(this,this.constructor)}}})),DisposableSymbols,init_symbols=__esmMin((()=>{DisposableSymbols={get dispose(){return Symbol.dispose||Symbol.for(`dispose`)},get asyncDispose(){return Symbol.asyncDispose||Symbol.for(`asyncDispose`)}}}));function isSyncDisposable(obj){return obj?.[DisposableSymbols.dispose]!=null}function isAsyncDisposable(obj){return obj?.[DisposableSymbols.asyncDispose]!=null}var init_utils$2=__esmMin((()=>{init_symbols()})),SuppressedError$2,PonyfillAsyncDisposableStack,init_AsyncDisposableStack=__esmMin((()=>{init_esm$4(),init_SupressedError(),init_symbols(),init_utils$2(),SuppressedError$2=globalThis.SuppressedError||PonyfillSuppressedError,PonyfillAsyncDisposableStack=class PonyfillAsyncDisposableStack{callbacks=[];get disposed(){return this.callbacks.length===0}use(value){return isAsyncDisposable(value)?this.callbacks.push(()=>value[DisposableSymbols.asyncDispose]()):isSyncDisposable(value)&&this.callbacks.push(()=>value[DisposableSymbols.dispose]()),value}adopt(value,onDisposeAsync){return onDisposeAsync&&this.callbacks.push(()=>onDisposeAsync(value)),value}defer(onDisposeAsync){onDisposeAsync&&this.callbacks.push(onDisposeAsync)}move(){let stack=new PonyfillAsyncDisposableStack;return stack.callbacks=this.callbacks,this.callbacks=[],stack}disposeAsync(){return this[DisposableSymbols.asyncDispose]()}_error;_iterateCallbacks(){let cb=this.callbacks.pop();if(cb)return handleMaybePromise(cb,()=>this._iterateCallbacks(),error=>(this._error=this._error?new SuppressedError$2(error,this._error):error,this._iterateCallbacks()))}[DisposableSymbols.asyncDispose](){let res$=this._iterateCallbacks();if(res$?.then)return res$.then(()=>{if(this._error){let error=this._error;throw this._error=void 0,error}});if(this._error){let error=this._error;throw this._error=void 0,error}}[Symbol.toStringTag]=`AsyncDisposableStack`}})),SuppressedError$1,PonyfillDisposableStack,init_DisposableStack=__esmMin((()=>{init_SupressedError(),init_symbols(),init_utils$2(),globalThis.SuppressedError,DisposableSymbols.dispose,Symbol.toStringTag})),DisposableStack,AsyncDisposableStack,SuppressedError,init_esm$3=__esmMin((()=>{init_AsyncDisposableStack(),init_DisposableStack(),init_SupressedError(),init_symbols(),globalThis.DisposableStack,AsyncDisposableStack=globalThis.AsyncDisposableStack||PonyfillAsyncDisposableStack,globalThis.SuppressedError})),require_shouldSkipPonyfill=__commonJSMin(((exports,module)=>{function isNextJs(){return Object.keys(globalThis).some(key=>key.startsWith(`__NEXT`))}module.exports=function(){return!!(globalThis.Deno||globalThis.Bun||isNextJs())}}));function Oe(e,t){return(t?/^[\x00-\xFF]*$/:/^[\x00-\x7F]*$/).test(e)}function D(e,t=!1){let r=[],n=0;for(;n<e.length;){let c=e[n],l=a(function(f){if(!t)throw TypeError(f);r.push({type:`INVALID_CHAR`,index:n,value:e[n++]})},`ErrorOrInvalid`);if(c===`*`){r.push({type:`ASTERISK`,index:n,value:e[n++]});continue}if(c===`+`||c===`?`){r.push({type:`OTHER_MODIFIER`,index:n,value:e[n++]});continue}if(c===`\\`){r.push({type:`ESCAPED_CHAR`,index:n++,value:e[n++]});continue}if(c===`{`){r.push({type:`OPEN`,index:n,value:e[n++]});continue}if(c===`}`){r.push({type:`CLOSE`,index:n,value:e[n++]});continue}if(c===`:`){let f=``,s$1=n+1;for(;s$1<e.length;){let i$1=e.substr(s$1,1);if(s$1===n+1&&Re.test(i$1)||s$1!==n+1&&Ee.test(i$1)){f+=e[s$1++];continue}break}if(!f){l(`Missing parameter name at ${n}`);continue}r.push({type:`NAME`,index:n,value:f}),n=s$1;continue}if(c===`(`){let f=1,s$1=``,i$1=n+1,o=!1;if(e[i$1]===`?`){l(`Pattern cannot start with "?" at ${i$1}`);continue}for(;i$1<e.length;){if(!Oe(e[i$1],!1)){l(`Invalid character '${e[i$1]}' at ${i$1}.`),o=!0;break}if(e[i$1]===`\\`){s$1+=e[i$1++]+e[i$1++];continue}if(e[i$1]===`)`){if(f--,f===0){i$1++;break}}else if(e[i$1]===`(`&&(f++,e[i$1+1]!==`?`)){l(`Capturing groups are not allowed at ${i$1}`),o=!0;break}s$1+=e[i$1++]}if(o)continue;if(f){l(`Unbalanced pattern at ${n}`);continue}if(!s$1){l(`Missing pattern at ${n}`);continue}r.push({type:`REGEX`,index:n,value:s$1}),n=i$1;continue}r.push({type:`CHAR`,index:n,value:e[n++]})}return r.push({type:`END`,index:n,value:``}),r}function F(e,t={}){let r=D(e);t.delimiter??=`/#?`,t.prefixes??=`./`;let n=`[^${x(t.delimiter)}]+?`,c=[],l=0,f=0,i$1=new Set,o=a(u=>{if(f<r.length&&r[f].type===u)return r[f++].value},`tryConsume`),h$1=a(()=>o(`OTHER_MODIFIER`)??o(`ASTERISK`),`tryConsumeModifier`),p=a(u=>{let d$1=o(u);if(d$1!==void 0)return d$1;let{type:g,index:y$1}=r[f];throw TypeError(`Unexpected ${g} at ${y$1}, expected ${u}`)},`mustConsume`),A=a(()=>{let u=``,d$1;for(;d$1=o(`CHAR`)??o(`ESCAPED_CHAR`);)u+=d$1;return u},`consumeText`),xe=a(u=>u,`DefaultEncodePart`),N=t.encodePart||xe,H=``,$=a(u=>{H+=u},`appendToPendingFixedValue`),M=a(()=>{H.length&&(c.push(new P(3,``,``,N(H),``,3)),H=``)},`maybeAddPartFromPendingFixedValue`),X=a((u,d$1,g,y$1,Z)=>{let m$1=3;switch(Z){case`?`:m$1=1;break;case`*`:m$1=0;break;case`+`:m$1=2;break}if(!d$1&&!g&&m$1===3){$(u);return}if(M(),!d$1&&!g){if(!u)return;c.push(new P(3,``,``,N(u),``,m$1));return}let S;S=g?g===`*`?v:g:n;let k=2;S===n?(k=1,S=``):S===v&&(k=0,S=``);let E;if(d$1?E=d$1:g&&(E=l++),i$1.has(E))throw TypeError(`Duplicate name '${E}'.`);i$1.add(E),c.push(new P(k,E,N(u),S,N(y$1),m$1))},`addPart`);for(;f<r.length;){let u=o(`CHAR`),d$1=o(`NAME`),g=o(`REGEX`);if(!d$1&&!g&&(g=o(`ASTERISK`)),d$1||g){let m$1=u??``;t.prefixes.indexOf(m$1)===-1&&($(m$1),m$1=``),M();let S=h$1();X(m$1,d$1,g,``,S);continue}let y$1=u??o(`ESCAPED_CHAR`);if(y$1){$(y$1);continue}if(o(`OPEN`)){let m$1=A(),S=o(`NAME`),k=o(`REGEX`);!S&&!k&&(k=o(`ASTERISK`));let E=A();p(`CLOSE`);let be=h$1();X(m$1,S,k,E,be);continue}M(),p(`END`)}return c}function x(e){return e.replace(/([.+*?^${}()[\]|/\\])/g,`\\$1`)}function B(e){return e&&e.ignoreCase?`ui`:`u`}function q(e,t,r){return W(F(e,r),t,r)}function T(e){switch(e){case 0:return`*`;case 1:return`?`;case 2:return`+`;case 3:return``}}function W(e,t,r={}){r.delimiter??=`/#?`,r.prefixes??=`./`,r.sensitive??=!1,r.strict??=!1,r.end??=!0,r.start??=!0,r.endsWith=``;let n=r.start?`^`:``;for(let s$1 of e){if(s$1.type===3){s$1.modifier===3?n+=x(s$1.value):n+=`(?:${x(s$1.value)})${T(s$1.modifier)}`;continue}t&&t.push(s$1.name);let i$1=`[^${x(r.delimiter)}]+?`,o=s$1.value;if(s$1.type===1?o=i$1:s$1.type===0&&(o=v),!s$1.prefix.length&&!s$1.suffix.length){s$1.modifier===3||s$1.modifier===1?n+=`(${o})${T(s$1.modifier)}`:n+=`((?:${o})${T(s$1.modifier)})`;continue}if(s$1.modifier===3||s$1.modifier===1){n+=`(?:${x(s$1.prefix)}(${o})${x(s$1.suffix)})`,n+=T(s$1.modifier);continue}n+=`(?:${x(s$1.prefix)}`,n+=`((?:${o})(?:`,n+=x(s$1.suffix),n+=x(s$1.prefix),n+=`(?:${o}))*)${x(s$1.suffix)})`,s$1.modifier===0&&(n+=`?`)}let c=`[${x(r.endsWith)}]|$`,l=`[${x(r.delimiter)}]`;if(r.end)return r.strict||(n+=`${l}?`),r.endsWith.length?n+=`(?=${c})`:n+=`$`,new RegExp(n,B(r));r.strict||(n+=`(?:${l}(?=${c}))?`);let f=!1;if(e.length){let s$1=e[e.length-1];s$1.type===3&&s$1.modifier===3&&(f=r.delimiter.indexOf(s$1)>-1)}return f||(n+=`(?=${l}|${c})`),new RegExp(n,B(r))}function ee(e,t){return e.length?e[0]===`/`?!0:!t||e.length<2?!1:(e[0]==`\\`||e[0]==`{`)&&e[1]==`/`:!1}function te(e,t){return e.startsWith(t)?e.substring(t.length,e.length):e}function ke(e,t){return e.endsWith(t)?e.substr(0,e.length-t.length):e}function _(e){return!e||e.length<2?!1:e[0]===`[`||(e[0]===`\\`||e[0]===`{`)&&e[1]===`[`}function U(e){if(!e)return!0;for(let t of re)if(e.test(t))return!0;return!1}function ne(e,t){if(e=te(e,`#`),t||e===``)return e;let r=new URL(`https://example.com`);return r.hash=e,r.hash?r.hash.substring(1,r.hash.length):``}function se(e,t){if(e=te(e,`?`),t||e===``)return e;let r=new URL(`https://example.com`);return r.search=e,r.search?r.search.substring(1,r.search.length):``}function ie(e,t){return t||e===``?e:_(e)?K(e):j(e)}function ae(e,t){if(t||e===``)return e;let r=new URL(`https://example.com`);return r.password=e,r.password}function oe(e,t){if(t||e===``)return e;let r=new URL(`https://example.com`);return r.username=e,r.username}function ce(e,t,r){if(r||e===``)return e;if(t&&!re.includes(t))return new URL(`${t}:${e}`).pathname;let n=e[0]==`/`;return e=new URL(n?e:`/-`+e,`https://example.com`).pathname,n||(e=e.substring(2,e.length)),e}function le(e,t,r){return z$1(t)===e&&(e=``),r||e===``?e:G(e)}function fe(e,t){return e=ke(e,`:`),t||e===``?e:w$1(e)}function z$1(e){switch(e){case`ws`:case`http`:return`80`;case`wws`:case`https`:return`443`;case`ftp`:return`21`;default:return``}}function w$1(e){if(e===``)return e;if(/^[-+.A-Za-z0-9]*$/.test(e))return e.toLowerCase();throw TypeError(`Invalid protocol '${e}'.`)}function he(e){if(e===``)return e;let t=new URL(`https://example.com`);return t.username=e,t.username}function ue(e){if(e===``)return e;let t=new URL(`https://example.com`);return t.password=e,t.password}function j(e){if(e===``)return e;if(/[\t\n\r #%/:<>?@[\]^\\|]/g.test(e))throw TypeError(`Invalid hostname '${e}'`);let t=new URL(`https://example.com`);return t.hostname=e,t.hostname}function K(e){if(e===``)return e;if(/[^0-9a-fA-F[\]:]/g.test(e))throw TypeError(`Invalid IPv6 hostname '${e}'`);return e.toLowerCase()}function G(e){if(e===``||/^[0-9]*$/.test(e)&&parseInt(e)<=65535)return e;throw TypeError(`Invalid port '${e}'.`)}function de(e){if(e===``)return e;let t=new URL(`https://example.com`);return t.pathname=e[0]===`/`?e:`/-`+e,e[0]===`/`?t.pathname:t.pathname.substring(2,t.pathname.length)}function pe(e){return e===``?e:new URL(`data:${e}`).pathname}function ge(e){if(e===``)return e;let t=new URL(`https://example.com`);return t.search=e,t.search.substring(1,t.search.length)}function me(e){if(e===``)return e;let t=new URL(`https://example.com`);return t.hash=e,t.hash.substring(1,t.hash.length)}function Se(e,t){if(typeof e!=`string`)throw TypeError(`parameter 1 is not of type 'string'.`);let r=new URL(e,t);return{protocol:r.protocol.substring(0,r.protocol.length-1),username:r.username,password:r.password,hostname:r.hostname,port:r.port,pathname:r.pathname,search:r.search===``?void 0:r.search.substring(1,r.search.length),hash:r.hash===``?void 0:r.hash.substring(1,r.hash.length)}}function R(e,t){return t?I(e):e}function L(e,t,r){let n;if(typeof t.baseURL==`string`)try{n=new URL(t.baseURL),t.protocol===void 0&&(e.protocol=R(n.protocol.substring(0,n.protocol.length-1),r)),!r&&t.protocol===void 0&&t.hostname===void 0&&t.port===void 0&&t.username===void 0&&(e.username=R(n.username,r)),!r&&t.protocol===void 0&&t.hostname===void 0&&t.port===void 0&&t.username===void 0&&t.password===void 0&&(e.password=R(n.password,r)),t.protocol===void 0&&t.hostname===void 0&&(e.hostname=R(n.hostname,r)),t.protocol===void 0&&t.hostname===void 0&&t.port===void 0&&(e.port=R(n.port,r)),t.protocol===void 0&&t.hostname===void 0&&t.port===void 0&&t.pathname===void 0&&(e.pathname=R(n.pathname,r)),t.protocol===void 0&&t.hostname===void 0&&t.port===void 0&&t.pathname===void 0&&t.search===void 0&&(e.search=R(n.search.substring(1,n.search.length),r)),t.protocol===void 0&&t.hostname===void 0&&t.port===void 0&&t.pathname===void 0&&t.search===void 0&&t.hash===void 0&&(e.hash=R(n.hash.substring(1,n.hash.length),r))}catch{throw TypeError(`invalid baseURL '${t.baseURL}'.`)}if(typeof t.protocol==`string`&&(e.protocol=fe(t.protocol,r)),typeof t.username==`string`&&(e.username=oe(t.username,r)),typeof t.password==`string`&&(e.password=ae(t.password,r)),typeof t.hostname==`string`&&(e.hostname=ie(t.hostname,r)),typeof t.port==`string`&&(e.port=le(t.port,e.protocol,r)),typeof t.pathname==`string`){if(e.pathname=t.pathname,n&&!ee(e.pathname,r)){let c=n.pathname.lastIndexOf(`/`);c>=0&&(e.pathname=R(n.pathname.substring(0,c+1),r)+e.pathname)}e.pathname=ce(e.pathname,e.protocol,r)}return typeof t.search==`string`&&(e.search=se(t.search,r)),typeof t.hash==`string`&&(e.hash=ne(t.hash,r)),e}function I(e){return e.replace(/([+*?:{}()\\])/g,`\\$1`)}function Te(e){return e.replace(/([.+*?^${}()[\]|/\\])/g,`\\$1`)}function Ae(e,t){t.delimiter??=`/#?`,t.prefixes??=`./`,t.sensitive??=!1,t.strict??=!1,t.end??=!0,t.start??=!0,t.endsWith=``;let r=`.*`,n=`[^${Te(t.delimiter)}]+?`,c=/[$_\u200C\u200D\p{ID_Continue}]/u,l=``;for(let f=0;f<e.length;++f){let s$1=e[f];if(s$1.type===3){if(s$1.modifier===3){l+=I(s$1.value);continue}l+=`{${I(s$1.value)}}${T(s$1.modifier)}`;continue}let i$1=s$1.hasCustomName(),o=!!s$1.suffix.length||!!s$1.prefix.length&&(s$1.prefix.length!==1||!t.prefixes.includes(s$1.prefix)),h$1=f>0?e[f-1]:null,p=f<e.length-1?e[f+1]:null;if(!o&&i$1&&s$1.type===1&&s$1.modifier===3&&p&&!p.prefix.length&&!p.suffix.length)if(p.type===3){let A=p.value.length>0?p.value[0]:``;o=c.test(A)}else o=!p.hasCustomName();if(!o&&!s$1.prefix.length&&h$1&&h$1.type===3){let A=h$1.value[h$1.value.length-1];o=t.prefixes.includes(A)}o&&(l+=`{`),l+=I(s$1.prefix),i$1&&(l+=`:${s$1.name}`),s$1.type===2?l+=`(${s$1.value})`:s$1.type===1?i$1||(l+=`(${n})`):s$1.type===0&&(!i$1&&(!h$1||h$1.type===3||h$1.modifier!==3||o||s$1.prefix!==``)?l+=`*`:l+=`(.*)`),s$1.type===1&&i$1&&s$1.suffix.length&&c.test(s$1.suffix[0])&&(l+=`\\`),l+=I(s$1.suffix),o&&(l+=`}`),s$1.modifier!==3&&(l+=T(s$1.modifier))}return l}var Pe,a,P,Re,Ee,v,b,J,Q,re,C,V,O,Y,init_urlpattern=__esmMin((()=>{Pe=Object.defineProperty,a=(e,t)=>Pe(e,`name`,{value:t,configurable:!0}),P=class{type=3;name=``;prefix=``;value=``;suffix=``;modifier=3;constructor(t,r,n,c,l,f){this.type=t,this.name=r,this.prefix=n,this.value=c,this.suffix=l,this.modifier=f}hasCustomName(){return this.name!==``&&typeof this.name!=`number`}},a(P,`Part`),Re=/[$_\p{ID_Start}]/u,Ee=/[$_\u200C\u200D\p{ID_Continue}]/u,v=`.*`,a(Oe,`isASCII`),a(D,`lexer`),a(F,`parse`),a(x,`escapeString`),a(B,`flags`),a(q,`stringToRegexp`),a(T,`modifierToString`),a(W,`partsToRegexp`),b={delimiter:``,prefixes:``,sensitive:!0,strict:!0},J={delimiter:`.`,prefixes:``,sensitive:!0,strict:!0},Q={delimiter:`/`,prefixes:`/`,sensitive:!0,strict:!0},a(ee,`isAbsolutePathname`),a(te,`maybeStripPrefix`),a(ke,`maybeStripSuffix`),a(_,`treatAsIPv6Hostname`),re=[`ftp`,`file`,`http`,`https`,`ws`,`wss`],a(U,`isSpecialScheme`),a(ne,`canonicalizeHash`),a(se,`canonicalizeSearch`),a(ie,`canonicalizeHostname`),a(ae,`canonicalizePassword`),a(oe,`canonicalizeUsername`),a(ce,`canonicalizePathname`),a(le,`canonicalizePort`),a(fe,`canonicalizeProtocol`),a(z$1,`defaultPortForProtocol`),a(w$1,`protocolEncodeCallback`),a(he,`usernameEncodeCallback`),a(ue,`passwordEncodeCallback`),a(j,`hostnameEncodeCallback`),a(K,`ipv6HostnameEncodeCallback`),a(G,`portEncodeCallback`),a(de,`standardURLPathnameEncodeCallback`),a(pe,`pathURLPathnameEncodeCallback`),a(ge,`searchEncodeCallback`),a(me,`hashEncodeCallback`),C=class{#i;#n=[];#t={};#e=0;#s=1;#l=0;#o=0;#d=0;#p=0;#g=!1;constructor(t){this.#i=t}get result(){return this.#t}parse(){for(this.#n=D(this.#i,!0);this.#e<this.#n.length;this.#e+=this.#s){if(this.#s=1,this.#n[this.#e].type===`END`){if(this.#o===0){this.#b(),this.#f()?this.#r(9,1):this.#h()?this.#r(8,1):this.#r(7,0);continue}else if(this.#o===2){this.#u(5);continue}this.#r(10,0);break}if(this.#d>0)if(this.#A())--this.#d;else continue;if(this.#T()){this.#d+=1;continue}switch(this.#o){case 0:this.#P()&&this.#u(1);break;case 1:if(this.#P()){this.#C();let t=7,r=1;this.#E()?(t=2,r=3):this.#g&&(t=2),this.#r(t,r)}break;case 2:this.#S()?this.#u(3):(this.#x()||this.#h()||this.#f())&&this.#u(5);break;case 3:this.#O()?this.#r(4,1):this.#S()&&this.#r(5,1);break;case 4:this.#S()&&this.#r(5,1);break;case 5:this.#y()?this.#p+=1:this.#w()&&--this.#p,this.#k()&&!this.#p?this.#r(6,1):this.#x()?this.#r(7,0):this.#h()?this.#r(8,1):this.#f()&&this.#r(9,1);break;case 6:this.#x()?this.#r(7,0):this.#h()?this.#r(8,1):this.#f()&&this.#r(9,1);break;case 7:this.#h()?this.#r(8,1):this.#f()&&this.#r(9,1);break;case 8:this.#f()&&this.#r(9,1);break;case 9:break;case 10:break}}this.#t.hostname!==void 0&&this.#t.port===void 0&&(this.#t.port=``)}#r(t,r){switch(this.#o){case 0:break;case 1:this.#t.protocol=this.#c();break;case 2:break;case 3:this.#t.username=this.#c();break;case 4:this.#t.password=this.#c();break;case 5:this.#t.hostname=this.#c();break;case 6:this.#t.port=this.#c();break;case 7:this.#t.pathname=this.#c();break;case 8:this.#t.search=this.#c();break;case 9:this.#t.hash=this.#c();break;case 10:break}this.#o!==0&&t!==10&&([1,2,3,4].includes(this.#o)&&[6,7,8,9].includes(t)&&(this.#t.hostname??=``),[1,2,3,4,5,6].includes(this.#o)&&[8,9].includes(t)&&(this.#t.pathname??=this.#g?`/`:``),[1,2,3,4,5,6,7].includes(this.#o)&&t===9&&(this.#t.search??=``)),this.#R(t,r)}#R(t,r){this.#o=t,this.#l=this.#e+r,this.#e+=r,this.#s=0}#b(){this.#e=this.#l,this.#s=0}#u(t){this.#b(),this.#o=t}#m(t){return t<0&&(t=this.#n.length-t),t<this.#n.length?this.#n[t]:this.#n[this.#n.length-1]}#a(t,r){let n=this.#m(t);return n.value===r&&(n.type===`CHAR`||n.type===`ESCAPED_CHAR`||n.type===`INVALID_CHAR`)}#P(){return this.#a(this.#e,`:`)}#E(){return this.#a(this.#e+1,`/`)&&this.#a(this.#e+2,`/`)}#S(){return this.#a(this.#e,`@`)}#O(){return this.#a(this.#e,`:`)}#k(){return this.#a(this.#e,`:`)}#x(){return this.#a(this.#e,`/`)}#h(){if(this.#a(this.#e,`?`))return!0;if(this.#n[this.#e].value!==`?`)return!1;let t=this.#m(this.#e-1);return t.type!==`NAME`&&t.type!==`REGEX`&&t.type!==`CLOSE`&&t.type!==`ASTERISK`}#f(){return this.#a(this.#e,`#`)}#T(){return this.#n[this.#e].type==`OPEN`}#A(){return this.#n[this.#e].type==`CLOSE`}#y(){return this.#a(this.#e,`[`)}#w(){return this.#a(this.#e,`]`)}#c(){let t=this.#n[this.#e],r=this.#m(this.#l).index;return this.#i.substring(r,t.index)}#C(){let t={};Object.assign(t,b),t.encodePart=w$1;let r=q(this.#c(),void 0,t);this.#g=U(r)}},a(C,`Parser`),V=[`protocol`,`username`,`password`,`hostname`,`port`,`pathname`,`search`,`hash`],O=`*`,a(Se,`extractValues`),a(R,`processBaseURLString`),a(L,`applyInit`),a(I,`escapePatternString`),a(Te,`escapeRegexpString`),a(Ae,`partsToPattern`),Y=class{#i;#n={};#t={};#e={};#s={};#l=!1;constructor(t={},r,n){try{let c;if(typeof r==`string`?c=r:n=r,typeof t==`string`){let i$1=new C(t);if(i$1.parse(),t=i$1.result,c===void 0&&typeof t.protocol!=`string`)throw TypeError(`A base URL must be provided for a relative constructor string.`);t.baseURL=c}else{if(!t||typeof t!=`object`)throw TypeError(`parameter 1 is not of type 'string' and cannot convert to dictionary.`);if(c)throw TypeError(`parameter 1 is not of type 'string'.`)}typeof n>`u`&&(n={ignoreCase:!1});let l={ignoreCase:n.ignoreCase===!0};this.#i=L({pathname:O,protocol:O,username:O,password:O,hostname:O,port:O,search:O,hash:O},t,!0),z$1(this.#i.protocol)===this.#i.port&&(this.#i.port=``);let s$1;for(s$1 of V){if(!(s$1 in this.#i))continue;let i$1={},o=this.#i[s$1];switch(this.#t[s$1]=[],s$1){case`protocol`:Object.assign(i$1,b),i$1.encodePart=w$1;break;case`username`:Object.assign(i$1,b),i$1.encodePart=he;break;case`password`:Object.assign(i$1,b),i$1.encodePart=ue;break;case`hostname`:Object.assign(i$1,J),_(o)?i$1.encodePart=K:i$1.encodePart=j;break;case`port`:Object.assign(i$1,b),i$1.encodePart=G;break;case`pathname`:U(this.#n.protocol)?(Object.assign(i$1,Q,l),i$1.encodePart=de):(Object.assign(i$1,b,l),i$1.encodePart=pe);break;case`search`:Object.assign(i$1,b,l),i$1.encodePart=ge;break;case`hash`:Object.assign(i$1,b,l),i$1.encodePart=me;break}try{this.#s[s$1]=F(o,i$1),this.#n[s$1]=W(this.#s[s$1],this.#t[s$1],i$1),this.#e[s$1]=Ae(this.#s[s$1],i$1),this.#l=this.#l||this.#s[s$1].some(h$1=>h$1.type===2)}catch{throw TypeError(`invalid ${s$1} pattern '${this.#i[s$1]}'.`)}}}catch(c){throw TypeError(`Failed to construct 'URLPattern': ${c.message}`)}}get[Symbol.toStringTag](){return`URLPattern`}test(t={},r){let n={pathname:``,protocol:``,username:``,password:``,hostname:``,port:``,search:``,hash:``};if(typeof t!=`string`&&r)throw TypeError(`parameter 1 is not of type 'string'.`);if(typeof t>`u`)return!1;try{n=typeof t==`object`?L(n,t,!1):L(n,Se(t,r),!1)}catch{return!1}let c;for(c of V)if(!this.#n[c].exec(n[c]))return!1;return!0}exec(t={},r){let n={pathname:``,protocol:``,username:``,password:``,hostname:``,port:``,search:``,hash:``};if(typeof t!=`string`&&r)throw TypeError(`parameter 1 is not of type 'string'.`);if(typeof t>`u`)return;try{n=typeof t==`object`?L(n,t,!1):L(n,Se(t,r),!1)}catch{return null}let c={};r?c.inputs=[t,r]:c.inputs=[t];let l;for(l of V){let f=this.#n[l].exec(n[l]);if(!f)return null;let s$1={};for(let[i$1,o]of this.#t[l].entries())(typeof o==`string`||typeof o==`number`)&&(s$1[o]=f[i$1+1]);c[l]={input:n[l]??``,groups:s$1}}return c}static compareComponent(t,r,n){let c=a((i$1,o)=>{for(let h$1 of[`type`,`modifier`,`prefix`,`value`,`suffix`]){if(i$1[h$1]<o[h$1])return-1;if(i$1[h$1]!==o[h$1])return 1}return 0},`comparePart`),l=new P(3,``,``,``,``,3),f=new P(0,``,``,``,``,3),s$1=a((i$1,o)=>{let h$1=0;for(;h$1<Math.min(i$1.length,o.length);++h$1){let p=c(i$1[h$1],o[h$1]);if(p)return p}return i$1.length===o.length?0:c(i$1[h$1]??l,o[h$1]??l)},`comparePartList`);return!r.#e[t]&&!n.#e[t]?0:r.#e[t]&&!n.#e[t]?s$1(r.#s[t],[f]):!r.#e[t]&&n.#e[t]?s$1([f],n.#s[t]):s$1(r.#s[t],n.#s[t])}get protocol(){return this.#e.protocol}get username(){return this.#e.username}get password(){return this.#e.password}get hostname(){return this.#e.hostname}get port(){return this.#e.port}get pathname(){return this.#e.pathname}get search(){return this.#e.search}get hash(){return this.#e.hash}get hasRegExpGroups(){return this.#l}},a(Y,`URLPattern`)})),urlpattern_polyfill_exports=__export$3({URLPattern:()=>Y}),init_urlpattern_polyfill=__esmMin((()=>{init_urlpattern(),globalThis.URLPattern||(globalThis.URLPattern=Y)})),require_sbmh=__commonJSMin(((exports,module)=>{let{EventEmitter:EventEmitter$2}=__require(`node:events`),{inherits:inherits$5}=__require(`node:util`);function SBMH(needle){if(typeof needle==`string`&&(needle=Buffer.from(needle)),!Buffer.isBuffer(needle))throw TypeError(`The needle has to be a String or a Buffer.`);let needleLength=needle.length,needleLastCharIndex=needleLength-1;if(needleLength===0)throw Error(`The needle cannot be an empty String/Buffer.`);if(needleLength>256)throw Error(`The needle cannot have a length bigger than 256.`);this.maxMatches=1/0,this.matches=0,this._occ=new Uint8Array(256).fill(needleLength),this._lookbehind_size=0,this._needle=needle,this._bufpos=0,this._lookbehind=Buffer.alloc(needleLastCharIndex);for(var i$1=0;i$1<needleLastCharIndex;++i$1)this._occ[needle[i$1]]=needleLastCharIndex-i$1}inherits$5(SBMH,EventEmitter$2),SBMH.prototype.reset=function(){this._lookbehind_size=0,this.matches=0,this._bufpos=0},SBMH.prototype.push=function(chunk,pos){Buffer.isBuffer(chunk)||(chunk=Buffer.from(chunk,`binary`));let chlen=chunk.length;this._bufpos=pos||0;let r;for(;r!==chlen&&this.matches<this.maxMatches;)r=this._sbmh_feed(chunk);return r},SBMH.prototype._sbmh_feed=function(data){let len=data.length,needle=this._needle,needleLength=needle.length,needleLastCharIndex=needleLength-1,needleLastChar=needle[needleLastCharIndex],pos=-this._lookbehind_size,ch;if(pos<0){for(;pos<0&&pos<=len-needleLength;){if(ch=data[pos+needleLastCharIndex],ch===needleLastChar&&this._sbmh_memcmp(data,pos,needleLastCharIndex))return this._lookbehind_size=0,++this.matches,this.emit(`info`,!0),this._bufpos=pos+needleLength;pos+=this._occ[ch]}for(;pos<0&&!this._sbmh_memcmp(data,pos,len-pos);)++pos;if(pos>=0)this.emit(`info`,!1,this._lookbehind,0,this._lookbehind_size),this._lookbehind_size=0;else{let bytesToCutOff=this._lookbehind_size+pos;return bytesToCutOff>0&&this.emit(`info`,!1,this._lookbehind,0,bytesToCutOff),this._lookbehind_size-=bytesToCutOff,this._lookbehind.copy(this._lookbehind,0,bytesToCutOff,this._lookbehind_size),data.copy(this._lookbehind,this._lookbehind_size),this._lookbehind_size+=len,this._bufpos=len,len}}if(pos=data.indexOf(needle,pos+this._bufpos),pos!==-1)return++this.matches,pos===0?this.emit(`info`,!0):this.emit(`info`,!0,data,this._bufpos,pos),this._bufpos=pos+needleLength;for(pos=len-needleLastCharIndex,pos<0&&(pos=0);pos!==len&&(data[pos]!==needle[0]||Buffer.compare(data.subarray(pos+1,len),needle.subarray(1,len-pos))!==0);)++pos;return pos!==len&&(data.copy(this._lookbehind,0,pos,len),this._lookbehind_size=len-pos),pos!==0&&this.emit(`info`,!1,data,this._bufpos,pos),this._bufpos=len,len},SBMH.prototype._sbmh_lookup_char=function(data,pos){return pos<0?this._lookbehind[this._lookbehind_size+pos]:data[pos]},SBMH.prototype._sbmh_memcmp=function(data,pos,len){for(var i$1=0;i$1<len;++i$1)if(this._sbmh_lookup_char(data,pos+i$1)!==this._needle[i$1])return!1;return!0},module.exports=SBMH})),require_PartStream=__commonJSMin(((exports,module)=>{let inherits$4=__require(`node:util`).inherits,ReadableStream$1=__require(`node:stream`).Readable;function PartStream$1(opts){ReadableStream$1.call(this,opts)}inherits$4(PartStream$1,ReadableStream$1),PartStream$1.prototype._read=function(n){},module.exports=PartStream$1})),require_getLimit=__commonJSMin(((exports,module)=>{module.exports=function(limits,name$2,defaultLimit){if(!limits||limits[name$2]===void 0||limits[name$2]===null)return defaultLimit;if(typeof limits[name$2]!=`number`||isNaN(limits[name$2]))throw TypeError(`Limit `+name$2+` is not a valid number`);return limits[name$2]}})),require_HeaderParser=__commonJSMin(((exports,module)=>{let EventEmitter$1=__require(`node:events`).EventEmitter,inherits$3=__require(`node:util`).inherits,getLimit$2=require_getLimit(),StreamSearch$1=require_sbmh(),B_DCRLF=Buffer.from(`\r
|
|
28
28
|
\r
|
|
29
29
|
`),RE_CRLF=/\r\n/g,RE_HDR=/^([^:]+):[ \t]?([\x00-\xFF]+)?$/;function HeaderParser$1(cfg){EventEmitter$1.call(this),cfg||={};let self$1=this;this.nread=0,this.maxed=!1,this.npairs=0,this.maxHeaderPairs=getLimit$2(cfg,`maxHeaderPairs`,2e3),this.maxHeaderSize=getLimit$2(cfg,`maxHeaderSize`,80*1024),this.buffer=``,this.header={},this.finished=!1,this.ss=new StreamSearch$1(B_DCRLF),this.ss.on(`info`,function(isMatch,data,start,end){data&&!self$1.maxed&&(self$1.nread+end-start>=self$1.maxHeaderSize?(end=self$1.maxHeaderSize-self$1.nread+start,self$1.nread=self$1.maxHeaderSize,self$1.maxed=!0):self$1.nread+=end-start,self$1.buffer+=data.toString(`binary`,start,end)),isMatch&&self$1._finish()})}inherits$3(HeaderParser$1,EventEmitter$1),HeaderParser$1.prototype.push=function(data){let r=this.ss.push(data);if(this.finished)return r},HeaderParser$1.prototype.reset=function(){this.finished=!1,this.buffer=``,this.header={},this.ss.reset()},HeaderParser$1.prototype._finish=function(){this.buffer&&this._parseHeader(),this.ss.matches=this.ss.maxMatches;let header=this.header;this.header={},this.buffer=``,this.finished=!0,this.nread=this.npairs=0,this.maxed=!1,this.emit(`header`,header)},HeaderParser$1.prototype._parseHeader=function(){if(this.npairs===this.maxHeaderPairs)return;let lines=this.buffer.split(RE_CRLF),len=lines.length,m$1,h$1;for(var i$1=0;i$1<len;++i$1){if(lines[i$1].length===0)continue;if((lines[i$1][0]===` `||lines[i$1][0]===` `)&&h$1){this.header[h$1][this.header[h$1].length-1]+=lines[i$1];continue}let posColon=lines[i$1].indexOf(`:`);if(posColon===-1||posColon===0)return;if(m$1=RE_HDR.exec(lines[i$1]),h$1=m$1[1].toLowerCase(),this.header[h$1]=this.header[h$1]||[],this.header[h$1].push(m$1[2]||``),++this.npairs===this.maxHeaderPairs)break}},module.exports=HeaderParser$1})),require_Dicer=__commonJSMin(((exports,module)=>{let WritableStream$1=__require(`node:stream`).Writable,inherits$2=__require(`node:util`).inherits,StreamSearch=require_sbmh(),PartStream=require_PartStream(),HeaderParser=require_HeaderParser(),DASH=45,B_ONEDASH=Buffer.from(`-`),B_CRLF=Buffer.from(`\r
|
|
30
30
|
`),EMPTY_FN=function(){};function Dicer$2(cfg){if(!(this instanceof Dicer$2))return new Dicer$2(cfg);if(WritableStream$1.call(this,cfg),!cfg||!cfg.headerFirst&&typeof cfg.boundary!=`string`)throw TypeError(`Boundary required`);typeof cfg.boundary==`string`?this.setBoundary(cfg.boundary):this._bparser=void 0,this._headerFirst=cfg.headerFirst,this._dashes=0,this._parts=0,this._finished=!1,this._realFinish=!1,this._isPreamble=!0,this._justMatched=!1,this._firstWrite=!0,this._inHeader=!0,this._part=void 0,this._cb=void 0,this._ignoreData=!1,this._partOpts={highWaterMark:cfg.partHwm},this._pause=!1;let self$1=this;this._hparser=new HeaderParser(cfg),this._hparser.on(`header`,function(header){self$1._inHeader=!1,self$1._part.emit(`header`,header)})}inherits$2(Dicer$2,WritableStream$1),Dicer$2.prototype.emit=function(ev){if(ev===`finish`&&!this._realFinish){if(!this._finished){let self$1=this;process.nextTick(function(){if(self$1.emit(`error`,Error(`Unexpected end of multipart data`)),self$1._part&&!self$1._ignoreData){let type=self$1._isPreamble?`Preamble`:`Part`;self$1._part.emit(`error`,Error(type+` terminated early due to unexpected end of multipart data`)),self$1._part.push(null),process.nextTick(function(){self$1._realFinish=!0,self$1.emit(`finish`),self$1._realFinish=!1});return}self$1._realFinish=!0,self$1.emit(`finish`),self$1._realFinish=!1})}}else WritableStream$1.prototype.emit.apply(this,arguments)},Dicer$2.prototype._write=function(data,encoding,cb){if(!this._hparser&&!this._bparser)return cb();if(this._headerFirst&&this._isPreamble){this._part||(this._part=new PartStream(this._partOpts),this.listenerCount(`preamble`)===0?this._ignore():this.emit(`preamble`,this._part));let r=this._hparser.push(data);if(!this._inHeader&&r!==void 0&&r<data.length)data=data.slice(r);else return cb()}this._firstWrite&&=(this._bparser.push(B_CRLF),!1),this._bparser.push(data),this._pause?this._cb=cb:cb()},Dicer$2.prototype.reset=function(){this._part=void 0,this._bparser=void 0,this._hparser=void 0},Dicer$2.prototype.setBoundary=function(boundary){let self$1=this;this._bparser=new StreamSearch(`\r
|