@stacksjs/orm 0.70.44 → 0.70.53
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/LICENSE.md +21 -0
- package/dist/index.js +27 -133
- package/dist/src/auto-crud.d.ts +225 -0
- package/dist/src/define-model.d.ts +59 -3
- package/dist/src/generate-database-schema.d.ts +23 -0
- package/dist/src/index.d.ts +143 -81
- package/dist/src/model-types.d.ts +53 -4
- package/dist/src/paginator-request.d.ts +68 -0
- package/dist/src/paginator.d.ts +99 -0
- package/dist/src/traits/audit.d.ts +22 -5
- package/dist/src/traits/billable.d.ts +36 -0
- package/dist/src/traits/categorizable.d.ts +4 -0
- package/dist/src/types.d.ts +9 -5
- package/dist/src/utils.d.ts +1 -1
- package/package.json +11 -7
package/dist/index.js
CHANGED
|
@@ -1,137 +1,31 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
var Tz=Object.defineProperty;var Wz=(_)=>_;function Kz(_,k){this[_]=Wz.bind(null,k)}var X9=(_,k)=>{for(var j in k)Tz(_,j,{get:k[j],enumerable:!0,configurable:!0,set:Kz.bind(k,j)})};var R=(_,k)=>()=>(_&&(k=_(_=0)),k);var s=import.meta.require;function H6(_){return _&&typeof _==="object"&&s8.some((k)=>Object.prototype.hasOwnProperty.call(_,k))}function _j(_){return nQ(_)}function q6(_){return encodeURIComponent(_).replace(/!/g,"%21").replace(/\*/g,"%2A").replace(/\(/g,"%28").replace(/\)/g,"%29").replace(/'/g,"%27").replace(/%5B/g,"[").replace(/%5D/g,"]")}function KQ(_){if(_ instanceof Date)return Math.floor(_.getTime()/1000).toString();if(_===null)return"";return String(_)}function nQ(_){let k=[];function j(d,O){if(O===void 0)return;if(O===null||typeof O!=="object"||O instanceof Date){k.push(q6(d)+"="+q6(KQ(O)));return}if(Array.isArray(O)){for(let $=0;$<O.length;$++)if(O[$]!==void 0)j(d+"["+$+"]",O[$]);return}for(let $ of Object.keys(O))j(d+"["+$+"]",O[$])}if(typeof _==="object"&&_!==null)for(let d of Object.keys(_))j(d,_[d]);return k.join("&")}function JQ(_){return["number","string","boolean"].includes(typeof _)}function b6(_){let k=_.match(/\{\w+\}/g);if(!k)return[];return k.map((j)=>j.replace(/[{}]/g,""))}function sj(_){if(!Array.isArray(_)||!_[0]||typeof _[0]!=="object")return{};if(!H6(_[0]))return _.shift();let k=Object.keys(_[0]),j=k.filter((d)=>s8.includes(d));if(j.length>0&&j.length!==k.length)r1(`Options found in arguments (${j.join(", ")}). Did you mean to pass an options object? See https://github.com/stripe/stripe-node/wiki/Passing-Options.`);return{}}function W0(_){let k={host:null,headers:{},settings:{},streaming:!1};if(_.length>0){let j=_[_.length-1];if(typeof j==="string")k.authenticator=V0(_.pop());else if(H6(j)){let d={..._.pop()},O=Object.keys(d).filter(($)=>!s8.includes($));if(O.length)r1(`Invalid options found (${O.join(", ")}); ignoring.`);if(d.apiKey)k.authenticator=V0(d.apiKey);if(d.idempotencyKey)k.headers["Idempotency-Key"]=d.idempotencyKey;if(d.stripeAccount)k.headers["Stripe-Account"]=d.stripeAccount;if(d.stripeContext){if(k.headers["Stripe-Account"])throw Error("Can't specify both stripeAccount and stripeContext.");k.headers["Stripe-Context"]=d.stripeContext}if(d.apiVersion)k.headers["Stripe-Version"]=d.apiVersion;if(Number.isInteger(d.maxNetworkRetries))k.settings.maxNetworkRetries=d.maxNetworkRetries;if(Number.isInteger(d.timeout))k.settings.timeout=d.timeout;if(d.host)k.host=d.host;if(d.authenticator){if(d.apiKey)throw Error("Can't specify both apiKey and authenticator.");if(typeof d.authenticator!=="function")throw Error("The authenticator must be a function receiving a request as the first parameter.");k.authenticator=d.authenticator}if(d.headers)Object.assign(k.headers,d.headers);if(d.additionalHeaders)Object.assign(k.headers,d.additionalHeaders);if(d.streaming)k.streaming=!0}}return k}function N6(_){let k=this,j=Object.prototype.hasOwnProperty.call(_,"constructor")?_.constructor:function(...d){k.apply(this,d)};return Object.assign(j,k),j.prototype=Object.create(k.prototype),Object.assign(j.prototype,_),j}function K0(_){if(typeof _!=="object")throw Error("Argument must be an object");return Object.keys(_).reduce((k,j)=>{if(_[j]!=null)k[j]=_[j];return k},{})}function x6(_){if(!(_&&typeof _==="object"))return _;return Object.keys(_).reduce((k,j)=>{return k[IQ(j)]=_[j],k},{})}function IQ(_){return _.split("-").map((k)=>k.charAt(0).toUpperCase()+k.substr(1).toLowerCase()).join("-")}function o1(_,k){if(k)return _.then((j)=>{setTimeout(()=>{k(null,j)},0)},(j)=>{setTimeout(()=>{k(j,null)},0)});return _}function i6(_){if(_==="OAuth")return"oauth";else return _[0].toLowerCase()+_.substring(1)}function r1(_){if(typeof process.emitWarning!=="function")return console.warn(`Stripe: ${_}`);return process.emitWarning(_,"Stripe")}function DQ(_){let k=typeof _;return(k==="function"||k==="object")&&!!_}function B6(_){let k={},j=(d,O)=>{Object.entries(d).forEach(([$,Z])=>{let X=O?`${O}[${$}]`:$;if(DQ(Z))if(!(Z instanceof Uint8Array)&&!Object.prototype.hasOwnProperty.call(Z,"data"))return j(Z,X);else k[X]=Z;else k[X]=String(Z)})};return j(_,null),k}function n0(_,k,j){if(!Number.isInteger(k))if(j!==void 0)return j;else throw Error(`${_} must be an integer`);return k}function c6(){return typeof process>"u"?{}:{lang_version:process.version}}function y6(_){for(let[k,j]of RQ)if(_[k])return j;return""}function V0(_){let k=(j)=>{return j.headers.Authorization="Bearer "+_,Promise.resolve()};return k._apiKey=_,k}function wQ(_,k){if(this[_]instanceof Date)return Math.floor(this[_].getTime()/1000).toString();return k}function v6(_){return JSON.stringify(_,wQ)}function J0(_){if(!_)return"v1";return _.startsWith("/v2")?"v2":"v1"}function I0(_){if(Array.isArray(_))return _.join(", ");return String(_)}function A6(_){let k=Array.isArray(_)?_[0]:_;return Number(k)}function m6(_){return Object.entries(_).map(([k,j])=>{return[k,I0(j)]})}var s8,T0,RQ;var ck=R(()=>{s8=["apiKey","idempotencyKey","stripeAccount","apiVersion","maxNetworkRetries","timeout","host","authenticator","stripeContext","headers","additionalHeaders","streaming"];T0=(()=>{let _={"\n":"\\n",'"':"\\\"","\u2028":"\\u2028","\u2029":"\\u2029"};return(k)=>{let j=k.replace(/["\n\r\u2028\u2029]/g,(d)=>_[d]);return(d)=>{return j.replace(/\{([\s\S]+?)\}/g,(O,$)=>{let Z=d[$];if(JQ(Z))return encodeURIComponent(Z);return""})}}})();RQ=[["ANTIGRAVITY_CLI_ALIAS","antigravity"],["CLAUDECODE","claude_code"],["CLINE_ACTIVE","cline"],["CODEX_SANDBOX","codex_cli"],["CODEX_THREAD_ID","codex_cli"],["CODEX_SANDBOX_NETWORK_DISABLED","codex_cli"],["CODEX_CI","codex_cli"],["CURSOR_AGENT","cursor"],["GEMINI_CLI","gemini_cli"],["OPENCLAW_SHELL","openclaw"],["OPENCODE","open_code"]]});class t_{getClientName(){throw Error("getClientName not implemented.")}makeRequest(_,k,j,d,O,$,Z,X){throw Error("makeRequest not implemented.")}static makeTimeoutError(){let _=TypeError(t_.TIMEOUT_ERROR_CODE);return _.code=t_.TIMEOUT_ERROR_CODE,_}}class t1{constructor(_,k){this._statusCode=_,this._headers=k}getStatusCode(){return this._statusCode}getHeaders(){return this._headers}getRawResponse(){throw Error("getRawResponse not implemented.")}toStream(_){throw Error("toStream not implemented.")}toJSON(){throw Error("toJSON not implemented.")}}var D0=R(()=>{t_.CONNECTION_CLOSED_ERROR_CODES=["ECONNRESET","EPIPE"];t_.TIMEOUT_ERROR_CODE="ETIMEDOUT"});var a1,o8;var g6=R(()=>{ck();D0();a1=class a1 extends t_{constructor(_){super();if(!_){if(!globalThis.fetch)throw Error("fetch() function not provided and is not defined in the global scope. You must provide a fetch implementation.");_=globalThis.fetch}if(globalThis.AbortController)this._fetchFn=a1.makeFetchWithAbortTimeout(_);else this._fetchFn=a1.makeFetchWithRaceTimeout(_)}static makeFetchWithRaceTimeout(_){return(k,j,d)=>{let O,$=new Promise((X,E)=>{O=setTimeout(()=>{O=null,E(t_.makeTimeoutError())},d)}),Z=_(k,j);return Promise.race([Z,$]).finally(()=>{if(O)clearTimeout(O)})}}static makeFetchWithAbortTimeout(_){return async(k,j,d)=>{let O=new AbortController,$=setTimeout(()=>{$=null,O.abort(t_.makeTimeoutError())},d);try{return await _(k,{...j,signal:O.signal})}catch(Z){if(Z.name==="AbortError")throw t_.makeTimeoutError();else throw Z}finally{if($)clearTimeout($)}}}getClientName(){return"fetch"}async makeRequest(_,k,j,d,O,$,Z,X){let F=new URL(j,`${Z==="http"?"http":"https"}://${_}`);F.port=k;let G=d=="POST"||d=="PUT"||d=="PATCH",Y=$||(G?"":void 0),S=await this._fetchFn(F.toString(),{method:d,headers:m6(O),body:Y},X);return new o8(S)}};o8=class o8 extends t1{constructor(_){super(_.status,o8._transformHeadersToObject(_.headers));this._res=_}getRawResponse(){return this._res}toStream(_){return _(),this._res.body}toJSON(){return this._res.json()}static _transformHeadersToObject(_){let k={};for(let j of _){if(!Array.isArray(j)||j.length!=2)throw Error("Response objects produced by the fetch function given to FetchHttpClient do not have an iterable headers map. Response#headers should be an iterable object.");k[j[0]]=j[1]}return k}}});class e1{computeHMACSignature(_,k){throw Error("computeHMACSignature not implemented.")}computeHMACSignatureAsync(_,k){throw Error("computeHMACSignatureAsync not implemented.")}computeSHA256Async(_){throw Error("computeSHA256 not implemented.")}}var _d;var R0=R(()=>{_d=class _d extends Error{}});var t8,r8;var u6=R(()=>{R0();t8=class t8 extends e1{constructor(_){super();this.subtleCrypto=_||crypto.subtle}computeHMACSignature(_,k){throw new _d("SubtleCryptoProvider cannot be used in a synchronous context.")}async computeHMACSignatureAsync(_,k){let j=new TextEncoder,d=await this.subtleCrypto.importKey("raw",j.encode(k),{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]),O=await this.subtleCrypto.sign("hmac",d,j.encode(_)),$=new Uint8Array(O),Z=Array($.length);for(let X=0;X<$.length;X++)Z[X]=r8[$[X]];return Z.join("")}async computeSHA256Async(_){return new Uint8Array(await this.subtleCrypto.digest("SHA-256",_))}};r8=Array(256);for(let _=0;_<r8.length;_++)r8[_]=_.toString(16).padStart(2,"0")});class a8{constructor(){this._fetchFn=null,this._agent=null}getPlatformInfo(){return null}uuid4(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(_)=>{let k=Math.random()*16|0;return(_==="x"?k:k&3|8).toString(16)})}secureCompare(_,k){if(_.length!==k.length)return!1;let j=_.length,d=0;for(let O=0;O<j;++O)d|=_.charCodeAt(O)^k.charCodeAt(O);return d===0}createEmitter(){throw Error("createEmitter not implemented.")}tryBufferData(_){throw Error("tryBufferData not implemented.")}createNodeHttpClient(_){throw Error("createNodeHttpClient not implemented.")}createFetchHttpClient(_){return new a1(_)}createDefaultHttpClient(){throw Error("createDefaultHttpClient not implemented.")}createNodeCryptoProvider(){throw Error("createNodeCryptoProvider not implemented.")}createSubtleCryptoProvider(_){return new t8(_)}createDefaultCryptoProvider(){throw Error("createDefaultCryptoProvider not implemented.")}}var l6=R(()=>{g6();u6()});class e8{constructor(){this.eventTarget=new EventTarget,this.listenerMapping=new Map}on(_,k){let j=(d)=>{k(d.data)};return this.listenerMapping.set(k,j),this.eventTarget.addEventListener(_,j)}removeListener(_,k){let j=this.listenerMapping.get(k);return this.listenerMapping.delete(k),this.eventTarget.removeEventListener(_,j)}once(_,k){let j=(d)=>{k(d.data)};return this.listenerMapping.set(k,j),this.eventTarget.addEventListener(_,j,{once:!0})}emit(_,k){return this.eventTarget.dispatchEvent(new p6(_,k))}}var p6;var s6=R(()=>{p6=class p6 extends Event{constructor(_,k){super(_);this.data=k}}});var _$;var o6=R(()=>{l6();s6();_$=class _$ extends a8{createEmitter(){return new e8}tryBufferData(_){if(_.file.data instanceof ReadableStream)throw Error("Uploading a file as a stream is not supported in non-Node environments. Please open or upvote an issue at github.com/stripe/stripe-node if you use this, detailing your use-case.");return Promise.resolve(_)}createNodeHttpClient(){throw Error("Stripe: `createNodeHttpClient()` is not available in non-Node environments. Please use `createFetchHttpClient()` instead.")}createDefaultHttpClient(){return super.createFetchHttpClient()}createNodeCryptoProvider(){throw Error("Stripe: `createNodeCryptoProvider()` is not available in non-Node environments. Please use `createSubtleCryptoProvider()` instead.")}createDefaultCryptoProvider(){return this.createSubtleCryptoProvider()}}});var h0={};X9(h0,{generateV2Error:()=>j$,generateV1Error:()=>kd,generateOAuthError:()=>k$,TemporarySessionExpiredError:()=>L$,StripeUnsupportedResponseTypeError:()=>S$,StripeUnsupportedGrantTypeError:()=>z$,StripeSignatureVerificationError:()=>Kk,StripeRateLimitError:()=>Z$,StripePermissionError:()=>$$,StripeOAuthInvalidRequestError:()=>G$,StripeOAuthError:()=>yk,StripeInvalidScopeError:()=>F$,StripeInvalidRequestError:()=>w0,StripeInvalidGrantError:()=>X$,StripeInvalidClientError:()=>E$,StripeIdempotencyError:()=>C0,StripeError:()=>N_,StripeConnectionError:()=>M0,StripeCardError:()=>d$,StripeAuthenticationError:()=>O$,StripeAPIError:()=>jd,RateLimitError:()=>Y$});var kd=(_)=>{let k=_.statusCode;if(k===429||k===400&&_.code==="rate_limit")return new Z$(_);if(k===400||k===404){if(_.type==="idempotency_error")return new C0(_);return new w0(_)}if(k===401)return new O$(_);if(k===402)return new d$(_);if(k===403)return new $$(_);return new jd(_)},k$=(_)=>{switch(_.type){case"invalid_grant":return new X$(_);case"invalid_client":return new E$(_);case"invalid_request":return new G$(_);case"invalid_scope":return new F$(_);case"unsupported_grant_type":return new z$(_);case"unsupported_response_type":return new S$(_);default:return new yk(_)}},j$=(_)=>{switch(_.type){case"idempotency_error":return new C0(_);case"rate_limit":return new Y$(_);case"temporary_session_expired":return new L$(_)}switch(_.code){case"invalid_fields":return new w0(_)}return kd(_)},N_,d$,w0,jd,O$,$$,Z$,M0,Kk,C0,yk,X$,E$,G$,F$,z$,S$,Y$,L$;var f0=R(()=>{N_=class N_ extends Error{constructor(_={},k=null){super(_.message);this.type=k||this.constructor.name,this.raw=_,this.rawType=_.type,this.code=_.code,this.doc_url=_.doc_url,this.param=_.param,this.detail=_.detail,this.headers=_.headers,this.requestId=_.requestId,this.statusCode=_.statusCode,this.message=_.message??"",this.userMessage=_.user_message,this.charge=_.charge,this.decline_code=_.decline_code,this.payment_intent=_.payment_intent,this.payment_method=_.payment_method,this.payment_method_type=_.payment_method_type,this.setup_intent=_.setup_intent,this.source=_.source}};N_.generate=kd;d$=class d$ extends N_{constructor(_={}){super(_,"StripeCardError")}};w0=class w0 extends N_{constructor(_={}){super(_,"StripeInvalidRequestError")}};jd=class jd extends N_{constructor(_={}){super(_,"StripeAPIError")}};O$=class O$ extends N_{constructor(_={}){super(_,"StripeAuthenticationError")}};$$=class $$ extends N_{constructor(_={}){super(_,"StripePermissionError")}};Z$=class Z$ extends N_{constructor(_={}){super(_,"StripeRateLimitError")}};M0=class M0 extends N_{constructor(_={}){super(_,"StripeConnectionError")}};Kk=class Kk extends N_{constructor(_,k,j={}){super(j,"StripeSignatureVerificationError");this.header=_,this.payload=k}};C0=class C0 extends N_{constructor(_={}){super(_,"StripeIdempotencyError")}};yk=class yk extends N_{constructor(_={},k="StripeOAuthError"){super(_,k)}};X$=class X$ extends yk{constructor(_={}){super(_,"StripeInvalidGrantError")}};E$=class E$ extends yk{constructor(_={}){super(_,"StripeInvalidClientError")}};G$=class G$ extends yk{constructor(_={}){super(_,"StripeOAuthInvalidRequestError")}};F$=class F$ extends yk{constructor(_={}){super(_,"StripeInvalidScopeError")}};z$=class z$ extends yk{constructor(_={}){super(_,"StripeUnsupportedGrantTypeError")}};S$=class S$ extends yk{constructor(_={}){super(_,"StripeUnsupportedResponseTypeError")}};Y$=class Y$ extends N_{constructor(_={}){super(_,"RateLimitError")}};L$=class L$ extends N_{constructor(_={}){super(_,"TemporarySessionExpiredError")}}});class oj{constructor(_,k){this._stripe=_,this._maxBufferedRequestMetric=k}_normalizeStripeContext(_,k){if(_)return _.toString()||null;return k?.toString()||null}_addHeadersDirectlyToObject(_,k){_.requestId=k["request-id"],_.stripeAccount=_.stripeAccount||k["stripe-account"],_.apiVersion=_.apiVersion||k["stripe-version"],_.idempotencyKey=_.idempotencyKey||k["idempotency-key"]}_makeResponseEvent(_,k,j){let d=Date.now(),O=d-_.request_start_time;return K0({api_version:j["stripe-version"],account:j["stripe-account"],idempotency_key:j["idempotency-key"],method:_.method,path:_.path,status:k,request_id:this._getRequestId(j),elapsed:O,request_start_time:_.request_start_time,request_end_time:d})}_getRequestId(_){return _["request-id"]}_streamingResponseHandler(_,k,j){return(d)=>{let O=d.getHeaders(),$=()=>{let X=this._makeResponseEvent(_,d.getStatusCode(),O);this._stripe._emitter.emit("response",X),this._recordRequestMetrics(this._getRequestId(O),X.elapsed,k)},Z=d.toStream($);return this._addHeadersDirectlyToObject(Z,O),j(null,Z)}}_jsonResponseHandler(_,k,j,d){return(O)=>{let $=O.getHeaders(),Z=this._getRequestId($),X=O.getStatusCode(),E=this._makeResponseEvent(_,X,$);this._stripe._emitter.emit("response",E),O.toJSON().then((F)=>{if(F.error){let G=typeof F.error==="string";if(G)F.error={type:F.error,message:F.error_description};F.error.headers=$,F.error.statusCode=X,F.error.requestId=Z;let Y;if(G)Y=k$(F.error);else if(k==="v2")Y=j$(F.error);else Y=kd(F.error);throw Y}return F},(F)=>{throw new jd({message:"Invalid JSON received from the Stripe API",exception:F,requestId:$["request-id"]})}).then((F)=>{this._recordRequestMetrics(Z,E.elapsed,j);let G=O.getRawResponse();this._addHeadersDirectlyToObject(G,$),Object.defineProperty(F,"lastResponse",{enumerable:!1,writable:!1,value:G}),d(null,F)},(F)=>d(F,null))}}static _generateConnectionErrorMessage(_){return`An error occurred with our connection to Stripe.${_>0?` Request was retried ${_} times.`:""}`}static _shouldRetry(_,k,j,d){if(d&&k===0&&t_.CONNECTION_CLOSED_ERROR_CODES.includes(d.code))return!0;if(k>=j)return!1;if(!_)return!0;if(_.getHeaders()["stripe-should-retry"]==="false")return!1;if(_.getHeaders()["stripe-should-retry"]==="true")return!0;if(_.getStatusCode()===409)return!0;if(_.getStatusCode()>=500)return!0;return!1}_getSleepTimeInMS(_,k=null){let j=this._stripe.getInitialNetworkRetryDelay(),d=this._stripe.getMaxNetworkRetryDelay(),O=Math.min(j*Math.pow(2,_-1),d);if(O*=0.5*(1+Math.random()),O=Math.max(j,O),Number.isInteger(k)&&k<=MQ)O=Math.max(O,k);return O*1000}_getMaxNetworkRetries(_={}){return _.maxNetworkRetries!==void 0&&Number.isInteger(_.maxNetworkRetries)?_.maxNetworkRetries:this._stripe.getMaxNetworkRetries()}_defaultIdempotencyKey(_,k,j){let d=this._getMaxNetworkRetries(k),O=()=>`stripe-node-retry-${this._stripe._platformFunctions.uuid4()}`;if(j==="v2"){if(_==="POST"||_==="DELETE")return O()}else if(j==="v1"){if(_==="POST"&&d>0)return O()}return null}_makeHeaders({contentType:_,contentLength:k,apiVersion:j,clientUserAgent:d,method:O,userSuppliedHeaders:$,userSuppliedSettings:Z,stripeAccount:X,stripeContext:E,apiMode:F}){let G={Accept:"application/json","Content-Type":_,"User-Agent":this._getUserAgentString(F),"X-Stripe-Client-User-Agent":d,"X-Stripe-Client-Telemetry":this._getTelemetryHeader(),"Stripe-Version":j,"Stripe-Account":X,"Stripe-Context":E,"Idempotency-Key":this._defaultIdempotencyKey(O,Z,F)},Y=O=="POST"||O=="PUT"||O=="PATCH";if(Y||k){if(!Y)r1(`${O} method had non-zero contentLength but no payload is expected for this verb`);G["Content-Length"]=k}return Object.assign(K0(G),x6($))}_getUserAgentString(_){let k=this._stripe.getConstant("PACKAGE_VERSION"),j=this._stripe._appInfo?this._stripe.getAppInfoAsString():"",d=this._stripe.getConstant("AI_AGENT"),O=`Stripe/${_} NodeBindings/${k}`;if(j)O+=` ${j}`;if(d)O+=` AIAgent/${d}`;return O}_getTelemetryHeader(){if(this._stripe.getTelemetryEnabled()&&this._stripe._prevRequestMetrics.length>0){let _=this._stripe._prevRequestMetrics.shift();return JSON.stringify({last_request_metrics:_})}}_recordRequestMetrics(_,k,j){if(this._stripe.getTelemetryEnabled()&&_)if(this._stripe._prevRequestMetrics.length>this._maxBufferedRequestMetric)r1("Request metrics buffer is full, dropping telemetry message.");else{let d={request_id:_,request_duration_ms:k};if(j&&j.length>0)d.usage=j;this._stripe._prevRequestMetrics.push(d)}}_rawRequest(_,k,j,d,O){return new Promise((Z,X)=>{let E;try{let z=_.toUpperCase();if(z!=="POST"&&j&&Object.keys(j).length!==0)throw Error("rawRequest only supports params on POST requests. Please pass null and add your parameters to path.");let U=[].slice.call([j,d]),Q=sj(U),I=z==="POST"?Object.assign({},Q):null,T=W0(U),W=T.headers,J=T.authenticator;E={requestMethod:z,requestPath:k,bodyData:I,queryData:{},authenticator:J,headers:W,host:T.host,streaming:!!T.streaming,settings:{},usage:O||["raw_request"]}}catch(z){X(z);return}function F(z,U){if(z)X(z);else Z(U)}let{headers:G,settings:Y}=E,S=E.authenticator;this._request(E.requestMethod,E.host,k,E.bodyData,S,{headers:G,settings:Y,streaming:E.streaming},E.usage,F)})}_getContentLength(_){return typeof _==="string"?new TextEncoder().encode(_).length:_.length}_request(_,k,j,d,O,$,Z=[],X,E=null){let F;O=O??this._stripe._authenticator??null;let G=J0(j),Y=(U,Q,I,T,W)=>{return setTimeout(U,this._getSleepTimeInMS(T,W),Q,I,T+1)},S=(U,Q,I)=>{let T=$.settings&&$.settings.timeout&&Number.isInteger($.settings.timeout)&&$.settings.timeout>=0?$.settings.timeout:this._stripe.getApiField("timeout"),W={host:k||this._stripe.getApiField("host"),port:this._stripe.getApiField("port"),path:j,method:_,headers:Object.assign({},Q),body:F,protocol:this._stripe.getApiField("protocol")};O(W).then(()=>{let J=this._stripe.getApiField("httpClient").makeRequest(W.host,W.port,W.path,W.method,W.headers,W.body,W.protocol,T),C=Date.now(),f=K0({api_version:U,account:I0(Q["Stripe-Account"]),idempotency_key:I0(Q["Idempotency-Key"]),method:_,path:j,request_start_time:C}),N=I||0,y=this._getMaxNetworkRetries($.settings||{});this._stripe._emitter.emit("request",f),J.then((B)=>{if(oj._shouldRetry(B,N,y))return Y(S,U,Q,N,A6(B.getHeaders()["retry-after"]));else if($.streaming&&B.getStatusCode()<400)return this._streamingResponseHandler(f,Z,X)(B);else return this._jsonResponseHandler(f,G,Z,X)(B)}).catch((B)=>{if(oj._shouldRetry(null,N,y,B))return Y(S,U,Q,N,null);else{let A=B.code&&B.code===t_.TIMEOUT_ERROR_CODE;return X(new M0({message:A?`Request aborted due to timeout being reached (${T}ms)`:oj._generateConnectionErrorMessage(N),detail:B}))}})}).catch((J)=>{throw new N_({message:"Unable to authenticate the request",exception:J})})},z=(U,Q)=>{if(U)return X(U);F=Q,this._stripe.getClientUserAgent((I)=>{let T=this._stripe.getApiField("version"),W=this._makeHeaders({contentType:G=="v2"?"application/json":"application/x-www-form-urlencoded",contentLength:this._getContentLength(Q),apiVersion:T,clientUserAgent:I,method:_,userSuppliedHeaders:$.headers??null,userSuppliedSettings:$.settings??{},stripeAccount:$.stripeAccount??this._stripe.getApiField("stripeAccount"),stripeContext:this._normalizeStripeContext($.stripeContext,this._stripe.getApiField("stripeContext")),apiMode:G});S(T,W,0)})};if(E)E(_,d,$.headers,z);else{let U;if(G=="v2")U=d?v6(d):"";else U=_j(d||{});z(null,U)}}}var MQ=60;var r6=R(()=>{f0();D0();ck()});class U${constructor(_,k,j,d){this.index=0,this.pagePromise=_,this.promiseCache={currentPromise:null},this.requestArgs=k,this.spec=j,this.stripeResource=d}async iterate(_){if(!(_&&_.data&&typeof _.data.length==="number"))throw Error("Unexpected: Stripe API response does not have a well-formed `data` array.");let k=k7(this.requestArgs);if(this.index<_.data.length){let j=k?_.data.length-1-this.index:this.index,d=_.data[j];return this.index+=1,{value:d,done:!1}}else if(_.has_more){this.index=0,this.pagePromise=this.getNextPage(_);let j=await this.pagePromise;return this.iterate(j)}return{done:!0,value:void 0}}getNextPage(_){throw Error("Unimplemented")}async _next(){return this.iterate(await this.pagePromise)}next(){if(this.promiseCache.currentPromise)return this.promiseCache.currentPromise;let _=(async()=>{let k=await this._next();return this.promiseCache.currentPromise=null,k})();return this.promiseCache.currentPromise=_,_}}class e6{constructor(_,k,j,d){this.firstPagePromise=_,this.currentPageIterator=null,this.nextPageUrl=null,this.requestArgs=k,this.spec=j,this.stripeResource=d}async initFirstPage(){if(this.firstPagePromise){let _=await this.firstPagePromise;this.firstPagePromise=null,this.currentPageIterator=_.data[Symbol.iterator](),this.nextPageUrl=_.next_page_url||null}}async turnPage(){if(!this.nextPageUrl)return null;this.spec.fullPath=this.nextPageUrl;let _=await this.stripeResource._makeRequest([],this.spec,{});return this.nextPageUrl=_.next_page_url||null,this.currentPageIterator=_.data[Symbol.iterator](),this.currentPageIterator}async next(){if(await this.initFirstPage(),this.currentPageIterator){let j=this.currentPageIterator.next();if(!j.done)return{done:!1,value:j.value}}let _=await this.turnPage();if(!_)return{done:!0,value:void 0};let k=_.next();if(!k.done)return{done:!1,value:k.value};return{done:!0,value:void 0}}}function CQ(){if(typeof Symbol<"u"&&Symbol.asyncIterator)return Symbol.asyncIterator;return"@@asyncIterator"}function hQ(_){if(_.length<2)return null;let k=_[1];if(typeof k!=="function")throw Error(`The second argument to autoPagingEach, if present, must be a callback function; received ${typeof k}`);return k}function fQ(_){if(_.length===0)return;let k=_[0];if(typeof k!=="function")throw Error(`The first argument to autoPagingEach, if present, must be a callback function; received ${typeof k}`);if(k.length===2)return k;if(k.length>2)throw Error(`The \`onItem\` callback function passed to autoPagingEach must accept at most two arguments; got ${k}`);return function(d,O){let $=k(d);O($)}}function qQ(_,k){let j=k?0:_.data.length-1,d=_.data[j],O=d&&d.id;if(!O)throw Error("Unexpected: No `id` found on the last item while auto-paging a list.");return O}function HQ(_){return function(){let j=[].slice.call(arguments),d=fQ(j),O=hQ(j);if(j.length>2)throw Error(`autoPagingEach takes up to two arguments; received ${j}`);let $=NQ(_,d);return o1($,O)}}function bQ(_){return function(j,d){let O=j&&j.limit;if(!O)throw Error("You must pass a `limit` option to autoPagingToArray, e.g., `autoPagingToArray({limit: 1000});`.");if(O>1e4)throw Error("You cannot specify a limit of more than 10,000 items to fetch in `autoPagingToArray`; use `autoPagingEach` to iterate through longer lists.");let $=new Promise((Z,X)=>{let E=[];_((F)=>{if(E.push(F),E.length>=O)return!1}).then(()=>{Z(E)}).catch(X)});return o1($,d)}}function NQ(_,k){return new Promise((j,d)=>{function O($){if($.done){j();return}let Z=$.value;return new Promise((X)=>{k(Z,X)}).then((X)=>{if(X===!1)return O({done:!0,value:void 0});else return _().then(O)})}_().then(O).catch(d)})}function k7(_){let k=[].slice.call(_);return!!sj(k).ending_before}var t6,a6,_7=(_,k,j,d)=>{let O=J0(j.fullPath||j.path);if(O!=="v2"&&j.methodType==="search")return P$(new a6(d,k,j,_));if(O!=="v2"&&j.methodType==="list")return P$(new t6(d,k,j,_));if(O==="v2"&&j.methodType==="list")return P$(new e6(d,k,j,_));return null},P$=(_)=>{let k=HQ((...O)=>_.next(...O)),j=bQ(k),d={autoPagingEach:k,autoPagingToArray:j,next:()=>_.next(),return:()=>{return{}},[CQ()]:()=>{return d}};return d};var j7=R(()=>{ck();t6=class t6 extends U${getNextPage(_){let k=k7(this.requestArgs),j=qQ(_,k);return this.stripeResource._makeRequest(this.requestArgs,this.spec,{[k?"ending_before":"starting_after"]:j})}};a6=class a6 extends U${getNextPage(_){if(!_.next_page)throw Error("Unexpected: Stripe API response does not have a well-formed `next_page` field, but `has_more` was true.");return this.stripeResource._makeRequest(this.requestArgs,this.spec,{page:_.next_page})}}});function d7(_){if(_.path!==void 0&&_.fullPath!==void 0)throw Error(`Method spec specified both a 'path' (${_.path}) and a 'fullPath' (${_.fullPath}).`);return function(...k){let j=typeof k[k.length-1]=="function"&&k.pop();_.urlParams=b6(_.fullPath||this.createResourcePathWithSymbols(_.path||""));let d=o1(this._makeRequest(k,_,{}),j);return Object.assign(d,_7(this,k,_,d)),d}}var O7=R(()=>{ck();j7()});class x_{constructor(_,k){let[j,d]=x_.normalize(_,k);this._coefficient=j,this._exponent=d,Object.freeze(this)}static normalize(_,k){if(_===0n)return[0n,0];let j=_,d=k;while(j!==0n&&j%10n===0n)j/=10n,d+=1;return[j,d]}static roundDivision(_,k,j,d){if(k===0n)return _;if(d==="round-down")return _;let O=k>0n===j>0n?1n:-1n;if(d==="round-up")return _+O;if(d==="ceil")return O===1n?_+1n:_;if(d==="floor")return O===-1n?_-1n:_;let $=k<0n?-k:k,Z=j<0n?-j:j,X=$*2n,E;if(X===Z)E=0;else if(X<Z)E=-1;else E=1;if(E<0)return _;if(E>0)return _+O;if(d==="half-up")return _+O;if(d==="half-down")return _;if(_%2n===0n)return _;else return _+O}add(_){let k=_;if(this._exponent===k._exponent)return new x_(this._coefficient+k._coefficient,this._exponent);if(this._exponent<k._exponent){let j=10n**BigInt(k._exponent-this._exponent);return new x_(this._coefficient+k._coefficient*j,this._exponent)}else{let j=10n**BigInt(this._exponent-k._exponent);return new x_(this._coefficient*j+k._coefficient,k._exponent)}}sub(_){let k=_;if(this._exponent===k._exponent)return new x_(this._coefficient-k._coefficient,this._exponent);if(this._exponent<k._exponent){let j=10n**BigInt(k._exponent-this._exponent);return new x_(this._coefficient-k._coefficient*j,this._exponent)}else{let j=10n**BigInt(this._exponent-k._exponent);return new x_(this._coefficient*j-k._coefficient,k._exponent)}}mul(_){let k=_;return new x_(this._coefficient*k._coefficient,this._exponent+k._exponent)}div(_,k,j){if(k<0||!Number.isInteger(k))throw Error("precision must be a non-negative integer");let d=_;if(d._coefficient===0n)throw Error("Division by zero");let O=this._exponent-d._exponent+k,$,Z,X;if(O>=0){let F=this._coefficient*10n**BigInt(O);$=F/d._coefficient,Z=F%d._coefficient,X=d._coefficient}else{let F=d._coefficient*10n**BigInt(-O);$=this._coefficient/F,Z=this._coefficient%F,X=F}let E=x_.roundDivision($,Z,X,j);return new x_(E,-k)}cmp(_){let k=_;if(this._exponent===k._exponent){if(this._coefficient<k._coefficient)return-1;if(this._coefficient>k._coefficient)return 1;return 0}if(this._exponent<k._exponent){let j=10n**BigInt(k._exponent-this._exponent),d=k._coefficient*j;if(this._coefficient<d)return-1;if(this._coefficient>d)return 1;return 0}else{let j=10n**BigInt(this._exponent-k._exponent),d=this._coefficient*j;if(d<k._coefficient)return-1;if(d>k._coefficient)return 1;return 0}}eq(_){return this.cmp(_)===0}lt(_){return this.cmp(_)===-1}lte(_){return this.cmp(_)<=0}gt(_){return this.cmp(_)===1}gte(_){return this.cmp(_)>=0}isZero(){return this._coefficient===0n}isNegative(){return this._coefficient<0n}isPositive(){return this._coefficient>0n}neg(){return new x_(-this._coefficient,this._exponent)}abs(){if(this._coefficient<0n)return new x_(-this._coefficient,this._exponent);return this}round(_,k){let j=typeof k==="string"?xQ[k]:k;if(j===void 0)throw Error(`Unknown rounding preset: "${k}"`);if(j.value<0||!Number.isInteger(j.value))throw Error("DecimalRoundingOptions.value must be a non-negative integer");if(j.mode==="decimal-places"){let G=this.toFixed(j.value,_);return vk.from(G)}if(this._coefficient===0n)return this;let O=(this._coefficient<0n?(-this._coefficient).toString():this._coefficient.toString()).length;if(j.value===0)return vk.zero;if(O<=j.value)return this;let $=O-j.value,Z=10n**BigInt($),X=this._coefficient/Z,E=this._coefficient%Z,F=x_.roundDivision(X,E,Z,_);return new x_(F,this._exponent+$)}toString(){if(this._coefficient===0n)return"0";let _=this._coefficient.toString(),k=_.startsWith("-"),j=k?_.slice(1):_;if(this._exponent<0){let O=-this._exponent;if((O>=j.length?O-j.length:0)>30){if(j.length===1)return`${_}E${String(this._exponent)}`;let Z=j[0]??"",X=j.slice(1),E=this._exponent+j.length-1;return`${k?"-":""}${Z}.${X}E${String(E)}`}if(O>=j.length){let Z="0".repeat(O-j.length);return`${k?"-":""}0.${Z}${j}`}else{let Z=j.slice(0,j.length-O),X=j.slice(j.length-O);return`${k?"-":""}${Z}.${X}`}}if(j.length+this._exponent<=30){if(this._exponent===0)return _;let O="0".repeat(this._exponent);return`${k?"-":""}${j}${O}`}else{if(j.length===1)return`${_}E+${String(this._exponent)}`;let O=j[0]??"",$=j.slice(1),Z=this._exponent+j.length-1;return`${k?"-":""}${O}.${$}E+${String(Z)}`}}toJSON(){return this.toString()}toNumber(){return Number(this.toString())}toFixed(_,k){if(_<0||!Number.isInteger(_))throw Error("decimalPlaces must be a non-negative integer");let j=(O)=>{let $=O.toString(),Z=$.startsWith("-"),X=Z?$.slice(1):$;if(_===0)return $;if(_>=X.length){let E="0".repeat(_-X.length);return`${Z?"-":""}0.${E}${X}`}else{let E=X.slice(0,X.length-_),F=X.slice(X.length-_);return`${Z?"-":""}${E}.${F}`}},d=-_;if(this._exponent===d)return j(this._coefficient);if(this._exponent<d){let O=d-this._exponent,$=10n**BigInt(O),Z=this._coefficient/$,X=this._coefficient%$,E=x_.roundDivision(Z,X,$,k);return j(E)}else{let O=this._exponent-d,$=this._coefficient*10n**BigInt(O);return j($)}}valueOf(){return this.toString()}}var xQ,vk;var q0=R(()=>{xQ={"ubb-usage-count":{mode:"significant-figures",value:15},"v1-api":{mode:"decimal-places",value:12}};vk={from(_){if(typeof _==="bigint")return new x_(_,0);if(typeof _==="number"){if(!Number.isFinite(_))throw Error("Number must be finite");return vk.from(_.toString())}let k=_.trim();if(k==="")throw Error("Cannot parse empty string as Decimal");let j=/^([+-]?)(\d+)(?:\.(\d+))?(?:[eE]([+-]?\d+))?$/.exec(k);if(!j)throw Error(`Invalid decimal string: ${_}`);let d=j[1]==="-"?-1n:1n,O=j[2]??"",$=j[3]??"",Z=j[4]?Number(j[4]):0;if(!Number.isSafeInteger(Z)||Z>1e6||Z<-1e6)throw Error(`Exponent out of range: ${String(j[4])} exceeds safe integer bounds`);let X=O+$,E=d*BigInt(X),F=Z-$.length;if(!Number.isSafeInteger(F)||F>1e6||F<-1e6)throw Error(`Computed exponent out of range: ${String(F)} exceeds safe integer bounds`);return new x_(E,F)},zero:new x_(0n,0)}});var dd=(_,k)=>{if(_==null)return _;switch(k.kind){case"int64_string":return typeof _==="bigint"||typeof _==="number"?String(_):_;case"decimal_string":return typeof _.toFixed==="function"&&typeof _.isZero==="function"?_.toString():_;case"object":{if(typeof _!=="object"||Array.isArray(_))return _;let j=_,d={};for(let O of Object.keys(j)){let $=k.fields[O];d[O]=$?dd(j[O],$):j[O]}return d}case"array":{if(!Array.isArray(_))return _;return _.map((j)=>dd(j,k.element))}case"nullable":return dd(_,k.inner)}},Od=(_,k)=>{if(_==null)return _;switch(k.kind){case"int64_string":if(typeof _==="string")try{return BigInt(_)}catch{throw Error(`Failed to coerce int64_string value: expected an integer string, got '${_}'`)}return _;case"decimal_string":if(typeof _==="string")try{return vk.from(_)}catch{throw Error(`Failed to coerce decimal_string value: expected a decimal string, got '${_}'`)}return _;case"object":{if(typeof _!=="object"||Array.isArray(_))return _;let j=_;for(let d of Object.keys(k.fields))if(d in j)j[d]=Od(j[d],k.fields[d]);return j}case"array":{if(!Array.isArray(_))return _;for(let j=0;j<_.length;j++)_[j]=Od(_[j],k.element);return _}case"nullable":return Od(_,k.inner)}};var $7=R(()=>{q0()});function P(_,k){if(this._stripe=_,k)throw Error("Support for curried url params was dropped in stripe-node v7.0.0. Instead, pass two ids.");this.basePath=T0(this.basePath||_.getApiField("basePath")),this.resourcePath=this.path,this.path=T0(this.path),this.initialize(...arguments)}var M=R(()=>{ck();O7();$7();P.extend=N6;P.method=d7;P.MAX_BUFFERED_REQUEST_METRICS=100;P.prototype={_stripe:null,path:"",resourcePath:"",basePath:null,initialize(){},requestDataProcessor:null,validateRequest:null,createFullPath(_,k){let j=[this.basePath(k),this.path(k)];if(typeof _==="function"){let d=_(k);if(d)j.push(d)}else j.push(_);return this._joinUrlParts(j)},createResourcePathWithSymbols(_){if(_)return`/${this._joinUrlParts([this.resourcePath,_])}`;else return`/${this.resourcePath}`},_joinUrlParts(_){return _.join("/").replace(/\/{2,}/g,"/")},_getRequestOpts(_,k,j){let d=(k.method||"GET").toUpperCase(),O=k.usage||[],$=k.urlParams||[],Z=k.encode||((N)=>N),X=!!k.fullPath,E=T0(X?k.fullPath:k.path||""),F=X?k.fullPath:this.createResourcePathWithSymbols(k.path),G=[].slice.call(_),Y=$.reduce((N,y)=>{let B=G.shift();if(typeof B!=="string")throw Error(`Stripe: Argument "${y}" must be a string, but got: ${B} (on API request to \`${d} ${F}\`)`);return N[y]=B,N},{}),S=sj(G),z=Z(Object.assign({},S,j)),U=W0(G),Q=U.host||k.host,I=!!k.streaming||!!U.streaming;if(G.filter((N)=>N!=null).length)throw Error(`Stripe: Unknown arguments (${G}). Did you mean to pass an options object? See https://github.com/stripe/stripe-node/wiki/Passing-Options. (on API request to ${d} \`${F}\`)`);let T=X?E(Y):this.createFullPath(E,Y),W=Object.assign(U.headers,k.headers);if(k.validator)k.validator(z,{headers:W});let J=k.method==="GET"||k.method==="DELETE";return{requestMethod:d,requestPath:T,bodyData:J?null:z,queryData:J?z:{},authenticator:U.authenticator??null,headers:W,host:Q??null,streaming:I,settings:U.settings,usage:O}},_makeRequest(_,k,j){return new Promise((d,O)=>{let $;try{$=this._getRequestOpts(_,k,j)}catch(Y){O(Y);return}if(k.requestSchema&&$.bodyData)$.bodyData=dd($.bodyData,k.requestSchema);function Z(Y,S){if(Y)O(Y);else try{if(k.responseSchema)Od(S,k.responseSchema);d(k.transformResponseData?k.transformResponseData(S):S)}catch(z){O(z)}}let X=Object.keys($.queryData).length===0,E=[$.requestPath,X?"":"?",_j($.queryData)].join(""),{headers:F,settings:G}=$;this._stripe._requestSender._request($.requestMethod,$.host,E,$.bodyData,$.authenticator,{headers:F,settings:G,streaming:$.streaming},$.usage,Z,this.requestDataProcessor?.bind(this))})}}});class kj{constructor(_=[]){this._segments=[..._]}get segments(){return[...this._segments]}push(_){if(!_)throw Error("Segment cannot be null or undefined");return new kj([...this._segments,_])}pop(){if(this._segments.length===0)throw Error("Cannot pop from an empty context");return new kj(this._segments.slice(0,-1))}toString(){return this._segments.join("/")}static parse(_){if(!_)return new kj([]);return new kj(_.split("/"))}}function Z7(_){let k={DEFAULT_TOLERANCE:300,signature:null,constructEvent(G,Y,S,z,U,Q){try{if(!this.signature)throw Error("ERR: missing signature helper, unable to verify");this.signature.verifyHeader(G,Y,S,z||k.DEFAULT_TOLERANCE,U,Q)}catch(T){if(T instanceof _d)T.message+="\nUse `await constructEventAsync(...)` instead of `constructEvent(...)`";throw T}let I=G instanceof Uint8Array?JSON.parse(new TextDecoder("utf8").decode(G)):JSON.parse(G);if(I&&I.object==="v2.core.event")throw Error("You passed an event notification to stripe.webhooks.constructEvent, which expects a webhook payload. Use stripe.parseEventNotification instead.");return I},async constructEventAsync(G,Y,S,z,U,Q){if(!this.signature)throw Error("ERR: missing signature helper, unable to verify");await this.signature.verifyHeaderAsync(G,Y,S,z||k.DEFAULT_TOLERANCE,U,Q);let I=G instanceof Uint8Array?JSON.parse(new TextDecoder("utf8").decode(G)):JSON.parse(G);if(I&&I.object==="v2.core.event")throw Error("You passed an event notification to stripe.webhooks.constructEvent, which expects a webhook payload. Use stripe.parseEventNotification instead.");return I},generateTestHeaderString:function(G){let Y=F(G),S=Y.signature||Y.cryptoProvider.computeHMACSignature(Y.payloadString,Y.secret);return Y.generateHeaderString(S)},generateTestHeaderStringAsync:async function(G){let Y=F(G),S=Y.signature||await Y.cryptoProvider.computeHMACSignatureAsync(Y.payloadString,Y.secret);return Y.generateHeaderString(S)}},j={EXPECTED_SCHEME:"v1",verifyHeader(G,Y,S,z,U,Q){let{decodedHeader:I,decodedPayload:T,details:W,suspectPayloadType:J}=O(G,Y,this.EXPECTED_SCHEME),C=/\s/.test(S);U=U||E();let f=U.computeHMACSignature(d(T,W),S);return $(T,I,W,f,z,J,C,Q),!0},async verifyHeaderAsync(G,Y,S,z,U,Q){let{decodedHeader:I,decodedPayload:T,details:W,suspectPayloadType:J}=O(G,Y,this.EXPECTED_SCHEME),C=/\s/.test(S);U=U||E();let f=await U.computeHMACSignatureAsync(d(T,W),S);return $(T,I,W,f,z,J,C,Q)}};function d(G,Y){return`${Y.timestamp}.${G}`}function O(G,Y,S){if(!G)throw new Kk(Y,G,{message:"No webhook payload was provided."});let z=typeof G!="string"&&!(G instanceof Uint8Array),U=new TextDecoder("utf8"),Q=G instanceof Uint8Array?U.decode(G):G;if(Array.isArray(Y))throw Error("Unexpected: An array was passed as a header, which should not be possible for the stripe-signature header.");if(Y==null||Y=="")throw new Kk(Y,G,{message:"No stripe-signature header value was provided."});let I=Y instanceof Uint8Array?U.decode(Y):Y,T=Z(I,S);if(!T||T.timestamp===-1)throw new Kk(I,Q,{message:"Unable to extract timestamp and signatures from header"});if(!T.signatures.length)throw new Kk(I,Q,{message:"No signatures found with expected scheme"});return{decodedPayload:Q,decodedHeader:I,details:T,suspectPayloadType:z}}function $(G,Y,S,z,U,Q,I,T){let W=!!S.signatures.filter(_.secureCompare.bind(_,z)).length,J=`
|
|
3
|
-
Learn more about webhook signing and explore webhook integration examples for various frameworks at https://docs.stripe.com/webhooks/signature`,
|
|
2
|
+
var a3=Object.create;var{getPrototypeOf:o3,defineProperty:w9,getOwnPropertyNames:s3}=Object;var r3=Object.prototype.hasOwnProperty;function t3($){return this[$]}var e3,$B,ZB=($,Z,J)=>{var Q=$!=null&&typeof $==="object";if(Q){var X=Z?e3??=new WeakMap:$B??=new WeakMap,Y=X.get($);if(Y)return Y}J=$!=null?a3(o3($)):{};let G=Z||!$||!$.__esModule?w9(J,"default",{value:$,enumerable:!0}):J;for(let V of s3($))if(!r3.call(G,V))w9(G,V,{get:t3.bind($,V),enumerable:!0});if(Q)X.set($,G);return G};var K=($,Z)=>()=>(Z||$((Z={exports:{}}).exports,Z),Z.exports);var C=import.meta.require;var b0=K((u9)=>{Object.defineProperty(u9,"__esModule",{value:!0});u9.CryptoProviderOnlySupportsAsyncError=u9.CryptoProvider=void 0;class h9{computeHMACSignature($,Z){throw Error("computeHMACSignature not implemented.")}computeHMACSignatureAsync($,Z){throw Error("computeHMACSignatureAsync not implemented.")}computeSHA256Async($){throw Error("computeSHA256 not implemented.")}}u9.CryptoProvider=h9;class m9 extends Error{}u9.CryptoProviderOnlySupportsAsyncError=m9});var i9=K((p9)=>{Object.defineProperty(p9,"__esModule",{value:!0});p9.NodeCryptoProvider=void 0;var n9=C("crypto"),SB=b0();class l9 extends SB.CryptoProvider{computeHMACSignature($,Z){return n9.createHmac("sha256",Z).update($,"utf8").digest("hex")}async computeHMACSignatureAsync($,Z){return await this.computeHMACSignature($,Z)}async computeSHA256Async($){return new Uint8Array(await n9.createHash("sha256").update($).digest())}}p9.NodeCryptoProvider=l9});var j0=K((o9)=>{Object.defineProperty(o9,"__esModule",{value:!0});o9.HttpClientResponse=o9.HttpClient=void 0;class H0{getClientName(){throw Error("getClientName not implemented.")}makeRequest($,Z,J,Q,X,Y,G,V){throw Error("makeRequest not implemented.")}static makeTimeoutError(){let $=TypeError(H0.TIMEOUT_ERROR_CODE);return $.code=H0.TIMEOUT_ERROR_CODE,$}}o9.HttpClient=H0;H0.CONNECTION_CLOSED_ERROR_CODES=["ECONNRESET","EPIPE"];H0.TIMEOUT_ERROR_CODE="ETIMEDOUT";class a9{constructor($,Z){this._statusCode=$,this._headers=Z}getStatusCode(){return this._statusCode}getHeaders(){return this._headers}getRawResponse(){throw Error("getRawResponse not implemented.")}toStream($){throw Error("toStream not implemented.")}toJSON(){throw Error("toJSON not implemented.")}}o9.HttpClientResponse=a9});var XZ=K((JZ)=>{Object.defineProperty(JZ,"__esModule",{value:!0});JZ.NodeHttpClientResponse=JZ.NodeHttpClient=void 0;var r9=C("http"),t9=C("https"),A$=j0(),e9=r9.default||r9,$Z=t9.default||t9,vB=new e9.Agent({keepAlive:!0}),yB=new $Z.Agent({keepAlive:!0});class ZZ extends A$.HttpClient{constructor($){super();this._agent=$}getClientName(){return"node"}makeRequest($,Z,J,Q,X,Y,G,V){let U=G==="http",W=this._agent;if(!W)W=U?vB:yB;return new Promise((z,L)=>{let H=(U?e9:$Z).request({host:$,port:Z,path:J,method:Q,agent:W,headers:X,ciphers:"DEFAULT:!aNULL:!eNULL:!LOW:!EXPORT:!SSLv2:!MD5"});H.setTimeout(V,()=>{H.destroy(A$.HttpClient.makeTimeoutError())}),H.on("response",(T)=>{z(new N$(T))}),H.on("error",(T)=>{L(T)}),H.once("socket",(T)=>{if(T.connecting)T.once(U?"connect":"secureConnect",()=>{H.write(Y),H.end()});else H.write(Y),H.end()})})}}JZ.NodeHttpClient=ZZ;class N$ extends A$.HttpClientResponse{constructor($){super($.statusCode,$.headers||{});this._res=$}getRawResponse(){return this._res}toStream($){return this._res.once("end",()=>$()),this._res}toJSON(){return new Promise(($,Z)=>{let J="";this._res.setEncoding("utf8"),this._res.on("data",(Q)=>{J+=Q}),this._res.once("end",()=>{try{$(JSON.parse(J))}catch(Q){Z(Q)}})})}}JZ.NodeHttpClientResponse=N$});var c=K((WZ)=>{Object.defineProperty(WZ,"__esModule",{value:!0});WZ.parseHeadersForFetch=WZ.parseHttpHeaderAsNumber=WZ.parseHttpHeaderAsString=WZ.getAPIMode=WZ.jsonStringifyRequestData=WZ.concat=WZ.createApiKeyAuthenticator=WZ.detectAIAgent=WZ.AI_AGENTS=WZ.determineProcessUserAgentProperties=WZ.validateInteger=WZ.flattenAndStringify=WZ.isObject=WZ.emitWarning=WZ.pascalToCamelCase=WZ.callbackifyPromiseWithTimeout=WZ.normalizeHeader=WZ.normalizeHeaders=WZ.removeNullish=WZ.protoExtend=WZ.getOptionsFromArgs=WZ.getDataFromArgs=WZ.extractUrlParams=WZ.makeURLInterpolator=WZ.queryStringifyRequestData=WZ.isOptionsHash=void 0;var I$=["apiKey","idempotencyKey","stripeAccount","apiVersion","maxNetworkRetries","timeout","host","authenticator","stripeContext","headers","additionalHeaders","streaming"];function P$($){return $&&typeof $==="object"&&I$.some((Z)=>Object.prototype.hasOwnProperty.call($,Z))}WZ.isOptionsHash=P$;function jB($){return MB($)}WZ.queryStringifyRequestData=jB;function YZ($){return encodeURIComponent($).replace(/!/g,"%21").replace(/\*/g,"%2A").replace(/\(/g,"%28").replace(/\)/g,"%29").replace(/'/g,"%27").replace(/%5B/g,"[").replace(/%5D/g,"]")}function fB($){if($ instanceof Date)return Math.floor($.getTime()/1000).toString();if($===null)return"";return String($)}function MB($){let Z=[];function J(Q,X){if(X===void 0)return;if(X===null||typeof X!=="object"||X instanceof Date){Z.push(YZ(Q)+"="+YZ(fB(X)));return}if(Array.isArray(X)){for(let Y=0;Y<X.length;Y++)if(X[Y]!==void 0)J(Q+"["+Y+"]",X[Y]);return}for(let Y of Object.keys(X))J(Q+"["+Y+"]",X[Y])}if(typeof $==="object"&&$!==null)for(let Q of Object.keys($))J(Q,$[Q]);return Z.join("&")}WZ.makeURLInterpolator=(()=>{let $={"\n":"\\n",'"':"\\\"","\u2028":"\\u2028","\u2029":"\\u2029"};return(Z)=>{let J=Z.replace(/["\n\r\u2028\u2029]/g,(Q)=>$[Q]);return(Q)=>{return J.replace(/\{([\s\S]+?)\}/g,(X,Y)=>{let G=Q[Y];if(_B(G))return encodeURIComponent(G);return""})}}})();function _B($){return["number","string","boolean"].includes(typeof $)}function gB($){let Z=$.match(/\{\w+\}/g);if(!Z)return[];return Z.map((J)=>J.replace(/[{}]/g,""))}WZ.extractUrlParams=gB;function hB($){if(!Array.isArray($)||!$[0]||typeof $[0]!=="object")return{};if(!P$($[0]))return $.shift();let Z=Object.keys($[0]),J=Z.filter((Q)=>I$.includes(Q));if(J.length>0&&J.length!==Z.length)S$(`Options found in arguments (${J.join(", ")}). Did you mean to pass an options object? See https://github.com/stripe/stripe-node/wiki/Passing-Options.`);return{}}WZ.getDataFromArgs=hB;function mB($){let Z={host:null,headers:{},settings:{},streaming:!1};if($.length>0){let J=$[$.length-1];if(typeof J==="string")Z.authenticator=x$($.pop());else if(P$(J)){let Q={...$.pop()},X=Object.keys(Q).filter((Y)=>!I$.includes(Y));if(X.length)S$(`Invalid options found (${X.join(", ")}); ignoring.`);if(Q.apiKey)Z.authenticator=x$(Q.apiKey);if(Q.idempotencyKey)Z.headers["Idempotency-Key"]=Q.idempotencyKey;if(Q.stripeAccount)Z.headers["Stripe-Account"]=Q.stripeAccount;if(Q.stripeContext){if(Z.headers["Stripe-Account"])throw Error("Can't specify both stripeAccount and stripeContext.");Z.headers["Stripe-Context"]=Q.stripeContext}if(Q.apiVersion)Z.headers["Stripe-Version"]=Q.apiVersion;if(Number.isInteger(Q.maxNetworkRetries))Z.settings.maxNetworkRetries=Q.maxNetworkRetries;if(Number.isInteger(Q.timeout))Z.settings.timeout=Q.timeout;if(Q.host)Z.host=Q.host;if(Q.authenticator){if(Q.apiKey)throw Error("Can't specify both apiKey and authenticator.");if(typeof Q.authenticator!=="function")throw Error("The authenticator must be a function receiving a request as the first parameter.");Z.authenticator=Q.authenticator}if(Q.headers)Object.assign(Z.headers,Q.headers);if(Q.additionalHeaders)Object.assign(Z.headers,Q.additionalHeaders);if(Q.streaming)Z.streaming=!0}}return Z}WZ.getOptionsFromArgs=mB;function uB($){let Z=this,J=Object.prototype.hasOwnProperty.call($,"constructor")?$.constructor:function(...Q){Z.apply(this,Q)};return Object.assign(J,Z),J.prototype=Object.create(Z.prototype),Object.assign(J.prototype,$),J}WZ.protoExtend=uB;function cB($){if(typeof $!=="object")throw Error("Argument must be an object");return Object.keys($).reduce((Z,J)=>{if($[J]!=null)Z[J]=$[J];return Z},{})}WZ.removeNullish=cB;function nB($){if(!($&&typeof $==="object"))return $;return Object.keys($).reduce((Z,J)=>{return Z[GZ(J)]=$[J],Z},{})}WZ.normalizeHeaders=nB;function GZ($){return $.split("-").map((Z)=>Z.charAt(0).toUpperCase()+Z.substr(1).toLowerCase()).join("-")}WZ.normalizeHeader=GZ;function lB($,Z){if(Z)return $.then((J)=>{setTimeout(()=>{Z(null,J)},0)},(J)=>{setTimeout(()=>{Z(J,null)},0)});return $}WZ.callbackifyPromiseWithTimeout=lB;function pB($){if($==="OAuth")return"oauth";else return $[0].toLowerCase()+$.substring(1)}WZ.pascalToCamelCase=pB;function S$($){if(typeof process.emitWarning!=="function")return console.warn(`Stripe: ${$}`);return process.emitWarning($,"Stripe")}WZ.emitWarning=S$;function VZ($){let Z=typeof $;return(Z==="function"||Z==="object")&&!!$}WZ.isObject=VZ;function dB($){let Z={},J=(Q,X)=>{Object.entries(Q).forEach(([Y,G])=>{let V=X?`${X}[${Y}]`:Y;if(VZ(G))if(!(G instanceof Uint8Array)&&!Object.prototype.hasOwnProperty.call(G,"data"))return J(G,V);else Z[V]=G;else Z[V]=String(G)})};return J($,null),Z}WZ.flattenAndStringify=dB;function iB($,Z,J){if(!Number.isInteger(Z))if(J!==void 0)return J;else throw Error(`${$} must be an integer`);return Z}WZ.validateInteger=iB;function aB(){return typeof process>"u"?{}:{lang_version:process.version}}WZ.determineProcessUserAgentProperties=aB;WZ.AI_AGENTS=[["ANTIGRAVITY_CLI_ALIAS","antigravity"],["CLAUDECODE","claude_code"],["CLINE_ACTIVE","cline"],["CODEX_SANDBOX","codex_cli"],["CODEX_THREAD_ID","codex_cli"],["CODEX_SANDBOX_NETWORK_DISABLED","codex_cli"],["CODEX_CI","codex_cli"],["CURSOR_AGENT","cursor"],["GEMINI_CLI","gemini_cli"],["OPENCLAW_SHELL","openclaw"],["OPENCODE","open_code"]];function oB($){for(let[Z,J]of WZ.AI_AGENTS)if($[Z])return J;return""}WZ.detectAIAgent=oB;function x$($){let Z=(J)=>{return J.headers.Authorization="Bearer "+$,Promise.resolve()};return Z._apiKey=$,Z}WZ.createApiKeyAuthenticator=x$;function sB($){let Z=$.reduce((X,Y)=>X+Y.length,0),J=new Uint8Array(Z),Q=0;return $.forEach((X)=>{J.set(X,Q),Q+=X.length}),J}WZ.concat=sB;function rB($,Z){if(this[$]instanceof Date)return Math.floor(this[$].getTime()/1000).toString();return Z}function tB($){return JSON.stringify($,rB)}WZ.jsonStringifyRequestData=tB;function eB($){if(!$)return"v1";return $.startsWith("/v2")?"v2":"v1"}WZ.getAPIMode=eB;function BZ($){if(Array.isArray($))return $.join(", ");return String($)}WZ.parseHttpHeaderAsString=BZ;function $W($){let Z=Array.isArray($)?$[0]:$;return Number(Z)}WZ.parseHttpHeaderAsNumber=$W;function ZW($){return Object.entries($).map(([Z,J])=>{return[Z,BZ(J)]})}WZ.parseHeadersForFetch=ZW});var HZ=K((LZ)=>{Object.defineProperty(LZ,"__esModule",{value:!0});LZ.FetchHttpClientResponse=LZ.FetchHttpClient=void 0;var xW=c(),f0=j0();class E8 extends f0.HttpClient{constructor($){super();if(!$){if(!globalThis.fetch)throw Error("fetch() function not provided and is not defined in the global scope. You must provide a fetch implementation.");$=globalThis.fetch}if(globalThis.AbortController)this._fetchFn=E8.makeFetchWithAbortTimeout($);else this._fetchFn=E8.makeFetchWithRaceTimeout($)}static makeFetchWithRaceTimeout($){return(Z,J,Q)=>{let X,Y=new Promise((V,U)=>{X=setTimeout(()=>{X=null,U(f0.HttpClient.makeTimeoutError())},Q)}),G=$(Z,J);return Promise.race([G,Y]).finally(()=>{if(X)clearTimeout(X)})}}static makeFetchWithAbortTimeout($){return async(Z,J,Q)=>{let X=new AbortController,Y=setTimeout(()=>{Y=null,X.abort(f0.HttpClient.makeTimeoutError())},Q);try{return await $(Z,{...J,signal:X.signal})}catch(G){if(G.name==="AbortError")throw f0.HttpClient.makeTimeoutError();else throw G}finally{if(Y)clearTimeout(Y)}}}getClientName(){return"fetch"}async makeRequest($,Z,J,Q,X,Y,G,V){let W=new URL(J,`${G==="http"?"http":"https"}://${$}`);W.port=Z;let B=Q=="POST"||Q=="PUT"||Q=="PATCH",z=Y||(B?"":void 0),L=await this._fetchFn(W.toString(),{method:Q,headers:(0,xW.parseHeadersForFetch)(X),body:z},V);return new F8(L)}}LZ.FetchHttpClient=E8;class F8 extends f0.HttpClientResponse{constructor($){super($.status,F8._transformHeadersToObject($.headers));this._res=$}getRawResponse(){return this._res}toStream($){return $(),this._res.body}toJSON(){return this._res.json()}static _transformHeadersToObject($){let Z={};for(let J of $){if(!Array.isArray(J)||J.length!=2)throw Error("Response objects produced by the fetch function given to FetchHttpClient do not have an iterable headers map. Response#headers should be an iterable object.");Z[J[0]]=J[1]}return Z}}LZ.FetchHttpClientResponse=F8});var qZ=K((DZ)=>{Object.defineProperty(DZ,"__esModule",{value:!0});DZ.SubtleCryptoProvider=void 0;var wZ=b0();class TZ extends wZ.CryptoProvider{constructor($){super();this.subtleCrypto=$||crypto.subtle}computeHMACSignature($,Z){throw new wZ.CryptoProviderOnlySupportsAsyncError("SubtleCryptoProvider cannot be used in a synchronous context.")}async computeHMACSignatureAsync($,Z){let J=new TextEncoder,Q=await this.subtleCrypto.importKey("raw",J.encode(Z),{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]),X=await this.subtleCrypto.sign("hmac",Q,J.encode($)),Y=new Uint8Array(X),G=Array(Y.length);for(let V=0;V<Y.length;V++)G[V]=R$[Y[V]];return G.join("")}async computeSHA256Async($){return new Uint8Array(await this.subtleCrypto.digest("SHA-256",$))}}DZ.SubtleCryptoProvider=TZ;var R$=Array(256);for(let $=0;$<R$.length;$++)R$[$]=$.toString(16).padStart(2,"0")});var kZ=K((FZ)=>{Object.defineProperty(FZ,"__esModule",{value:!0});FZ.PlatformFunctions=void 0;var PW=HZ(),SW=qZ();class EZ{constructor(){this._fetchFn=null,this._agent=null}getPlatformInfo(){return null}uuid4(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,($)=>{let Z=Math.random()*16|0;return($==="x"?Z:Z&3|8).toString(16)})}secureCompare($,Z){if($.length!==Z.length)return!1;let J=$.length,Q=0;for(let X=0;X<J;++X)Q|=$.charCodeAt(X)^Z.charCodeAt(X);return Q===0}createEmitter(){throw Error("createEmitter not implemented.")}tryBufferData($){throw Error("tryBufferData not implemented.")}createNodeHttpClient($){throw Error("createNodeHttpClient not implemented.")}createFetchHttpClient($){return new PW.FetchHttpClient($)}createDefaultHttpClient(){throw Error("createDefaultHttpClient not implemented.")}createNodeCryptoProvider(){throw Error("createNodeCryptoProvider not implemented.")}createSubtleCryptoProvider($){return new SW.SubtleCryptoProvider($)}createDefaultCryptoProvider(){throw Error("createDefaultCryptoProvider not implemented.")}}FZ.PlatformFunctions=EZ});var M0=K((xZ)=>{Object.defineProperty(xZ,"__esModule",{value:!0});xZ.TemporarySessionExpiredError=xZ.RateLimitError=xZ.StripeUnsupportedResponseTypeError=xZ.StripeUnsupportedGrantTypeError=xZ.StripeInvalidScopeError=xZ.StripeOAuthInvalidRequestError=xZ.StripeInvalidClientError=xZ.StripeInvalidGrantError=xZ.StripeOAuthError=xZ.StripeIdempotencyError=xZ.StripeSignatureVerificationError=xZ.StripeConnectionError=xZ.StripeRateLimitError=xZ.StripePermissionError=xZ.StripeAuthenticationError=xZ.StripeAPIError=xZ.StripeInvalidRequestError=xZ.StripeCardError=xZ.StripeError=xZ.generateV2Error=xZ.generateOAuthError=xZ.generateV1Error=void 0;var RW=($)=>{let Z=$.statusCode;if(Z===429||Z===400&&$.code==="rate_limit")return new f$($);if(Z===400||Z===404){if($.type==="idempotency_error")return new k8($);return new C8($)}if(Z===401)return new b$($);if(Z===402)return new v$($);if(Z===403)return new j$($);return new y$($)};xZ.generateV1Error=RW;var vW=($)=>{switch($.type){case"invalid_grant":return new M$($);case"invalid_client":return new _$($);case"invalid_request":return new g$($);case"invalid_scope":return new h$($);case"unsupported_grant_type":return new m$($);case"unsupported_response_type":return new u$($);default:return new d($)}};xZ.generateOAuthError=vW;var yW=($)=>{switch($.type){case"idempotency_error":return new k8($);case"rate_limit":return new c$($);case"temporary_session_expired":return new n$($)}switch($.code){case"invalid_fields":return new C8($)}return xZ.generateV1Error($)};xZ.generateV2Error=yW;class v extends Error{constructor($={},Z=null){super($.message);this.type=Z||this.constructor.name,this.raw=$,this.rawType=$.type,this.code=$.code,this.doc_url=$.doc_url,this.param=$.param,this.detail=$.detail,this.headers=$.headers,this.requestId=$.requestId,this.statusCode=$.statusCode,this.message=$.message??"",this.userMessage=$.user_message,this.charge=$.charge,this.decline_code=$.decline_code,this.payment_intent=$.payment_intent,this.payment_method=$.payment_method,this.payment_method_type=$.payment_method_type,this.setup_intent=$.setup_intent,this.source=$.source}}xZ.StripeError=v;v.generate=xZ.generateV1Error;class v$ extends v{constructor($={}){super($,"StripeCardError")}}xZ.StripeCardError=v$;class C8 extends v{constructor($={}){super($,"StripeInvalidRequestError")}}xZ.StripeInvalidRequestError=C8;class y$ extends v{constructor($={}){super($,"StripeAPIError")}}xZ.StripeAPIError=y$;class b$ extends v{constructor($={}){super($,"StripeAuthenticationError")}}xZ.StripeAuthenticationError=b$;class j$ extends v{constructor($={}){super($,"StripePermissionError")}}xZ.StripePermissionError=j$;class f$ extends v{constructor($={}){super($,"StripeRateLimitError")}}xZ.StripeRateLimitError=f$;class AZ extends v{constructor($={}){super($,"StripeConnectionError")}}xZ.StripeConnectionError=AZ;class NZ extends v{constructor($,Z,J={}){super(J,"StripeSignatureVerificationError");this.header=$,this.payload=Z}}xZ.StripeSignatureVerificationError=NZ;class k8 extends v{constructor($={}){super($,"StripeIdempotencyError")}}xZ.StripeIdempotencyError=k8;class d extends v{constructor($={},Z="StripeOAuthError"){super($,Z)}}xZ.StripeOAuthError=d;class M$ extends d{constructor($={}){super($,"StripeInvalidGrantError")}}xZ.StripeInvalidGrantError=M$;class _$ extends d{constructor($={}){super($,"StripeInvalidClientError")}}xZ.StripeInvalidClientError=_$;class g$ extends d{constructor($={}){super($,"StripeOAuthInvalidRequestError")}}xZ.StripeOAuthInvalidRequestError=g$;class h$ extends d{constructor($={}){super($,"StripeInvalidScopeError")}}xZ.StripeInvalidScopeError=h$;class m$ extends d{constructor($={}){super($,"StripeUnsupportedGrantTypeError")}}xZ.StripeUnsupportedGrantTypeError=m$;class u$ extends d{constructor($={}){super($,"StripeUnsupportedResponseTypeError")}}xZ.StripeUnsupportedResponseTypeError=u$;class c$ extends v{constructor($={}){super($,"RateLimitError")}}xZ.RateLimitError=c$;class n$ extends v{constructor($={}){super($,"TemporarySessionExpiredError")}}xZ.TemporarySessionExpiredError=n$});var fZ=K((bZ)=>{Object.defineProperty(bZ,"__esModule",{value:!0});bZ.NodePlatformFunctions=void 0;var A8=C("crypto"),PZ=C("events"),eW=i9(),SZ=XZ(),$U=kZ(),ZU=M0(),JU=c(),RZ=C("os");class vZ extends ZU.StripeError{}class yZ extends $U.PlatformFunctions{uuid4(){if(A8.randomUUID)return A8.randomUUID();return super.uuid4()}getPlatformInfo(){return`${process.platform} ${(0,RZ.release)()} ${(0,RZ.arch)()}`}secureCompare($,Z){if(!$||!Z)throw Error("secureCompare must receive two arguments");if($.length!==Z.length)return!1;if(A8.timingSafeEqual){let J=new TextEncoder,Q=J.encode($),X=J.encode(Z);return A8.timingSafeEqual(Q,X)}return super.secureCompare($,Z)}createEmitter(){return new PZ.EventEmitter}tryBufferData($){if(!($.file.data instanceof PZ.EventEmitter))return Promise.resolve($);let Z=[];return new Promise((J,Q)=>{$.file.data.on("data",(X)=>{Z.push(X)}).once("end",()=>{let X=Object.assign({},$);X.file.data=(0,JU.concat)(Z),J(X)}).on("error",(X)=>{Q(new vZ({message:"An error occurred while attempting to process the file for upload.",detail:X}))})})}createNodeHttpClient($){return new SZ.NodeHttpClient($)}createDefaultHttpClient(){return new SZ.NodeHttpClient}createNodeCryptoProvider(){return new eW.NodeCryptoProvider}createDefaultCryptoProvider(){return this.createNodeCryptoProvider()}}bZ.NodePlatformFunctions=yZ});var hZ=K((_Z)=>{Object.defineProperty(_Z,"__esModule",{value:!0});_Z.RequestSender=void 0;var w0=M0(),MZ=j0(),j=c(),QU=60;class _0{constructor($,Z){this._stripe=$,this._maxBufferedRequestMetric=Z}_normalizeStripeContext($,Z){if($)return $.toString()||null;return Z?.toString()||null}_addHeadersDirectlyToObject($,Z){$.requestId=Z["request-id"],$.stripeAccount=$.stripeAccount||Z["stripe-account"],$.apiVersion=$.apiVersion||Z["stripe-version"],$.idempotencyKey=$.idempotencyKey||Z["idempotency-key"]}_makeResponseEvent($,Z,J){let Q=Date.now(),X=Q-$.request_start_time;return(0,j.removeNullish)({api_version:J["stripe-version"],account:J["stripe-account"],idempotency_key:J["idempotency-key"],method:$.method,path:$.path,status:Z,request_id:this._getRequestId(J),elapsed:X,request_start_time:$.request_start_time,request_end_time:Q})}_getRequestId($){return $["request-id"]}_streamingResponseHandler($,Z,J){return(Q)=>{let X=Q.getHeaders(),Y=()=>{let V=this._makeResponseEvent($,Q.getStatusCode(),X);this._stripe._emitter.emit("response",V),this._recordRequestMetrics(this._getRequestId(X),V.elapsed,Z)},G=Q.toStream(Y);return this._addHeadersDirectlyToObject(G,X),J(null,G)}}_jsonResponseHandler($,Z,J,Q){return(X)=>{let Y=X.getHeaders(),G=this._getRequestId(Y),V=X.getStatusCode(),U=this._makeResponseEvent($,V,Y);this._stripe._emitter.emit("response",U),X.toJSON().then((W)=>{if(W.error){let B=typeof W.error==="string";if(B)W.error={type:W.error,message:W.error_description};W.error.headers=Y,W.error.statusCode=V,W.error.requestId=G;let z;if(B)z=(0,w0.generateOAuthError)(W.error);else if(Z==="v2")z=(0,w0.generateV2Error)(W.error);else z=(0,w0.generateV1Error)(W.error);throw z}return W},(W)=>{throw new w0.StripeAPIError({message:"Invalid JSON received from the Stripe API",exception:W,requestId:Y["request-id"]})}).then((W)=>{this._recordRequestMetrics(G,U.elapsed,J);let B=X.getRawResponse();this._addHeadersDirectlyToObject(B,Y),Object.defineProperty(W,"lastResponse",{enumerable:!1,writable:!1,value:B}),Q(null,W)},(W)=>Q(W,null))}}static _generateConnectionErrorMessage($){return`An error occurred with our connection to Stripe.${$>0?` Request was retried ${$} times.`:""}`}static _shouldRetry($,Z,J,Q){if(Q&&Z===0&&MZ.HttpClient.CONNECTION_CLOSED_ERROR_CODES.includes(Q.code))return!0;if(Z>=J)return!1;if(!$)return!0;if($.getHeaders()["stripe-should-retry"]==="false")return!1;if($.getHeaders()["stripe-should-retry"]==="true")return!0;if($.getStatusCode()===409)return!0;if($.getStatusCode()>=500)return!0;return!1}_getSleepTimeInMS($,Z=null){let J=this._stripe.getInitialNetworkRetryDelay(),Q=this._stripe.getMaxNetworkRetryDelay(),X=Math.min(J*Math.pow(2,$-1),Q);if(X*=0.5*(1+Math.random()),X=Math.max(J,X),Number.isInteger(Z)&&Z<=QU)X=Math.max(X,Z);return X*1000}_getMaxNetworkRetries($={}){return $.maxNetworkRetries!==void 0&&Number.isInteger($.maxNetworkRetries)?$.maxNetworkRetries:this._stripe.getMaxNetworkRetries()}_defaultIdempotencyKey($,Z,J){let Q=this._getMaxNetworkRetries(Z),X=()=>`stripe-node-retry-${this._stripe._platformFunctions.uuid4()}`;if(J==="v2"){if($==="POST"||$==="DELETE")return X()}else if(J==="v1"){if($==="POST"&&Q>0)return X()}return null}_makeHeaders({contentType:$,contentLength:Z,apiVersion:J,clientUserAgent:Q,method:X,userSuppliedHeaders:Y,userSuppliedSettings:G,stripeAccount:V,stripeContext:U,apiMode:W}){let B={Accept:"application/json","Content-Type":$,"User-Agent":this._getUserAgentString(W),"X-Stripe-Client-User-Agent":Q,"X-Stripe-Client-Telemetry":this._getTelemetryHeader(),"Stripe-Version":J,"Stripe-Account":V,"Stripe-Context":U,"Idempotency-Key":this._defaultIdempotencyKey(X,G,W)},z=X=="POST"||X=="PUT"||X=="PATCH";if(z||Z){if(!z)(0,j.emitWarning)(`${X} method had non-zero contentLength but no payload is expected for this verb`);B["Content-Length"]=Z}return Object.assign((0,j.removeNullish)(B),(0,j.normalizeHeaders)(Y))}_getUserAgentString($){let Z=this._stripe.getConstant("PACKAGE_VERSION"),J=this._stripe._appInfo?this._stripe.getAppInfoAsString():"",Q=this._stripe.getConstant("AI_AGENT"),X=`Stripe/${$} NodeBindings/${Z}`;if(J)X+=` ${J}`;if(Q)X+=` AIAgent/${Q}`;return X}_getTelemetryHeader(){if(this._stripe.getTelemetryEnabled()&&this._stripe._prevRequestMetrics.length>0){let $=this._stripe._prevRequestMetrics.shift();return JSON.stringify({last_request_metrics:$})}}_recordRequestMetrics($,Z,J){if(this._stripe.getTelemetryEnabled()&&$)if(this._stripe._prevRequestMetrics.length>this._maxBufferedRequestMetric)(0,j.emitWarning)("Request metrics buffer is full, dropping telemetry message.");else{let Q={request_id:$,request_duration_ms:Z};if(J&&J.length>0)Q.usage=J;this._stripe._prevRequestMetrics.push(Q)}}_rawRequest($,Z,J,Q,X){return new Promise((G,V)=>{let U;try{let H=$.toUpperCase();if(H!=="POST"&&J&&Object.keys(J).length!==0)throw Error("rawRequest only supports params on POST requests. Please pass null and add your parameters to path.");let T=[].slice.call([J,Q]),D=(0,j.getDataFromArgs)(T),q=H==="POST"?Object.assign({},D):null,O=(0,j.getOptionsFromArgs)(T),k=O.headers,N=O.authenticator;U={requestMethod:H,requestPath:Z,bodyData:q,queryData:{},authenticator:N,headers:k,host:O.host,streaming:!!O.streaming,settings:{},usage:X||["raw_request"]}}catch(H){V(H);return}function W(H,T){if(H)V(H);else G(T)}let{headers:B,settings:z}=U,L=U.authenticator;this._request(U.requestMethod,U.host,Z,U.bodyData,L,{headers:B,settings:z,streaming:U.streaming},U.usage,W)})}_getContentLength($){return typeof $==="string"?new TextEncoder().encode($).length:$.length}_request($,Z,J,Q,X,Y,G=[],V,U=null){let W;X=X??this._stripe._authenticator??null;let B=(0,j.getAPIMode)(J),z=(T,D,q,O,k)=>{return setTimeout(T,this._getSleepTimeInMS(O,k),D,q,O+1)},L=(T,D,q)=>{let O=Y.settings&&Y.settings.timeout&&Number.isInteger(Y.settings.timeout)&&Y.settings.timeout>=0?Y.settings.timeout:this._stripe.getApiField("timeout"),k={host:Z||this._stripe.getApiField("host"),port:this._stripe.getApiField("port"),path:J,method:$,headers:Object.assign({},D),body:W,protocol:this._stripe.getApiField("protocol")};X(k).then(()=>{let N=this._stripe.getApiField("httpClient").makeRequest(k.host,k.port,k.path,k.method,k.headers,k.body,k.protocol,O),R=Date.now(),M=(0,j.removeNullish)({api_version:T,account:(0,j.parseHttpHeaderAsString)(D["Stripe-Account"]),idempotency_key:(0,j.parseHttpHeaderAsString)(D["Idempotency-Key"]),method:$,path:J,request_start_time:R}),_=q||0,P0=this._getMaxNetworkRetries(Y.settings||{});this._stripe._emitter.emit("request",M),N.then((y)=>{if(_0._shouldRetry(y,_,P0))return z(L,T,D,_,(0,j.parseHttpHeaderAsNumber)(y.getHeaders()["retry-after"]));else if(Y.streaming&&y.getStatusCode()<400)return this._streamingResponseHandler(M,G,V)(y);else return this._jsonResponseHandler(M,B,G,V)(y)}).catch((y)=>{if(_0._shouldRetry(null,_,P0,y))return z(L,T,D,_,null);else{let i3=y.code&&y.code===MZ.HttpClient.TIMEOUT_ERROR_CODE;return V(new w0.StripeConnectionError({message:i3?`Request aborted due to timeout being reached (${O}ms)`:_0._generateConnectionErrorMessage(_),detail:y}))}})}).catch((N)=>{throw new w0.StripeError({message:"Unable to authenticate the request",exception:N})})},H=(T,D)=>{if(T)return V(T);W=D,this._stripe.getClientUserAgent((q)=>{let O=this._stripe.getApiField("version"),k=this._makeHeaders({contentType:B=="v2"?"application/json":"application/x-www-form-urlencoded",contentLength:this._getContentLength(D),apiVersion:O,clientUserAgent:q,method:$,userSuppliedHeaders:Y.headers??null,userSuppliedSettings:Y.settings??{},stripeAccount:Y.stripeAccount??this._stripe.getApiField("stripeAccount"),stripeContext:this._normalizeStripeContext(Y.stripeContext,this._stripe.getApiField("stripeContext")),apiMode:B});L(O,k,0)})};if(U)U($,Q,Y.headers,H);else{let T;if(B=="v2")T=Q?(0,j.jsonStringifyRequestData)(Q):"";else T=(0,j.queryStringifyRequestData)(Q||{});H(null,T)}}}_Z.RequestSender=_0});var dZ=K((lZ)=>{Object.defineProperty(lZ,"__esModule",{value:!0});lZ.makeAutoPaginationMethods=void 0;var N8=c();class d${constructor($,Z,J,Q){this.index=0,this.pagePromise=$,this.promiseCache={currentPromise:null},this.requestArgs=Z,this.spec=J,this.stripeResource=Q}async iterate($){if(!($&&$.data&&typeof $.data.length==="number"))throw Error("Unexpected: Stripe API response does not have a well-formed `data` array.");let Z=nZ(this.requestArgs);if(this.index<$.data.length){let J=Z?$.data.length-1-this.index:this.index,Q=$.data[J];return this.index+=1,{value:Q,done:!1}}else if($.has_more){this.index=0,this.pagePromise=this.getNextPage($);let J=await this.pagePromise;return this.iterate(J)}return{done:!0,value:void 0}}getNextPage($){throw Error("Unimplemented")}async _next(){return this.iterate(await this.pagePromise)}next(){if(this.promiseCache.currentPromise)return this.promiseCache.currentPromise;let $=(async()=>{let Z=await this._next();return this.promiseCache.currentPromise=null,Z})();return this.promiseCache.currentPromise=$,$}}class mZ extends d${getNextPage($){let Z=nZ(this.requestArgs),J=BU($,Z);return this.stripeResource._makeRequest(this.requestArgs,this.spec,{[Z?"ending_before":"starting_after"]:J})}}class uZ extends d${getNextPage($){if(!$.next_page)throw Error("Unexpected: Stripe API response does not have a well-formed `next_page` field, but `has_more` was true.");return this.stripeResource._makeRequest(this.requestArgs,this.spec,{page:$.next_page})}}class cZ{constructor($,Z,J,Q){this.firstPagePromise=$,this.currentPageIterator=null,this.nextPageUrl=null,this.requestArgs=Z,this.spec=J,this.stripeResource=Q}async initFirstPage(){if(this.firstPagePromise){let $=await this.firstPagePromise;this.firstPagePromise=null,this.currentPageIterator=$.data[Symbol.iterator](),this.nextPageUrl=$.next_page_url||null}}async turnPage(){if(!this.nextPageUrl)return null;this.spec.fullPath=this.nextPageUrl;let $=await this.stripeResource._makeRequest([],this.spec,{});return this.nextPageUrl=$.next_page_url||null,this.currentPageIterator=$.data[Symbol.iterator](),this.currentPageIterator}async next(){if(await this.initFirstPage(),this.currentPageIterator){let J=this.currentPageIterator.next();if(!J.done)return{done:!1,value:J.value}}let $=await this.turnPage();if(!$)return{done:!0,value:void 0};let Z=$.next();if(!Z.done)return{done:!1,value:Z.value};return{done:!0,value:void 0}}}var XU=($,Z,J,Q)=>{let X=(0,N8.getAPIMode)(J.fullPath||J.path);if(X!=="v2"&&J.methodType==="search")return p$(new uZ(Q,Z,J,$));if(X!=="v2"&&J.methodType==="list")return p$(new mZ(Q,Z,J,$));if(X==="v2"&&J.methodType==="list")return p$(new cZ(Q,Z,J,$));return null};lZ.makeAutoPaginationMethods=XU;var p$=($)=>{let Z=WU((...X)=>$.next(...X)),J=UU(Z),Q={autoPagingEach:Z,autoPagingToArray:J,next:()=>$.next(),return:()=>{return{}},[YU()]:()=>{return Q}};return Q};function YU(){if(typeof Symbol<"u"&&Symbol.asyncIterator)return Symbol.asyncIterator;return"@@asyncIterator"}function GU($){if($.length<2)return null;let Z=$[1];if(typeof Z!=="function")throw Error(`The second argument to autoPagingEach, if present, must be a callback function; received ${typeof Z}`);return Z}function VU($){if($.length===0)return;let Z=$[0];if(typeof Z!=="function")throw Error(`The first argument to autoPagingEach, if present, must be a callback function; received ${typeof Z}`);if(Z.length===2)return Z;if(Z.length>2)throw Error(`The \`onItem\` callback function passed to autoPagingEach must accept at most two arguments; got ${Z}`);return function(Q,X){let Y=Z(Q);X(Y)}}function BU($,Z){let J=Z?0:$.data.length-1,Q=$.data[J],X=Q&&Q.id;if(!X)throw Error("Unexpected: No `id` found on the last item while auto-paging a list.");return X}function WU($){return function(){let J=[].slice.call(arguments),Q=VU(J),X=GU(J);if(J.length>2)throw Error(`autoPagingEach takes up to two arguments; received ${J}`);let Y=zU($,Q);return(0,N8.callbackifyPromiseWithTimeout)(Y,X)}}function UU($){return function(J,Q){let X=J&&J.limit;if(!X)throw Error("You must pass a `limit` option to autoPagingToArray, e.g., `autoPagingToArray({limit: 1000});`.");if(X>1e4)throw Error("You cannot specify a limit of more than 10,000 items to fetch in `autoPagingToArray`; use `autoPagingEach` to iterate through longer lists.");let Y=new Promise((G,V)=>{let U=[];$((W)=>{if(U.push(W),U.length>=X)return!1}).then(()=>{G(U)}).catch(V)});return(0,N8.callbackifyPromiseWithTimeout)(Y,Q)}}function zU($,Z){return new Promise((J,Q)=>{function X(Y){if(Y.done){J();return}let G=Y.value;return new Promise((V)=>{Z(G,V)}).then((V)=>{if(V===!1)return X({done:!0,value:void 0});else return $().then(X)})}$().then(X).catch(Q)})}function nZ($){let Z=[].slice.call($);return!!(0,N8.getDataFromArgs)(Z).ending_before}});var sZ=K((aZ)=>{Object.defineProperty(aZ,"__esModule",{value:!0});aZ.stripeMethod=void 0;var iZ=c(),LU=dZ();function KU($){if($.path!==void 0&&$.fullPath!==void 0)throw Error(`Method spec specified both a 'path' (${$.path}) and a 'fullPath' (${$.fullPath}).`);return function(...Z){let J=typeof Z[Z.length-1]=="function"&&Z.pop();$.urlParams=(0,iZ.extractUrlParams)($.fullPath||this.createResourcePathWithSymbols($.path||""));let Q=(0,iZ.callbackifyPromiseWithTimeout)(this._makeRequest(Z,$,{}),J);return Object.assign(Q,(0,LU.makeAutoPaginationMethods)(this,Z,$,Q)),Q}}aZ.stripeMethod=KU});var I8=K((tZ)=>{Object.defineProperty(tZ,"__esModule",{value:!0});tZ.Decimal=tZ.isDecimal=tZ.DEFAULT_DIV_PRECISION=void 0;var HU={"ubb-usage-count":{mode:"significant-figures",value:15},"v1-api":{mode:"decimal-places",value:12}};tZ.DEFAULT_DIV_PRECISION=34;var rZ=30,x8=1e6;class P{constructor($,Z){let[J,Q]=P.normalize($,Z);this._coefficient=J,this._exponent=Q,Object.freeze(this)}static normalize($,Z){if($===0n)return[0n,0];let J=$,Q=Z;while(J!==0n&&J%10n===0n)J/=10n,Q+=1;return[J,Q]}static roundDivision($,Z,J,Q){if(Z===0n)return $;if(Q==="round-down")return $;let X=Z>0n===J>0n?1n:-1n;if(Q==="round-up")return $+X;if(Q==="ceil")return X===1n?$+1n:$;if(Q==="floor")return X===-1n?$-1n:$;let Y=Z<0n?-Z:Z,G=J<0n?-J:J,V=Y*2n,U;if(V===G)U=0;else if(V<G)U=-1;else U=1;if(U<0)return $;if(U>0)return $+X;if(Q==="half-up")return $+X;if(Q==="half-down")return $;if($%2n===0n)return $;else return $+X}add($){let Z=$;if(this._exponent===Z._exponent)return new P(this._coefficient+Z._coefficient,this._exponent);if(this._exponent<Z._exponent){let J=10n**BigInt(Z._exponent-this._exponent);return new P(this._coefficient+Z._coefficient*J,this._exponent)}else{let J=10n**BigInt(this._exponent-Z._exponent);return new P(this._coefficient*J+Z._coefficient,Z._exponent)}}sub($){let Z=$;if(this._exponent===Z._exponent)return new P(this._coefficient-Z._coefficient,this._exponent);if(this._exponent<Z._exponent){let J=10n**BigInt(Z._exponent-this._exponent);return new P(this._coefficient-Z._coefficient*J,this._exponent)}else{let J=10n**BigInt(this._exponent-Z._exponent);return new P(this._coefficient*J-Z._coefficient,Z._exponent)}}mul($){let Z=$;return new P(this._coefficient*Z._coefficient,this._exponent+Z._exponent)}div($,Z,J){if(Z<0||!Number.isInteger(Z))throw Error("precision must be a non-negative integer");let Q=$;if(Q._coefficient===0n)throw Error("Division by zero");let X=this._exponent-Q._exponent+Z,Y,G,V;if(X>=0){let W=this._coefficient*10n**BigInt(X);Y=W/Q._coefficient,G=W%Q._coefficient,V=Q._coefficient}else{let W=Q._coefficient*10n**BigInt(-X);Y=this._coefficient/W,G=this._coefficient%W,V=W}let U=P.roundDivision(Y,G,V,J);return new P(U,-Z)}cmp($){let Z=$;if(this._exponent===Z._exponent){if(this._coefficient<Z._coefficient)return-1;if(this._coefficient>Z._coefficient)return 1;return 0}if(this._exponent<Z._exponent){let J=10n**BigInt(Z._exponent-this._exponent),Q=Z._coefficient*J;if(this._coefficient<Q)return-1;if(this._coefficient>Q)return 1;return 0}else{let J=10n**BigInt(this._exponent-Z._exponent),Q=this._coefficient*J;if(Q<Z._coefficient)return-1;if(Q>Z._coefficient)return 1;return 0}}eq($){return this.cmp($)===0}lt($){return this.cmp($)===-1}lte($){return this.cmp($)<=0}gt($){return this.cmp($)===1}gte($){return this.cmp($)>=0}isZero(){return this._coefficient===0n}isNegative(){return this._coefficient<0n}isPositive(){return this._coefficient>0n}neg(){return new P(-this._coefficient,this._exponent)}abs(){if(this._coefficient<0n)return new P(-this._coefficient,this._exponent);return this}round($,Z){let J=typeof Z==="string"?HU[Z]:Z;if(J===void 0)throw Error(`Unknown rounding preset: "${Z}"`);if(J.value<0||!Number.isInteger(J.value))throw Error("DecimalRoundingOptions.value must be a non-negative integer");if(J.mode==="decimal-places"){let B=this.toFixed(J.value,$);return tZ.Decimal.from(B)}if(this._coefficient===0n)return this;let X=(this._coefficient<0n?(-this._coefficient).toString():this._coefficient.toString()).length;if(J.value===0)return tZ.Decimal.zero;if(X<=J.value)return this;let Y=X-J.value,G=10n**BigInt(Y),V=this._coefficient/G,U=this._coefficient%G,W=P.roundDivision(V,U,G,$);return new P(W,this._exponent+Y)}toString(){if(this._coefficient===0n)return"0";let $=this._coefficient.toString(),Z=$.startsWith("-"),J=Z?$.slice(1):$;if(this._exponent<0){let X=-this._exponent;if((X>=J.length?X-J.length:0)>rZ){if(J.length===1)return`${$}E${String(this._exponent)}`;let G=J[0]??"",V=J.slice(1),U=this._exponent+J.length-1;return`${Z?"-":""}${G}.${V}E${String(U)}`}if(X>=J.length){let G="0".repeat(X-J.length);return`${Z?"-":""}0.${G}${J}`}else{let G=J.slice(0,J.length-X),V=J.slice(J.length-X);return`${Z?"-":""}${G}.${V}`}}if(J.length+this._exponent<=rZ){if(this._exponent===0)return $;let X="0".repeat(this._exponent);return`${Z?"-":""}${J}${X}`}else{if(J.length===1)return`${$}E+${String(this._exponent)}`;let X=J[0]??"",Y=J.slice(1),G=this._exponent+J.length-1;return`${Z?"-":""}${X}.${Y}E+${String(G)}`}}toJSON(){return this.toString()}toNumber(){return Number(this.toString())}toFixed($,Z){if($<0||!Number.isInteger($))throw Error("decimalPlaces must be a non-negative integer");let J=(X)=>{let Y=X.toString(),G=Y.startsWith("-"),V=G?Y.slice(1):Y;if($===0)return Y;if($>=V.length){let U="0".repeat($-V.length);return`${G?"-":""}0.${U}${V}`}else{let U=V.slice(0,V.length-$),W=V.slice(V.length-$);return`${G?"-":""}${U}.${W}`}},Q=-$;if(this._exponent===Q)return J(this._coefficient);if(this._exponent<Q){let X=Q-this._exponent,Y=10n**BigInt(X),G=this._coefficient/Y,V=this._coefficient%Y,U=P.roundDivision(G,V,Y,Z);return J(U)}else{let X=this._exponent-Q,Y=this._coefficient*10n**BigInt(X);return J(Y)}}valueOf(){return this.toString()}}function wU($){return $ instanceof P}tZ.isDecimal=wU;tZ.Decimal={from($){if(typeof $==="bigint")return new P($,0);if(typeof $==="number"){if(!Number.isFinite($))throw Error("Number must be finite");return tZ.Decimal.from($.toString())}let Z=$.trim();if(Z==="")throw Error("Cannot parse empty string as Decimal");let J=/^([+-]?)(\d+)(?:\.(\d+))?(?:[eE]([+-]?\d+))?$/.exec(Z);if(!J)throw Error(`Invalid decimal string: ${$}`);let Q=J[1]==="-"?-1n:1n,X=J[2]??"",Y=J[3]??"",G=J[4]?Number(J[4]):0;if(!Number.isSafeInteger(G)||G>x8||G<-x8)throw Error(`Exponent out of range: ${String(J[4])} exceeds safe integer bounds`);let V=X+Y,U=Q*BigInt(V),W=G-Y.length;if(!Number.isSafeInteger(W)||W>x8||W<-x8)throw Error(`Computed exponent out of range: ${String(W)} exceeds safe integer bounds`);return new P(U,W)},zero:new P(0n,0)}});var $1=K((eZ)=>{Object.defineProperty(eZ,"__esModule",{value:!0});eZ.coerceV2ResponseData=eZ.coerceV2RequestData=void 0;var OU=I8(),qU=($,Z)=>{if($==null)return $;switch(Z.kind){case"int64_string":return typeof $==="bigint"||typeof $==="number"?String($):$;case"decimal_string":return typeof $.toFixed==="function"&&typeof $.isZero==="function"?$.toString():$;case"object":{if(typeof $!=="object"||Array.isArray($))return $;let J=$,Q={};for(let X of Object.keys(J)){let Y=Z.fields[X];Q[X]=Y?eZ.coerceV2RequestData(J[X],Y):J[X]}return Q}case"array":{if(!Array.isArray($))return $;return $.map((J)=>eZ.coerceV2RequestData(J,Z.element))}case"nullable":return eZ.coerceV2RequestData($,Z.inner)}};eZ.coerceV2RequestData=qU;var EU=($,Z)=>{if($==null)return $;switch(Z.kind){case"int64_string":if(typeof $==="string")try{return BigInt($)}catch{throw Error(`Failed to coerce int64_string value: expected an integer string, got '${$}'`)}return $;case"decimal_string":if(typeof $==="string")try{return OU.Decimal.from($)}catch{throw Error(`Failed to coerce decimal_string value: expected a decimal string, got '${$}'`)}return $;case"object":{if(typeof $!=="object"||Array.isArray($))return $;let J=$;for(let Q of Object.keys(Z.fields))if(Q in J)J[Q]=eZ.coerceV2ResponseData(J[Q],Z.fields[Q]);return J}case"array":{if(!Array.isArray($))return $;for(let J=0;J<$.length;J++)$[J]=eZ.coerceV2ResponseData($[J],Z.element);return $}case"nullable":return eZ.coerceV2ResponseData($,Z.inner)}};eZ.coerceV2ResponseData=EU});var w=K((J1)=>{Object.defineProperty(J1,"__esModule",{value:!0});J1.StripeResource=void 0;var J0=c(),FU=sZ(),Z1=$1();m0.extend=J0.protoExtend;m0.method=FU.stripeMethod;m0.MAX_BUFFERED_REQUEST_METRICS=100;function m0($,Z){if(this._stripe=$,Z)throw Error("Support for curried url params was dropped in stripe-node v7.0.0. Instead, pass two ids.");this.basePath=(0,J0.makeURLInterpolator)(this.basePath||$.getApiField("basePath")),this.resourcePath=this.path,this.path=(0,J0.makeURLInterpolator)(this.path),this.initialize(...arguments)}J1.StripeResource=m0;m0.prototype={_stripe:null,path:"",resourcePath:"",basePath:null,initialize(){},requestDataProcessor:null,validateRequest:null,createFullPath($,Z){let J=[this.basePath(Z),this.path(Z)];if(typeof $==="function"){let Q=$(Z);if(Q)J.push(Q)}else J.push($);return this._joinUrlParts(J)},createResourcePathWithSymbols($){if($)return`/${this._joinUrlParts([this.resourcePath,$])}`;else return`/${this.resourcePath}`},_joinUrlParts($){return $.join("/").replace(/\/{2,}/g,"/")},_getRequestOpts($,Z,J){let Q=(Z.method||"GET").toUpperCase(),X=Z.usage||[],Y=Z.urlParams||[],G=Z.encode||((_)=>_),V=!!Z.fullPath,U=(0,J0.makeURLInterpolator)(V?Z.fullPath:Z.path||""),W=V?Z.fullPath:this.createResourcePathWithSymbols(Z.path),B=[].slice.call($),z=Y.reduce((_,P0)=>{let y=B.shift();if(typeof y!=="string")throw Error(`Stripe: Argument "${P0}" must be a string, but got: ${y} (on API request to \`${Q} ${W}\`)`);return _[P0]=y,_},{}),L=(0,J0.getDataFromArgs)(B),H=G(Object.assign({},L,J)),T=(0,J0.getOptionsFromArgs)(B),D=T.host||Z.host,q=!!Z.streaming||!!T.streaming;if(B.filter((_)=>_!=null).length)throw Error(`Stripe: Unknown arguments (${B}). Did you mean to pass an options object? See https://github.com/stripe/stripe-node/wiki/Passing-Options. (on API request to ${Q} \`${W}\`)`);let O=V?U(z):this.createFullPath(U,z),k=Object.assign(T.headers,Z.headers);if(Z.validator)Z.validator(H,{headers:k});let N=Z.method==="GET"||Z.method==="DELETE";return{requestMethod:Q,requestPath:O,bodyData:N?null:H,queryData:N?H:{},authenticator:T.authenticator??null,headers:k,host:D??null,streaming:q,settings:T.settings,usage:X}},_makeRequest($,Z,J){return new Promise((Q,X)=>{let Y;try{Y=this._getRequestOpts($,Z,J)}catch(z){X(z);return}if(Z.requestSchema&&Y.bodyData)Y.bodyData=(0,Z1.coerceV2RequestData)(Y.bodyData,Z.requestSchema);function G(z,L){if(z)X(z);else try{if(Z.responseSchema)(0,Z1.coerceV2ResponseData)(L,Z.responseSchema);Q(Z.transformResponseData?Z.transformResponseData(L):L)}catch(H){X(H)}}let V=Object.keys(Y.queryData).length===0,U=[Y.requestPath,V?"":"?",(0,J0.queryStringifyRequestData)(Y.queryData)].join(""),{headers:W,settings:B}=Y;this._stripe._requestSender._request(Y.requestMethod,Y.host,U,Y.bodyData,Y.authenticator,{headers:W,settings:B,streaming:Y.streaming},Y.usage,G,this.requestDataProcessor?.bind(this))})}}});var G1=K((X1)=>{Object.defineProperty(X1,"__esModule",{value:!0});X1.StripeContext=void 0;class T0{constructor($=[]){this._segments=[...$]}get segments(){return[...this._segments]}push($){if(!$)throw Error("Segment cannot be null or undefined");return new T0([...this._segments,$])}pop(){if(this._segments.length===0)throw Error("Cannot pop from an empty context");return new T0(this._segments.slice(0,-1))}toString(){return this._segments.join("/")}static parse($){if(!$)return new T0([]);return new T0($.split("/"))}}X1.StripeContext=T0});var W1=K((V1)=>{Object.defineProperty(V1,"__esModule",{value:!0});V1.createWebhooks=void 0;var o=M0(),CU=b0();function kU($){let Z={DEFAULT_TOLERANCE:300,signature:null,constructEvent(B,z,L,H,T,D){try{if(!this.signature)throw Error("ERR: missing signature helper, unable to verify");this.signature.verifyHeader(B,z,L,H||Z.DEFAULT_TOLERANCE,T,D)}catch(O){if(O instanceof CU.CryptoProviderOnlySupportsAsyncError)O.message+="\nUse `await constructEventAsync(...)` instead of `constructEvent(...)`";throw O}let q=B instanceof Uint8Array?JSON.parse(new TextDecoder("utf8").decode(B)):JSON.parse(B);if(q&&q.object==="v2.core.event")throw Error("You passed an event notification to stripe.webhooks.constructEvent, which expects a webhook payload. Use stripe.parseEventNotification instead.");return q},async constructEventAsync(B,z,L,H,T,D){if(!this.signature)throw Error("ERR: missing signature helper, unable to verify");await this.signature.verifyHeaderAsync(B,z,L,H||Z.DEFAULT_TOLERANCE,T,D);let q=B instanceof Uint8Array?JSON.parse(new TextDecoder("utf8").decode(B)):JSON.parse(B);if(q&&q.object==="v2.core.event")throw Error("You passed an event notification to stripe.webhooks.constructEvent, which expects a webhook payload. Use stripe.parseEventNotification instead.");return q},generateTestHeaderString:function(B){let z=W(B),L=z.signature||z.cryptoProvider.computeHMACSignature(z.payloadString,z.secret);return z.generateHeaderString(L)},generateTestHeaderStringAsync:async function(B){let z=W(B),L=z.signature||await z.cryptoProvider.computeHMACSignatureAsync(z.payloadString,z.secret);return z.generateHeaderString(L)}},J={EXPECTED_SCHEME:"v1",verifyHeader(B,z,L,H,T,D){let{decodedHeader:q,decodedPayload:O,details:k,suspectPayloadType:N}=X(B,z,this.EXPECTED_SCHEME),R=/\s/.test(L);T=T||U();let M=T.computeHMACSignature(Q(O,k),L);return Y(O,q,k,M,H,N,R,D),!0},async verifyHeaderAsync(B,z,L,H,T,D){let{decodedHeader:q,decodedPayload:O,details:k,suspectPayloadType:N}=X(B,z,this.EXPECTED_SCHEME),R=/\s/.test(L);T=T||U();let M=await T.computeHMACSignatureAsync(Q(O,k),L);return Y(O,q,k,M,H,N,R,D)}};function Q(B,z){return`${z.timestamp}.${B}`}function X(B,z,L){if(!B)throw new o.StripeSignatureVerificationError(z,B,{message:"No webhook payload was provided."});let H=typeof B!="string"&&!(B instanceof Uint8Array),T=new TextDecoder("utf8"),D=B instanceof Uint8Array?T.decode(B):B;if(Array.isArray(z))throw Error("Unexpected: An array was passed as a header, which should not be possible for the stripe-signature header.");if(z==null||z=="")throw new o.StripeSignatureVerificationError(z,B,{message:"No stripe-signature header value was provided."});let q=z instanceof Uint8Array?T.decode(z):z,O=G(q,L);if(!O||O.timestamp===-1)throw new o.StripeSignatureVerificationError(q,D,{message:"Unable to extract timestamp and signatures from header"});if(!O.signatures.length)throw new o.StripeSignatureVerificationError(q,D,{message:"No signatures found with expected scheme"});return{decodedPayload:D,decodedHeader:q,details:O,suspectPayloadType:H}}function Y(B,z,L,H,T,D,q,O){let k=!!L.signatures.filter($.secureCompare.bind($,H)).length,N=`
|
|
3
|
+
Learn more about webhook signing and explore webhook integration examples for various frameworks at https://docs.stripe.com/webhooks/signature`,R=q?`
|
|
4
4
|
|
|
5
|
-
Note: The provided signing secret contains whitespace. This often indicates an extra newline or space is in the value`:"";if(!
|
|
5
|
+
Note: The provided signing secret contains whitespace. This often indicates an extra newline or space is in the value`:"";if(!k){if(D)throw new o.StripeSignatureVerificationError(z,B,{message:`Webhook payload must be provided as a string or a Buffer (https://nodejs.org/api/buffer.html) instance representing the _raw_ request body.Payload was provided as a parsed JavaScript object instead.
|
|
6
6
|
Signature verification is impossible without access to the original signed material.
|
|
7
|
-
`+
|
|
8
|
-
`+
|
|
7
|
+
`+N+`
|
|
8
|
+
`+R});throw new o.StripeSignatureVerificationError(z,B,{message:`No signatures found matching the expected signature for payload. Are you passing the raw request body you received from Stripe?
|
|
9
9
|
If a webhook request is being forwarded by a third-party tool, ensure that the exact request body, including JSON formatting and new line style, is preserved.
|
|
10
|
-
`+
|
|
11
|
-
`+C})}let f=Math.floor((typeof T==="number"?T:Date.now())/1000)-S.timestamp;if(U>0&&f>U)throw new Kk(Y,G,{message:"Timestamp outside the tolerance zone"});return!0}function Z(G,Y){if(typeof G!=="string")return null;return G.split(",").reduce((S,z)=>{let U=z.split("=");if(U[0]==="t")S.timestamp=parseInt(U[1],10);if(U[0]===Y)S.signatures.push(U[1]);return S},{timestamp:-1,signatures:[]})}let X=null;function E(){if(!X)X=_.createDefaultCryptoProvider();return X}function F(G){if(!G)throw new N_({message:"Options are required"});let Y=Math.floor(G.timestamp)||Math.floor(Date.now()/1000),S=G.scheme||j.EXPECTED_SCHEME,z=G.cryptoProvider||E(),U=`${Y}.${G.payload}`;return{...G,timestamp:Y,scheme:S,cryptoProvider:z,payloadString:U,generateHeaderString:(I)=>{return`t=${Y},${S}=${I}`}}}return k.signature=j,k}var X7=R(()=>{f0();R0()});var Q$="2026-03-25.dahlia";function iQ(_,k){for(let j in k){if(!Object.prototype.hasOwnProperty.call(k,j))continue;let d=j[0].toLowerCase()+j.substring(1),O=new k[j](_);this[d]=O}}function n_(_,k){return function(j){return new iQ(j,k)}}var BQ,E7;var G7=R(()=>{M();BQ=P.method,E7=P.extend({create:BQ({method:"POST",fullPath:"/v2/core/account_links"})})});var F7,z7;var S7=R(()=>{M();F7=P.method,z7=P.extend({create:F7({method:"POST",fullPath:"/v2/core/account_tokens",requestSchema:{kind:"object",fields:{identity:{kind:"object",fields:{individual:{kind:"object",fields:{relationship:{kind:"object",fields:{percent_ownership:{kind:"decimal_string"}}}}}}}}}}),retrieve:F7({method:"GET",fullPath:"/v2/core/account_tokens/{id}"})})});var zj,Y7;var L7=R(()=>{M();zj=P.method,Y7=P.extend({retrieve:zj({method:"GET",fullPath:"/v1/financial_connections/accounts/{account}"}),list:zj({method:"GET",fullPath:"/v1/financial_connections/accounts",methodType:"list"}),disconnect:zj({method:"POST",fullPath:"/v1/financial_connections/accounts/{account}/disconnect"}),listOwners:zj({method:"GET",fullPath:"/v1/financial_connections/accounts/{account}/owners",methodType:"list"}),refresh:zj({method:"POST",fullPath:"/v1/financial_connections/accounts/{account}/refresh"}),subscribe:zj({method:"POST",fullPath:"/v1/financial_connections/accounts/{account}/subscribe"}),unsubscribe:zj({method:"POST",fullPath:"/v1/financial_connections/accounts/{account}/unsubscribe"})})});var Zd,P7;var U7=R(()=>{M();Zd=P.method,P7=P.extend({create:Zd({method:"POST",fullPath:"/v2/core/accounts/{account_id}/persons",requestSchema:{kind:"object",fields:{relationship:{kind:"object",fields:{percent_ownership:{kind:"decimal_string"}}}}},responseSchema:{kind:"object",fields:{relationship:{kind:"object",fields:{percent_ownership:{kind:"decimal_string"}}}}}}),retrieve:Zd({method:"GET",fullPath:"/v2/core/accounts/{account_id}/persons/{id}",responseSchema:{kind:"object",fields:{relationship:{kind:"object",fields:{percent_ownership:{kind:"decimal_string"}}}}}}),update:Zd({method:"POST",fullPath:"/v2/core/accounts/{account_id}/persons/{id}",requestSchema:{kind:"object",fields:{relationship:{kind:"object",fields:{percent_ownership:{kind:"decimal_string"}}}}},responseSchema:{kind:"object",fields:{relationship:{kind:"object",fields:{percent_ownership:{kind:"decimal_string"}}}}}}),list:Zd({method:"GET",fullPath:"/v2/core/accounts/{account_id}/persons",methodType:"list",responseSchema:{kind:"object",fields:{data:{kind:"array",element:{kind:"object",fields:{relationship:{kind:"object",fields:{percent_ownership:{kind:"decimal_string"}}}}}}}}}),del:Zd({method:"DELETE",fullPath:"/v2/core/accounts/{account_id}/persons/{id}"})})});var Q7,V7;var T7=R(()=>{M();Q7=P.method,V7=P.extend({create:Q7({method:"POST",fullPath:"/v2/core/accounts/{account_id}/person_tokens",requestSchema:{kind:"object",fields:{relationship:{kind:"object",fields:{percent_ownership:{kind:"decimal_string"}}}}}}),retrieve:Q7({method:"GET",fullPath:"/v2/core/accounts/{account_id}/person_tokens/{id}"})})});var Xd,W7;var K7=R(()=>{M();U7();T7();Xd=P.method,W7=P.extend({constructor:function(..._){P.apply(this,_),this.persons=new P7(..._),this.personTokens=new V7(..._)},create:Xd({method:"POST",fullPath:"/v2/core/accounts",requestSchema:{kind:"object",fields:{identity:{kind:"object",fields:{individual:{kind:"object",fields:{relationship:{kind:"object",fields:{percent_ownership:{kind:"decimal_string"}}}}}}}}},responseSchema:{kind:"object",fields:{identity:{kind:"object",fields:{individual:{kind:"object",fields:{relationship:{kind:"object",fields:{percent_ownership:{kind:"decimal_string"}}}}}}}}}}),retrieve:Xd({method:"GET",fullPath:"/v2/core/accounts/{id}",responseSchema:{kind:"object",fields:{identity:{kind:"object",fields:{individual:{kind:"object",fields:{relationship:{kind:"object",fields:{percent_ownership:{kind:"decimal_string"}}}}}}}}}}),update:Xd({method:"POST",fullPath:"/v2/core/accounts/{id}",requestSchema:{kind:"object",fields:{identity:{kind:"object",fields:{individual:{kind:"object",fields:{relationship:{kind:"object",fields:{percent_ownership:{kind:"decimal_string"}}}}}}}}},responseSchema:{kind:"object",fields:{identity:{kind:"object",fields:{individual:{kind:"object",fields:{relationship:{kind:"object",fields:{percent_ownership:{kind:"decimal_string"}}}}}}}}}}),list:Xd({method:"GET",fullPath:"/v2/core/accounts",methodType:"list",responseSchema:{kind:"object",fields:{data:{kind:"array",element:{kind:"object",fields:{identity:{kind:"object",fields:{individual:{kind:"object",fields:{relationship:{kind:"object",fields:{percent_ownership:{kind:"decimal_string"}}}}}}}}}}}}}),close:Xd({method:"POST",fullPath:"/v2/core/accounts/{id}/close",responseSchema:{kind:"object",fields:{identity:{kind:"object",fields:{individual:{kind:"object",fields:{relationship:{kind:"object",fields:{percent_ownership:{kind:"decimal_string"}}}}}}}}}})})});var n7,J7;var I7=R(()=>{M();n7=P.method,J7=P.extend({retrieve:n7({method:"GET",fullPath:"/v1/entitlements/active_entitlements/{id}"}),list:n7({method:"GET",fullPath:"/v1/entitlements/active_entitlements",methodType:"list"})})});var rj,D7;var R7=R(()=>{M();rj=P.method,D7=P.extend({create:rj({method:"POST",fullPath:"/v1/billing/alerts"}),retrieve:rj({method:"GET",fullPath:"/v1/billing/alerts/{id}"}),list:rj({method:"GET",fullPath:"/v1/billing/alerts",methodType:"list"}),activate:rj({method:"POST",fullPath:"/v1/billing/alerts/{id}/activate"}),archive:rj({method:"POST",fullPath:"/v1/billing/alerts/{id}/archive"}),deactivate:rj({method:"POST",fullPath:"/v1/billing/alerts/{id}/deactivate"})})});var cQ,w7;var M7=R(()=>{M();cQ=P.method,w7=P.extend({find:cQ({method:"GET",fullPath:"/v1/tax/associations/find"})})});var Ed,C7;var h7=R(()=>{M();Ed=P.method,C7=P.extend({retrieve:Ed({method:"GET",fullPath:"/v1/issuing/authorizations/{authorization}",responseSchema:{kind:"object",fields:{fleet:{kind:"nullable",inner:{kind:"object",fields:{reported_breakdown:{kind:"nullable",inner:{kind:"object",fields:{fuel:{kind:"nullable",inner:{kind:"object",fields:{gross_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},non_fuel:{kind:"nullable",inner:{kind:"object",fields:{gross_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},tax:{kind:"nullable",inner:{kind:"object",fields:{local_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},national_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}}}}}},fuel:{kind:"nullable",inner:{kind:"object",fields:{quantity_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_cost_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},transactions:{kind:"array",element:{kind:"object",fields:{purchase_details:{kind:"nullable",inner:{kind:"object",fields:{fleet:{kind:"nullable",inner:{kind:"object",fields:{reported_breakdown:{kind:"nullable",inner:{kind:"object",fields:{fuel:{kind:"nullable",inner:{kind:"object",fields:{gross_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},non_fuel:{kind:"nullable",inner:{kind:"object",fields:{gross_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},tax:{kind:"nullable",inner:{kind:"object",fields:{local_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},national_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}}}}}},fuel:{kind:"nullable",inner:{kind:"object",fields:{quantity_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_cost_decimal:{kind:"decimal_string"}}}}}}}}}}}}}),update:Ed({method:"POST",fullPath:"/v1/issuing/authorizations/{authorization}",responseSchema:{kind:"object",fields:{fleet:{kind:"nullable",inner:{kind:"object",fields:{reported_breakdown:{kind:"nullable",inner:{kind:"object",fields:{fuel:{kind:"nullable",inner:{kind:"object",fields:{gross_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},non_fuel:{kind:"nullable",inner:{kind:"object",fields:{gross_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},tax:{kind:"nullable",inner:{kind:"object",fields:{local_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},national_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}}}}}},fuel:{kind:"nullable",inner:{kind:"object",fields:{quantity_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_cost_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},transactions:{kind:"array",element:{kind:"object",fields:{purchase_details:{kind:"nullable",inner:{kind:"object",fields:{fleet:{kind:"nullable",inner:{kind:"object",fields:{reported_breakdown:{kind:"nullable",inner:{kind:"object",fields:{fuel:{kind:"nullable",inner:{kind:"object",fields:{gross_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},non_fuel:{kind:"nullable",inner:{kind:"object",fields:{gross_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},tax:{kind:"nullable",inner:{kind:"object",fields:{local_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},national_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}}}}}},fuel:{kind:"nullable",inner:{kind:"object",fields:{quantity_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_cost_decimal:{kind:"decimal_string"}}}}}}}}}}}}}),list:Ed({method:"GET",fullPath:"/v1/issuing/authorizations",methodType:"list",responseSchema:{kind:"object",fields:{data:{kind:"array",element:{kind:"object",fields:{fleet:{kind:"nullable",inner:{kind:"object",fields:{reported_breakdown:{kind:"nullable",inner:{kind:"object",fields:{fuel:{kind:"nullable",inner:{kind:"object",fields:{gross_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},non_fuel:{kind:"nullable",inner:{kind:"object",fields:{gross_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},tax:{kind:"nullable",inner:{kind:"object",fields:{local_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},national_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}}}}}},fuel:{kind:"nullable",inner:{kind:"object",fields:{quantity_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_cost_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},transactions:{kind:"array",element:{kind:"object",fields:{purchase_details:{kind:"nullable",inner:{kind:"object",fields:{fleet:{kind:"nullable",inner:{kind:"object",fields:{reported_breakdown:{kind:"nullable",inner:{kind:"object",fields:{fuel:{kind:"nullable",inner:{kind:"object",fields:{gross_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},non_fuel:{kind:"nullable",inner:{kind:"object",fields:{gross_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},tax:{kind:"nullable",inner:{kind:"object",fields:{local_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},national_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}}}}}},fuel:{kind:"nullable",inner:{kind:"object",fields:{quantity_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_cost_decimal:{kind:"decimal_string"}}}}}}}}}}}}}}}}),approve:Ed({method:"POST",fullPath:"/v1/issuing/authorizations/{authorization}/approve",responseSchema:{kind:"object",fields:{fleet:{kind:"nullable",inner:{kind:"object",fields:{reported_breakdown:{kind:"nullable",inner:{kind:"object",fields:{fuel:{kind:"nullable",inner:{kind:"object",fields:{gross_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},non_fuel:{kind:"nullable",inner:{kind:"object",fields:{gross_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},tax:{kind:"nullable",inner:{kind:"object",fields:{local_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},national_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}}}}}},fuel:{kind:"nullable",inner:{kind:"object",fields:{quantity_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_cost_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},transactions:{kind:"array",element:{kind:"object",fields:{purchase_details:{kind:"nullable",inner:{kind:"object",fields:{fleet:{kind:"nullable",inner:{kind:"object",fields:{reported_breakdown:{kind:"nullable",inner:{kind:"object",fields:{fuel:{kind:"nullable",inner:{kind:"object",fields:{gross_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},non_fuel:{kind:"nullable",inner:{kind:"object",fields:{gross_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},tax:{kind:"nullable",inner:{kind:"object",fields:{local_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},national_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}}}}}},fuel:{kind:"nullable",inner:{kind:"object",fields:{quantity_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_cost_decimal:{kind:"decimal_string"}}}}}}}}}}}}}),decline:Ed({method:"POST",fullPath:"/v1/issuing/authorizations/{authorization}/decline",responseSchema:{kind:"object",fields:{fleet:{kind:"nullable",inner:{kind:"object",fields:{reported_breakdown:{kind:"nullable",inner:{kind:"object",fields:{fuel:{kind:"nullable",inner:{kind:"object",fields:{gross_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},non_fuel:{kind:"nullable",inner:{kind:"object",fields:{gross_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},tax:{kind:"nullable",inner:{kind:"object",fields:{local_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},national_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}}}}}},fuel:{kind:"nullable",inner:{kind:"object",fields:{quantity_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_cost_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},transactions:{kind:"array",element:{kind:"object",fields:{purchase_details:{kind:"nullable",inner:{kind:"object",fields:{fleet:{kind:"nullable",inner:{kind:"object",fields:{reported_breakdown:{kind:"nullable",inner:{kind:"object",fields:{fuel:{kind:"nullable",inner:{kind:"object",fields:{gross_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},non_fuel:{kind:"nullable",inner:{kind:"object",fields:{gross_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},tax:{kind:"nullable",inner:{kind:"object",fields:{local_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},national_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}}}}}},fuel:{kind:"nullable",inner:{kind:"object",fields:{quantity_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_cost_decimal:{kind:"decimal_string"}}}}}}}}}}}}})})});var Sj,f7;var q7=R(()=>{M();Sj=P.method,f7=P.extend({create:Sj({method:"POST",fullPath:"/v1/test_helpers/issuing/authorizations",requestSchema:{kind:"object",fields:{fleet:{kind:"object",fields:{reported_breakdown:{kind:"object",fields:{fuel:{kind:"object",fields:{gross_amount_decimal:{kind:"decimal_string"}}},non_fuel:{kind:"object",fields:{gross_amount_decimal:{kind:"decimal_string"}}},tax:{kind:"object",fields:{local_amount_decimal:{kind:"decimal_string"},national_amount_decimal:{kind:"decimal_string"}}}}}}},fuel:{kind:"object",fields:{quantity_decimal:{kind:"decimal_string"},unit_cost_decimal:{kind:"decimal_string"}}}}},responseSchema:{kind:"object",fields:{fleet:{kind:"nullable",inner:{kind:"object",fields:{reported_breakdown:{kind:"nullable",inner:{kind:"object",fields:{fuel:{kind:"nullable",inner:{kind:"object",fields:{gross_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},non_fuel:{kind:"nullable",inner:{kind:"object",fields:{gross_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},tax:{kind:"nullable",inner:{kind:"object",fields:{local_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},national_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}}}}}},fuel:{kind:"nullable",inner:{kind:"object",fields:{quantity_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_cost_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},transactions:{kind:"array",element:{kind:"object",fields:{purchase_details:{kind:"nullable",inner:{kind:"object",fields:{fleet:{kind:"nullable",inner:{kind:"object",fields:{reported_breakdown:{kind:"nullable",inner:{kind:"object",fields:{fuel:{kind:"nullable",inner:{kind:"object",fields:{gross_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},non_fuel:{kind:"nullable",inner:{kind:"object",fields:{gross_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},tax:{kind:"nullable",inner:{kind:"object",fields:{local_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},national_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}}}}}},fuel:{kind:"nullable",inner:{kind:"object",fields:{quantity_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_cost_decimal:{kind:"decimal_string"}}}}}}}}}}}}}),capture:Sj({method:"POST",fullPath:"/v1/test_helpers/issuing/authorizations/{authorization}/capture",requestSchema:{kind:"object",fields:{purchase_details:{kind:"object",fields:{fleet:{kind:"object",fields:{reported_breakdown:{kind:"object",fields:{fuel:{kind:"object",fields:{gross_amount_decimal:{kind:"decimal_string"}}},non_fuel:{kind:"object",fields:{gross_amount_decimal:{kind:"decimal_string"}}},tax:{kind:"object",fields:{local_amount_decimal:{kind:"decimal_string"},national_amount_decimal:{kind:"decimal_string"}}}}}}},fuel:{kind:"object",fields:{quantity_decimal:{kind:"decimal_string"},unit_cost_decimal:{kind:"decimal_string"}}},receipt:{kind:"array",element:{kind:"object",fields:{quantity:{kind:"decimal_string"}}}}}}}},responseSchema:{kind:"object",fields:{fleet:{kind:"nullable",inner:{kind:"object",fields:{reported_breakdown:{kind:"nullable",inner:{kind:"object",fields:{fuel:{kind:"nullable",inner:{kind:"object",fields:{gross_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},non_fuel:{kind:"nullable",inner:{kind:"object",fields:{gross_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},tax:{kind:"nullable",inner:{kind:"object",fields:{local_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},national_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}}}}}},fuel:{kind:"nullable",inner:{kind:"object",fields:{quantity_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_cost_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},transactions:{kind:"array",element:{kind:"object",fields:{purchase_details:{kind:"nullable",inner:{kind:"object",fields:{fleet:{kind:"nullable",inner:{kind:"object",fields:{reported_breakdown:{kind:"nullable",inner:{kind:"object",fields:{fuel:{kind:"nullable",inner:{kind:"object",fields:{gross_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},non_fuel:{kind:"nullable",inner:{kind:"object",fields:{gross_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},tax:{kind:"nullable",inner:{kind:"object",fields:{local_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},national_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}}}}}},fuel:{kind:"nullable",inner:{kind:"object",fields:{quantity_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_cost_decimal:{kind:"decimal_string"}}}}}}}}}}}}}),expire:Sj({method:"POST",fullPath:"/v1/test_helpers/issuing/authorizations/{authorization}/expire",responseSchema:{kind:"object",fields:{fleet:{kind:"nullable",inner:{kind:"object",fields:{reported_breakdown:{kind:"nullable",inner:{kind:"object",fields:{fuel:{kind:"nullable",inner:{kind:"object",fields:{gross_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},non_fuel:{kind:"nullable",inner:{kind:"object",fields:{gross_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},tax:{kind:"nullable",inner:{kind:"object",fields:{local_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},national_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}}}}}},fuel:{kind:"nullable",inner:{kind:"object",fields:{quantity_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_cost_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},transactions:{kind:"array",element:{kind:"object",fields:{purchase_details:{kind:"nullable",inner:{kind:"object",fields:{fleet:{kind:"nullable",inner:{kind:"object",fields:{reported_breakdown:{kind:"nullable",inner:{kind:"object",fields:{fuel:{kind:"nullable",inner:{kind:"object",fields:{gross_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},non_fuel:{kind:"nullable",inner:{kind:"object",fields:{gross_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},tax:{kind:"nullable",inner:{kind:"object",fields:{local_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},national_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}}}}}},fuel:{kind:"nullable",inner:{kind:"object",fields:{quantity_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_cost_decimal:{kind:"decimal_string"}}}}}}}}}}}}}),finalizeAmount:Sj({method:"POST",fullPath:"/v1/test_helpers/issuing/authorizations/{authorization}/finalize_amount",requestSchema:{kind:"object",fields:{fleet:{kind:"object",fields:{reported_breakdown:{kind:"object",fields:{fuel:{kind:"object",fields:{gross_amount_decimal:{kind:"decimal_string"}}},non_fuel:{kind:"object",fields:{gross_amount_decimal:{kind:"decimal_string"}}},tax:{kind:"object",fields:{local_amount_decimal:{kind:"decimal_string"},national_amount_decimal:{kind:"decimal_string"}}}}}}},fuel:{kind:"object",fields:{quantity_decimal:{kind:"decimal_string"},unit_cost_decimal:{kind:"decimal_string"}}}}},responseSchema:{kind:"object",fields:{fleet:{kind:"nullable",inner:{kind:"object",fields:{reported_breakdown:{kind:"nullable",inner:{kind:"object",fields:{fuel:{kind:"nullable",inner:{kind:"object",fields:{gross_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},non_fuel:{kind:"nullable",inner:{kind:"object",fields:{gross_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},tax:{kind:"nullable",inner:{kind:"object",fields:{local_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},national_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}}}}}},fuel:{kind:"nullable",inner:{kind:"object",fields:{quantity_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_cost_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},transactions:{kind:"array",element:{kind:"object",fields:{purchase_details:{kind:"nullable",inner:{kind:"object",fields:{fleet:{kind:"nullable",inner:{kind:"object",fields:{reported_breakdown:{kind:"nullable",inner:{kind:"object",fields:{fuel:{kind:"nullable",inner:{kind:"object",fields:{gross_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},non_fuel:{kind:"nullable",inner:{kind:"object",fields:{gross_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},tax:{kind:"nullable",inner:{kind:"object",fields:{local_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},national_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}}}}}},fuel:{kind:"nullable",inner:{kind:"object",fields:{quantity_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_cost_decimal:{kind:"decimal_string"}}}}}}}}}}}}}),increment:Sj({method:"POST",fullPath:"/v1/test_helpers/issuing/authorizations/{authorization}/increment",responseSchema:{kind:"object",fields:{fleet:{kind:"nullable",inner:{kind:"object",fields:{reported_breakdown:{kind:"nullable",inner:{kind:"object",fields:{fuel:{kind:"nullable",inner:{kind:"object",fields:{gross_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},non_fuel:{kind:"nullable",inner:{kind:"object",fields:{gross_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},tax:{kind:"nullable",inner:{kind:"object",fields:{local_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},national_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}}}}}},fuel:{kind:"nullable",inner:{kind:"object",fields:{quantity_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_cost_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},transactions:{kind:"array",element:{kind:"object",fields:{purchase_details:{kind:"nullable",inner:{kind:"object",fields:{fleet:{kind:"nullable",inner:{kind:"object",fields:{reported_breakdown:{kind:"nullable",inner:{kind:"object",fields:{fuel:{kind:"nullable",inner:{kind:"object",fields:{gross_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},non_fuel:{kind:"nullable",inner:{kind:"object",fields:{gross_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},tax:{kind:"nullable",inner:{kind:"object",fields:{local_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},national_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}}}}}},fuel:{kind:"nullable",inner:{kind:"object",fields:{quantity_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_cost_decimal:{kind:"decimal_string"}}}}}}}}}}}}}),respond:Sj({method:"POST",fullPath:"/v1/test_helpers/issuing/authorizations/{authorization}/fraud_challenges/respond",responseSchema:{kind:"object",fields:{fleet:{kind:"nullable",inner:{kind:"object",fields:{reported_breakdown:{kind:"nullable",inner:{kind:"object",fields:{fuel:{kind:"nullable",inner:{kind:"object",fields:{gross_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},non_fuel:{kind:"nullable",inner:{kind:"object",fields:{gross_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},tax:{kind:"nullable",inner:{kind:"object",fields:{local_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},national_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}}}}}},fuel:{kind:"nullable",inner:{kind:"object",fields:{quantity_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_cost_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},transactions:{kind:"array",element:{kind:"object",fields:{purchase_details:{kind:"nullable",inner:{kind:"object",fields:{fleet:{kind:"nullable",inner:{kind:"object",fields:{reported_breakdown:{kind:"nullable",inner:{kind:"object",fields:{fuel:{kind:"nullable",inner:{kind:"object",fields:{gross_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},non_fuel:{kind:"nullable",inner:{kind:"object",fields:{gross_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},tax:{kind:"nullable",inner:{kind:"object",fields:{local_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},national_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}}}}}},fuel:{kind:"nullable",inner:{kind:"object",fields:{quantity_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_cost_decimal:{kind:"decimal_string"}}}}}}}}}}}}}),reverse:Sj({method:"POST",fullPath:"/v1/test_helpers/issuing/authorizations/{authorization}/reverse",responseSchema:{kind:"object",fields:{fleet:{kind:"nullable",inner:{kind:"object",fields:{reported_breakdown:{kind:"nullable",inner:{kind:"object",fields:{fuel:{kind:"nullable",inner:{kind:"object",fields:{gross_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},non_fuel:{kind:"nullable",inner:{kind:"object",fields:{gross_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},tax:{kind:"nullable",inner:{kind:"object",fields:{local_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},national_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}}}}}},fuel:{kind:"nullable",inner:{kind:"object",fields:{quantity_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_cost_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},transactions:{kind:"array",element:{kind:"object",fields:{purchase_details:{kind:"nullable",inner:{kind:"object",fields:{fleet:{kind:"nullable",inner:{kind:"object",fields:{reported_breakdown:{kind:"nullable",inner:{kind:"object",fields:{fuel:{kind:"nullable",inner:{kind:"object",fields:{gross_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},non_fuel:{kind:"nullable",inner:{kind:"object",fields:{gross_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},tax:{kind:"nullable",inner:{kind:"object",fields:{local_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},national_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}}}}}},fuel:{kind:"nullable",inner:{kind:"object",fields:{quantity_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_cost_decimal:{kind:"decimal_string"}}}}}}}}}}}}})})});var V$,H7;var b7=R(()=>{M();V$=P.method,H7=P.extend({create:V$({method:"POST",fullPath:"/v1/tax/calculations"}),retrieve:V$({method:"GET",fullPath:"/v1/tax/calculations/{calculation}"}),listLineItems:V$({method:"GET",fullPath:"/v1/tax/calculations/{calculation}/line_items",methodType:"list"})})});var H0,N7;var x7=R(()=>{M();H0=P.method,N7=P.extend({create:H0({method:"POST",fullPath:"/v1/issuing/cardholders"}),retrieve:H0({method:"GET",fullPath:"/v1/issuing/cardholders/{cardholder}"}),update:H0({method:"POST",fullPath:"/v1/issuing/cardholders/{cardholder}"}),list:H0({method:"GET",fullPath:"/v1/issuing/cardholders",methodType:"list"})})});var b0,i7;var B7=R(()=>{M();b0=P.method,i7=P.extend({create:b0({method:"POST",fullPath:"/v1/issuing/cards"}),retrieve:b0({method:"GET",fullPath:"/v1/issuing/cards/{card}"}),update:b0({method:"POST",fullPath:"/v1/issuing/cards/{card}"}),list:b0({method:"GET",fullPath:"/v1/issuing/cards",methodType:"list"})})});var Gd,c7;var y7=R(()=>{M();Gd=P.method,c7=P.extend({deliverCard:Gd({method:"POST",fullPath:"/v1/test_helpers/issuing/cards/{card}/shipping/deliver"}),failCard:Gd({method:"POST",fullPath:"/v1/test_helpers/issuing/cards/{card}/shipping/fail"}),returnCard:Gd({method:"POST",fullPath:"/v1/test_helpers/issuing/cards/{card}/shipping/return"}),shipCard:Gd({method:"POST",fullPath:"/v1/test_helpers/issuing/cards/{card}/shipping/ship"}),submitCard:Gd({method:"POST",fullPath:"/v1/test_helpers/issuing/cards/{card}/shipping/submit"})})});var N0,v7;var A7=R(()=>{M();N0=P.method,v7=P.extend({create:N0({method:"POST",fullPath:"/v1/billing_portal/configurations"}),retrieve:N0({method:"GET",fullPath:"/v1/billing_portal/configurations/{configuration}"}),update:N0({method:"POST",fullPath:"/v1/billing_portal/configurations/{configuration}"}),list:N0({method:"GET",fullPath:"/v1/billing_portal/configurations",methodType:"list"})})});var Fd,m7;var g7=R(()=>{M();Fd=P.method,m7=P.extend({create:Fd({method:"POST",fullPath:"/v1/terminal/configurations"}),retrieve:Fd({method:"GET",fullPath:"/v1/terminal/configurations/{configuration}"}),update:Fd({method:"POST",fullPath:"/v1/terminal/configurations/{configuration}"}),list:Fd({method:"GET",fullPath:"/v1/terminal/configurations",methodType:"list"}),del:Fd({method:"DELETE",fullPath:"/v1/terminal/configurations/{configuration}"})})});var yQ,u7;var l7=R(()=>{M();yQ=P.method,u7=P.extend({create:yQ({method:"POST",fullPath:"/v1/test_helpers/confirmation_tokens"})})});var vQ,p7;var s7=R(()=>{M();vQ=P.method,p7=P.extend({create:vQ({method:"POST",fullPath:"/v1/terminal/connection_tokens"})})});var AQ,o7;var r7=R(()=>{M();AQ=P.method,o7=P.extend({retrieve:AQ({method:"GET",fullPath:"/v1/billing/credit_balance_summary"})})});var t7,a7;var e7=R(()=>{M();t7=P.method,a7=P.extend({retrieve:t7({method:"GET",fullPath:"/v1/billing/credit_balance_transactions/{id}"}),list:t7({method:"GET",fullPath:"/v1/billing/credit_balance_transactions",methodType:"list"})})});var tj,_X;var kX=R(()=>{M();tj=P.method,_X=P.extend({create:tj({method:"POST",fullPath:"/v1/billing/credit_grants"}),retrieve:tj({method:"GET",fullPath:"/v1/billing/credit_grants/{id}"}),update:tj({method:"POST",fullPath:"/v1/billing/credit_grants/{id}"}),list:tj({method:"GET",fullPath:"/v1/billing/credit_grants",methodType:"list"}),expire:tj({method:"POST",fullPath:"/v1/billing/credit_grants/{id}/expire"}),voidGrant:tj({method:"POST",fullPath:"/v1/billing/credit_grants/{id}/void"})})});var T$,jX;var dX=R(()=>{M();T$=P.method,jX=P.extend({create:T$({method:"POST",fullPath:"/v1/treasury/credit_reversals"}),retrieve:T$({method:"GET",fullPath:"/v1/treasury/credit_reversals/{credit_reversal}"}),list:T$({method:"GET",fullPath:"/v1/treasury/credit_reversals",methodType:"list"})})});var mQ,OX;var $X=R(()=>{M();mQ=P.method,OX=P.extend({fundCashBalance:mQ({method:"POST",fullPath:"/v1/test_helpers/customers/{customer}/fund_cash_balance"})})});var W$,ZX;var XX=R(()=>{M();W$=P.method,ZX=P.extend({create:W$({method:"POST",fullPath:"/v1/treasury/debit_reversals"}),retrieve:W$({method:"GET",fullPath:"/v1/treasury/debit_reversals/{debit_reversal}"}),list:W$({method:"GET",fullPath:"/v1/treasury/debit_reversals",methodType:"list"})})});var zd,EX;var GX=R(()=>{M();zd=P.method,EX=P.extend({create:zd({method:"POST",fullPath:"/v1/issuing/disputes"}),retrieve:zd({method:"GET",fullPath:"/v1/issuing/disputes/{dispute}"}),update:zd({method:"POST",fullPath:"/v1/issuing/disputes/{dispute}"}),list:zd({method:"GET",fullPath:"/v1/issuing/disputes",methodType:"list"}),submit:zd({method:"POST",fullPath:"/v1/issuing/disputes/{dispute}/submit"})})});var FX,zX;var SX=R(()=>{M();FX=P.method,zX=P.extend({retrieve:FX({method:"GET",fullPath:"/v1/radar/early_fraud_warnings/{early_fraud_warning}"}),list:FX({method:"GET",fullPath:"/v1/radar/early_fraud_warnings",methodType:"list"})})});var jj,YX;var LX=R(()=>{M();jj=P.method,YX=P.extend({create:jj({method:"POST",fullPath:"/v2/core/event_destinations"}),retrieve:jj({method:"GET",fullPath:"/v2/core/event_destinations/{id}"}),update:jj({method:"POST",fullPath:"/v2/core/event_destinations/{id}"}),list:jj({method:"GET",fullPath:"/v2/core/event_destinations",methodType:"list"}),del:jj({method:"DELETE",fullPath:"/v2/core/event_destinations/{id}"}),disable:jj({method:"POST",fullPath:"/v2/core/event_destinations/{id}/disable"}),enable:jj({method:"POST",fullPath:"/v2/core/event_destinations/{id}/enable"}),ping:jj({method:"POST",fullPath:"/v2/core/event_destinations/{id}/ping"})})});var K$,PX;var UX=R(()=>{M();K$=P.method,PX=P.extend({retrieve(..._){return K$({method:"GET",fullPath:"/v2/core/events/{id}",transformResponseData:(j)=>{return this.addFetchRelatedObjectIfNeeded(j)}}).apply(this,_)},list(..._){return K$({method:"GET",fullPath:"/v2/core/events",methodType:"list",transformResponseData:(j)=>{return{...j,data:j.data.map(this.addFetchRelatedObjectIfNeeded.bind(this))}}}).apply(this,_)},addFetchRelatedObjectIfNeeded(_){if(!_.related_object||!_.related_object.url)return _;return{..._,fetchRelatedObject:()=>K$({method:"GET",fullPath:_.related_object.url}).apply(this,[{stripeContext:_.context,headers:{"Stripe-Request-Trigger":`event=${_.id}`}}])}}})});var x0,QX;var VX=R(()=>{M();x0=P.method,QX=P.extend({create:x0({method:"POST",fullPath:"/v1/entitlements/features"}),retrieve:x0({method:"GET",fullPath:"/v1/entitlements/features/{id}"}),update:x0({method:"POST",fullPath:"/v1/entitlements/features/{id}"}),list:x0({method:"GET",fullPath:"/v1/entitlements/features",methodType:"list"})})});var Yj,TX;var WX=R(()=>{M();Yj=P.method,TX=P.extend({create:Yj({method:"POST",fullPath:"/v1/treasury/financial_accounts"}),retrieve:Yj({method:"GET",fullPath:"/v1/treasury/financial_accounts/{financial_account}"}),update:Yj({method:"POST",fullPath:"/v1/treasury/financial_accounts/{financial_account}"}),list:Yj({method:"GET",fullPath:"/v1/treasury/financial_accounts",methodType:"list"}),close:Yj({method:"POST",fullPath:"/v1/treasury/financial_accounts/{financial_account}/close"}),retrieveFeatures:Yj({method:"GET",fullPath:"/v1/treasury/financial_accounts/{financial_account}/features"}),updateFeatures:Yj({method:"POST",fullPath:"/v1/treasury/financial_accounts/{financial_account}/features"})})});var n$,KX;var nX=R(()=>{M();n$=P.method,KX=P.extend({fail:n$({method:"POST",fullPath:"/v1/test_helpers/treasury/inbound_transfers/{id}/fail"}),returnInboundTransfer:n$({method:"POST",fullPath:"/v1/test_helpers/treasury/inbound_transfers/{id}/return"}),succeed:n$({method:"POST",fullPath:"/v1/test_helpers/treasury/inbound_transfers/{id}/succeed"})})});var i0,JX;var IX=R(()=>{M();i0=P.method,JX=P.extend({create:i0({method:"POST",fullPath:"/v1/treasury/inbound_transfers"}),retrieve:i0({method:"GET",fullPath:"/v1/treasury/inbound_transfers/{id}"}),list:i0({method:"GET",fullPath:"/v1/treasury/inbound_transfers",methodType:"list"}),cancel:i0({method:"POST",fullPath:"/v1/treasury/inbound_transfers/{inbound_transfer}/cancel"})})});var Sd,DX;var RX=R(()=>{M();Sd=P.method,DX=P.extend({create:Sd({method:"POST",fullPath:"/v1/terminal/locations"}),retrieve:Sd({method:"GET",fullPath:"/v1/terminal/locations/{location}"}),update:Sd({method:"POST",fullPath:"/v1/terminal/locations/{location}"}),list:Sd({method:"GET",fullPath:"/v1/terminal/locations",methodType:"list"}),del:Sd({method:"DELETE",fullPath:"/v1/terminal/locations/{location}"})})});var gQ,wX;var MX=R(()=>{M();gQ=P.method,wX=P.extend({create:gQ({method:"POST",fullPath:"/v1/billing/meter_event_adjustments"})})});var uQ,CX;var hX=R(()=>{M();uQ=P.method,CX=P.extend({create:uQ({method:"POST",fullPath:"/v2/billing/meter_event_adjustments"})})});var lQ,fX;var qX=R(()=>{M();lQ=P.method,fX=P.extend({create:lQ({method:"POST",fullPath:"/v2/billing/meter_event_session"})})});var pQ,HX;var bX=R(()=>{M();pQ=P.method,HX=P.extend({create:pQ({method:"POST",fullPath:"/v2/billing/meter_event_stream",host:"meter-events.stripe.com"})})});var sQ,NX;var xX=R(()=>{M();sQ=P.method,NX=P.extend({create:sQ({method:"POST",fullPath:"/v1/billing/meter_events"})})});var oQ,iX;var BX=R(()=>{M();oQ=P.method,iX=P.extend({create:oQ({method:"POST",fullPath:"/v2/billing/meter_events"})})});var Lj,cX;var yX=R(()=>{M();Lj=P.method,cX=P.extend({create:Lj({method:"POST",fullPath:"/v1/billing/meters"}),retrieve:Lj({method:"GET",fullPath:"/v1/billing/meters/{id}"}),update:Lj({method:"POST",fullPath:"/v1/billing/meters/{id}"}),list:Lj({method:"GET",fullPath:"/v1/billing/meters",methodType:"list"}),deactivate:Lj({method:"POST",fullPath:"/v1/billing/meters/{id}/deactivate"}),listEventSummaries:Lj({method:"GET",fullPath:"/v1/billing/meters/{id}/event_summaries",methodType:"list"}),reactivate:Lj({method:"POST",fullPath:"/v1/billing/meters/{id}/reactivate"})})});var rQ,vX;var AX=R(()=>{M();rQ=P.method,vX=P.extend({create:rQ({method:"POST",fullPath:"/v1/terminal/onboarding_links"})})});var Yd,mX;var gX=R(()=>{M();Yd=P.method,mX=P.extend({create:Yd({method:"POST",fullPath:"/v1/climate/orders",requestSchema:{kind:"object",fields:{metric_tons:{kind:"decimal_string"}}},responseSchema:{kind:"object",fields:{metric_tons:{kind:"decimal_string"}}}}),retrieve:Yd({method:"GET",fullPath:"/v1/climate/orders/{order}",responseSchema:{kind:"object",fields:{metric_tons:{kind:"decimal_string"}}}}),update:Yd({method:"POST",fullPath:"/v1/climate/orders/{order}",responseSchema:{kind:"object",fields:{metric_tons:{kind:"decimal_string"}}}}),list:Yd({method:"GET",fullPath:"/v1/climate/orders",methodType:"list",responseSchema:{kind:"object",fields:{data:{kind:"array",element:{kind:"object",fields:{metric_tons:{kind:"decimal_string"}}}}}}}),cancel:Yd({method:"POST",fullPath:"/v1/climate/orders/{order}/cancel",responseSchema:{kind:"object",fields:{metric_tons:{kind:"decimal_string"}}}})})});var B0,uX;var lX=R(()=>{M();B0=P.method,uX=P.extend({update:B0({method:"POST",fullPath:"/v1/test_helpers/treasury/outbound_payments/{id}"}),fail:B0({method:"POST",fullPath:"/v1/test_helpers/treasury/outbound_payments/{id}/fail"}),post:B0({method:"POST",fullPath:"/v1/test_helpers/treasury/outbound_payments/{id}/post"}),returnOutboundPayment:B0({method:"POST",fullPath:"/v1/test_helpers/treasury/outbound_payments/{id}/return"})})});var c0,pX;var sX=R(()=>{M();c0=P.method,pX=P.extend({create:c0({method:"POST",fullPath:"/v1/treasury/outbound_payments"}),retrieve:c0({method:"GET",fullPath:"/v1/treasury/outbound_payments/{id}"}),list:c0({method:"GET",fullPath:"/v1/treasury/outbound_payments",methodType:"list"}),cancel:c0({method:"POST",fullPath:"/v1/treasury/outbound_payments/{id}/cancel"})})});var y0,oX;var rX=R(()=>{M();y0=P.method,oX=P.extend({update:y0({method:"POST",fullPath:"/v1/test_helpers/treasury/outbound_transfers/{outbound_transfer}"}),fail:y0({method:"POST",fullPath:"/v1/test_helpers/treasury/outbound_transfers/{outbound_transfer}/fail"}),post:y0({method:"POST",fullPath:"/v1/test_helpers/treasury/outbound_transfers/{outbound_transfer}/post"}),returnOutboundTransfer:y0({method:"POST",fullPath:"/v1/test_helpers/treasury/outbound_transfers/{outbound_transfer}/return"})})});var v0,tX;var aX=R(()=>{M();v0=P.method,tX=P.extend({create:v0({method:"POST",fullPath:"/v1/treasury/outbound_transfers"}),retrieve:v0({method:"GET",fullPath:"/v1/treasury/outbound_transfers/{outbound_transfer}"}),list:v0({method:"GET",fullPath:"/v1/treasury/outbound_transfers",methodType:"list"}),cancel:v0({method:"POST",fullPath:"/v1/treasury/outbound_transfers/{outbound_transfer}/cancel"})})});var tQ,eX;var _E=R(()=>{M();tQ=P.method,eX=P.extend({create:tQ({method:"POST",fullPath:"/v1/radar/payment_evaluations"})})});var A0,kE;var jE=R(()=>{M();A0=P.method,kE=P.extend({create:A0({method:"POST",fullPath:"/v1/issuing/personalization_designs"}),retrieve:A0({method:"GET",fullPath:"/v1/issuing/personalization_designs/{personalization_design}"}),update:A0({method:"POST",fullPath:"/v1/issuing/personalization_designs/{personalization_design}"}),list:A0({method:"GET",fullPath:"/v1/issuing/personalization_designs",methodType:"list"})})});var J$,dE;var OE=R(()=>{M();J$=P.method,dE=P.extend({activate:J$({method:"POST",fullPath:"/v1/test_helpers/issuing/personalization_designs/{personalization_design}/activate"}),deactivate:J$({method:"POST",fullPath:"/v1/test_helpers/issuing/personalization_designs/{personalization_design}/deactivate"}),reject:J$({method:"POST",fullPath:"/v1/test_helpers/issuing/personalization_designs/{personalization_design}/reject"})})});var $E,ZE;var XE=R(()=>{M();$E=P.method,ZE=P.extend({retrieve:$E({method:"GET",fullPath:"/v1/issuing/physical_bundles/{physical_bundle}"}),list:$E({method:"GET",fullPath:"/v1/issuing/physical_bundles",methodType:"list"})})});var EE,GE;var FE=R(()=>{M();EE=P.method,GE=P.extend({retrieve:EE({method:"GET",fullPath:"/v1/climate/products/{product}",responseSchema:{kind:"object",fields:{metric_tons_available:{kind:"decimal_string"}}}}),list:EE({method:"GET",fullPath:"/v1/climate/products",methodType:"list",responseSchema:{kind:"object",fields:{data:{kind:"array",element:{kind:"object",fields:{metric_tons_available:{kind:"decimal_string"}}}}}}})})});var jk,zE;var SE=R(()=>{M();jk=P.method,zE=P.extend({create:jk({method:"POST",fullPath:"/v1/terminal/readers"}),retrieve:jk({method:"GET",fullPath:"/v1/terminal/readers/{reader}"}),update:jk({method:"POST",fullPath:"/v1/terminal/readers/{reader}"}),list:jk({method:"GET",fullPath:"/v1/terminal/readers",methodType:"list"}),del:jk({method:"DELETE",fullPath:"/v1/terminal/readers/{reader}"}),cancelAction:jk({method:"POST",fullPath:"/v1/terminal/readers/{reader}/cancel_action"}),collectInputs:jk({method:"POST",fullPath:"/v1/terminal/readers/{reader}/collect_inputs"}),collectPaymentMethod:jk({method:"POST",fullPath:"/v1/terminal/readers/{reader}/collect_payment_method"}),confirmPaymentIntent:jk({method:"POST",fullPath:"/v1/terminal/readers/{reader}/confirm_payment_intent"}),processPaymentIntent:jk({method:"POST",fullPath:"/v1/terminal/readers/{reader}/process_payment_intent"}),processSetupIntent:jk({method:"POST",fullPath:"/v1/terminal/readers/{reader}/process_setup_intent"}),refundPayment:jk({method:"POST",fullPath:"/v1/terminal/readers/{reader}/refund_payment"}),setReaderDisplay:jk({method:"POST",fullPath:"/v1/terminal/readers/{reader}/set_reader_display"})})});var I$,YE;var LE=R(()=>{M();I$=P.method,YE=P.extend({presentPaymentMethod:I$({method:"POST",fullPath:"/v1/test_helpers/terminal/readers/{reader}/present_payment_method"}),succeedInputCollection:I$({method:"POST",fullPath:"/v1/test_helpers/terminal/readers/{reader}/succeed_input_collection"}),timeoutInputCollection:I$({method:"POST",fullPath:"/v1/test_helpers/terminal/readers/{reader}/timeout_input_collection"})})});var aQ,PE;var UE=R(()=>{M();aQ=P.method,PE=P.extend({create:aQ({method:"POST",fullPath:"/v1/test_helpers/treasury/received_credits"})})});var QE,VE;var TE=R(()=>{M();QE=P.method,VE=P.extend({retrieve:QE({method:"GET",fullPath:"/v1/treasury/received_credits/{id}"}),list:QE({method:"GET",fullPath:"/v1/treasury/received_credits",methodType:"list"})})});var eQ,WE;var KE=R(()=>{M();eQ=P.method,WE=P.extend({create:eQ({method:"POST",fullPath:"/v1/test_helpers/treasury/received_debits"})})});var nE,JE;var IE=R(()=>{M();nE=P.method,JE=P.extend({retrieve:nE({method:"GET",fullPath:"/v1/treasury/received_debits/{id}"}),list:nE({method:"GET",fullPath:"/v1/treasury/received_debits",methodType:"list"})})});var _V,DE;var RE=R(()=>{M();_V=P.method,DE=P.extend({expire:_V({method:"POST",fullPath:"/v1/test_helpers/refunds/{refund}/expire"})})});var m0,wE;var ME=R(()=>{M();m0=P.method,wE=P.extend({create:m0({method:"POST",fullPath:"/v1/tax/registrations"}),retrieve:m0({method:"GET",fullPath:"/v1/tax/registrations/{id}"}),update:m0({method:"POST",fullPath:"/v1/tax/registrations/{id}"}),list:m0({method:"GET",fullPath:"/v1/tax/registrations",methodType:"list"})})});var D$,CE;var hE=R(()=>{M();D$=P.method,CE=P.extend({create:D$({method:"POST",fullPath:"/v1/reporting/report_runs"}),retrieve:D$({method:"GET",fullPath:"/v1/reporting/report_runs/{report_run}"}),list:D$({method:"GET",fullPath:"/v1/reporting/report_runs",methodType:"list"})})});var fE,qE;var HE=R(()=>{M();fE=P.method,qE=P.extend({retrieve:fE({method:"GET",fullPath:"/v1/reporting/report_types/{report_type}"}),list:fE({method:"GET",fullPath:"/v1/reporting/report_types",methodType:"list"})})});var R$,bE;var NE=R(()=>{M();R$=P.method,bE=P.extend({create:R$({method:"POST",fullPath:"/v1/forwarding/requests"}),retrieve:R$({method:"GET",fullPath:"/v1/forwarding/requests/{id}"}),list:R$({method:"GET",fullPath:"/v1/forwarding/requests",methodType:"list"})})});var xE,iE;var BE=R(()=>{M();xE=P.method,iE=P.extend({retrieve:xE({method:"GET",fullPath:"/v1/sigma/scheduled_query_runs/{scheduled_query_run}"}),list:xE({method:"GET",fullPath:"/v1/sigma/scheduled_query_runs",methodType:"list"})})});var g0,cE;var yE=R(()=>{M();g0=P.method,cE=P.extend({create:g0({method:"POST",fullPath:"/v1/apps/secrets"}),list:g0({method:"GET",fullPath:"/v1/apps/secrets",methodType:"list"}),deleteWhere:g0({method:"POST",fullPath:"/v1/apps/secrets/delete"}),find:g0({method:"GET",fullPath:"/v1/apps/secrets/find"})})});var kV,vE;var AE=R(()=>{M();kV=P.method,vE=P.extend({create:kV({method:"POST",fullPath:"/v1/billing_portal/sessions"})})});var aj,mE;var gE=R(()=>{M();aj=P.method,mE=P.extend({create:aj({method:"POST",fullPath:"/v1/checkout/sessions",requestSchema:{kind:"object",fields:{line_items:{kind:"array",element:{kind:"object",fields:{price_data:{kind:"object",fields:{unit_amount_decimal:{kind:"decimal_string"}}}}}}}},responseSchema:{kind:"object",fields:{currency_conversion:{kind:"nullable",inner:{kind:"object",fields:{fx_rate:{kind:"decimal_string"}}}},line_items:{kind:"object",fields:{data:{kind:"array",element:{kind:"object",fields:{price:{kind:"nullable",inner:{kind:"object",fields:{currency_options:{kind:"array",element:{kind:"object",fields:{tiers:{kind:"array",element:{kind:"object",fields:{flat_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},tiers:{kind:"array",element:{kind:"object",fields:{flat_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}}}}}}}}),retrieve:aj({method:"GET",fullPath:"/v1/checkout/sessions/{session}",responseSchema:{kind:"object",fields:{currency_conversion:{kind:"nullable",inner:{kind:"object",fields:{fx_rate:{kind:"decimal_string"}}}},line_items:{kind:"object",fields:{data:{kind:"array",element:{kind:"object",fields:{price:{kind:"nullable",inner:{kind:"object",fields:{currency_options:{kind:"array",element:{kind:"object",fields:{tiers:{kind:"array",element:{kind:"object",fields:{flat_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},tiers:{kind:"array",element:{kind:"object",fields:{flat_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}}}}}}}}),update:aj({method:"POST",fullPath:"/v1/checkout/sessions/{session}",requestSchema:{kind:"object",fields:{line_items:{kind:"array",element:{kind:"object",fields:{price_data:{kind:"object",fields:{unit_amount_decimal:{kind:"decimal_string"}}}}}}}},responseSchema:{kind:"object",fields:{currency_conversion:{kind:"nullable",inner:{kind:"object",fields:{fx_rate:{kind:"decimal_string"}}}},line_items:{kind:"object",fields:{data:{kind:"array",element:{kind:"object",fields:{price:{kind:"nullable",inner:{kind:"object",fields:{currency_options:{kind:"array",element:{kind:"object",fields:{tiers:{kind:"array",element:{kind:"object",fields:{flat_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},tiers:{kind:"array",element:{kind:"object",fields:{flat_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}}}}}}}}),list:aj({method:"GET",fullPath:"/v1/checkout/sessions",methodType:"list",responseSchema:{kind:"object",fields:{data:{kind:"array",element:{kind:"object",fields:{currency_conversion:{kind:"nullable",inner:{kind:"object",fields:{fx_rate:{kind:"decimal_string"}}}},line_items:{kind:"object",fields:{data:{kind:"array",element:{kind:"object",fields:{price:{kind:"nullable",inner:{kind:"object",fields:{currency_options:{kind:"array",element:{kind:"object",fields:{tiers:{kind:"array",element:{kind:"object",fields:{flat_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},tiers:{kind:"array",element:{kind:"object",fields:{flat_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}}}}}}}}}}}),expire:aj({method:"POST",fullPath:"/v1/checkout/sessions/{session}/expire",responseSchema:{kind:"object",fields:{currency_conversion:{kind:"nullable",inner:{kind:"object",fields:{fx_rate:{kind:"decimal_string"}}}},line_items:{kind:"object",fields:{data:{kind:"array",element:{kind:"object",fields:{price:{kind:"nullable",inner:{kind:"object",fields:{currency_options:{kind:"array",element:{kind:"object",fields:{tiers:{kind:"array",element:{kind:"object",fields:{flat_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},tiers:{kind:"array",element:{kind:"object",fields:{flat_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}}}}}}}}),listLineItems:aj({method:"GET",fullPath:"/v1/checkout/sessions/{session}/line_items",methodType:"list",responseSchema:{kind:"object",fields:{data:{kind:"array",element:{kind:"object",fields:{price:{kind:"nullable",inner:{kind:"object",fields:{currency_options:{kind:"array",element:{kind:"object",fields:{tiers:{kind:"array",element:{kind:"object",fields:{flat_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},tiers:{kind:"array",element:{kind:"object",fields:{flat_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}}}}}})})});var uE,lE;var pE=R(()=>{M();uE=P.method,lE=P.extend({create:uE({method:"POST",fullPath:"/v1/financial_connections/sessions"}),retrieve:uE({method:"GET",fullPath:"/v1/financial_connections/sessions/{session}"})})});var sE,oE;var rE=R(()=>{M();sE=P.method,oE=P.extend({retrieve:sE({method:"GET",fullPath:"/v1/tax/settings"}),update:sE({method:"POST",fullPath:"/v1/tax/settings"})})});var tE,aE;var eE=R(()=>{M();tE=P.method,aE=P.extend({retrieve:tE({method:"GET",fullPath:"/v1/climate/suppliers/{supplier}"}),list:tE({method:"GET",fullPath:"/v1/climate/suppliers",methodType:"list"})})});var Ld,_4;var k4=R(()=>{M();Ld=P.method,_4=P.extend({create:Ld({method:"POST",fullPath:"/v1/test_helpers/test_clocks"}),retrieve:Ld({method:"GET",fullPath:"/v1/test_helpers/test_clocks/{test_clock}"}),list:Ld({method:"GET",fullPath:"/v1/test_helpers/test_clocks",methodType:"list"}),del:Ld({method:"DELETE",fullPath:"/v1/test_helpers/test_clocks/{test_clock}"}),advance:Ld({method:"POST",fullPath:"/v1/test_helpers/test_clocks/{test_clock}/advance"})})});var w$,j4;var d4=R(()=>{M();w$=P.method,j4=P.extend({retrieve:w$({method:"GET",fullPath:"/v1/issuing/tokens/{token}"}),update:w$({method:"POST",fullPath:"/v1/issuing/tokens/{token}"}),list:w$({method:"GET",fullPath:"/v1/issuing/tokens",methodType:"list"})})});var O4,$4;var Z4=R(()=>{M();O4=P.method,$4=P.extend({retrieve:O4({method:"GET",fullPath:"/v1/treasury/transaction_entries/{id}",responseSchema:{kind:"object",fields:{flow_details:{kind:"nullable",inner:{kind:"object",fields:{issuing_authorization:{kind:"object",fields:{fleet:{kind:"nullable",inner:{kind:"object",fields:{reported_breakdown:{kind:"nullable",inner:{kind:"object",fields:{fuel:{kind:"nullable",inner:{kind:"object",fields:{gross_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},non_fuel:{kind:"nullable",inner:{kind:"object",fields:{gross_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},tax:{kind:"nullable",inner:{kind:"object",fields:{local_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},national_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}}}}}},fuel:{kind:"nullable",inner:{kind:"object",fields:{quantity_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_cost_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},transactions:{kind:"array",element:{kind:"object",fields:{purchase_details:{kind:"nullable",inner:{kind:"object",fields:{fleet:{kind:"nullable",inner:{kind:"object",fields:{reported_breakdown:{kind:"nullable",inner:{kind:"object",fields:{fuel:{kind:"nullable",inner:{kind:"object",fields:{gross_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},non_fuel:{kind:"nullable",inner:{kind:"object",fields:{gross_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},tax:{kind:"nullable",inner:{kind:"object",fields:{local_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},national_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}}}}}},fuel:{kind:"nullable",inner:{kind:"object",fields:{quantity_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_cost_decimal:{kind:"decimal_string"}}}}}}}}}}}}}}}}}}),list:O4({method:"GET",fullPath:"/v1/treasury/transaction_entries",methodType:"list",responseSchema:{kind:"object",fields:{data:{kind:"array",element:{kind:"object",fields:{flow_details:{kind:"nullable",inner:{kind:"object",fields:{issuing_authorization:{kind:"object",fields:{fleet:{kind:"nullable",inner:{kind:"object",fields:{reported_breakdown:{kind:"nullable",inner:{kind:"object",fields:{fuel:{kind:"nullable",inner:{kind:"object",fields:{gross_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},non_fuel:{kind:"nullable",inner:{kind:"object",fields:{gross_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},tax:{kind:"nullable",inner:{kind:"object",fields:{local_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},national_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}}}}}},fuel:{kind:"nullable",inner:{kind:"object",fields:{quantity_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_cost_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},transactions:{kind:"array",element:{kind:"object",fields:{purchase_details:{kind:"nullable",inner:{kind:"object",fields:{fleet:{kind:"nullable",inner:{kind:"object",fields:{reported_breakdown:{kind:"nullable",inner:{kind:"object",fields:{fuel:{kind:"nullable",inner:{kind:"object",fields:{gross_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},non_fuel:{kind:"nullable",inner:{kind:"object",fields:{gross_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},tax:{kind:"nullable",inner:{kind:"object",fields:{local_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},national_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}}}}}},fuel:{kind:"nullable",inner:{kind:"object",fields:{quantity_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_cost_decimal:{kind:"decimal_string"}}}}}}}}}}}}}}}}}}}}})})});var X4,E4;var G4=R(()=>{M();X4=P.method,E4=P.extend({retrieve:X4({method:"GET",fullPath:"/v1/financial_connections/transactions/{transaction}"}),list:X4({method:"GET",fullPath:"/v1/financial_connections/transactions",methodType:"list"})})});var M$,F4;var z4=R(()=>{M();M$=P.method,F4=P.extend({retrieve:M$({method:"GET",fullPath:"/v1/issuing/transactions/{transaction}",responseSchema:{kind:"object",fields:{purchase_details:{kind:"nullable",inner:{kind:"object",fields:{fleet:{kind:"nullable",inner:{kind:"object",fields:{reported_breakdown:{kind:"nullable",inner:{kind:"object",fields:{fuel:{kind:"nullable",inner:{kind:"object",fields:{gross_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},non_fuel:{kind:"nullable",inner:{kind:"object",fields:{gross_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},tax:{kind:"nullable",inner:{kind:"object",fields:{local_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},national_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}}}}}},fuel:{kind:"nullable",inner:{kind:"object",fields:{quantity_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_cost_decimal:{kind:"decimal_string"}}}}}}}}}}),update:M$({method:"POST",fullPath:"/v1/issuing/transactions/{transaction}",responseSchema:{kind:"object",fields:{purchase_details:{kind:"nullable",inner:{kind:"object",fields:{fleet:{kind:"nullable",inner:{kind:"object",fields:{reported_breakdown:{kind:"nullable",inner:{kind:"object",fields:{fuel:{kind:"nullable",inner:{kind:"object",fields:{gross_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},non_fuel:{kind:"nullable",inner:{kind:"object",fields:{gross_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},tax:{kind:"nullable",inner:{kind:"object",fields:{local_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},national_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}}}}}},fuel:{kind:"nullable",inner:{kind:"object",fields:{quantity_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_cost_decimal:{kind:"decimal_string"}}}}}}}}}}),list:M$({method:"GET",fullPath:"/v1/issuing/transactions",methodType:"list",responseSchema:{kind:"object",fields:{data:{kind:"array",element:{kind:"object",fields:{purchase_details:{kind:"nullable",inner:{kind:"object",fields:{fleet:{kind:"nullable",inner:{kind:"object",fields:{reported_breakdown:{kind:"nullable",inner:{kind:"object",fields:{fuel:{kind:"nullable",inner:{kind:"object",fields:{gross_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},non_fuel:{kind:"nullable",inner:{kind:"object",fields:{gross_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},tax:{kind:"nullable",inner:{kind:"object",fields:{local_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},national_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}}}}}},fuel:{kind:"nullable",inner:{kind:"object",fields:{quantity_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_cost_decimal:{kind:"decimal_string"}}}}}}}}}}}}})})});var u0,S4;var Y4=R(()=>{M();u0=P.method,S4=P.extend({retrieve:u0({method:"GET",fullPath:"/v1/tax/transactions/{transaction}"}),createFromCalculation:u0({method:"POST",fullPath:"/v1/tax/transactions/create_from_calculation"}),createReversal:u0({method:"POST",fullPath:"/v1/tax/transactions/create_reversal"}),listLineItems:u0({method:"GET",fullPath:"/v1/tax/transactions/{transaction}/line_items",methodType:"list"})})});var C$,L4;var P4=R(()=>{M();C$=P.method,L4=P.extend({createForceCapture:C$({method:"POST",fullPath:"/v1/test_helpers/issuing/transactions/create_force_capture",requestSchema:{kind:"object",fields:{purchase_details:{kind:"object",fields:{fleet:{kind:"object",fields:{reported_breakdown:{kind:"object",fields:{fuel:{kind:"object",fields:{gross_amount_decimal:{kind:"decimal_string"}}},non_fuel:{kind:"object",fields:{gross_amount_decimal:{kind:"decimal_string"}}},tax:{kind:"object",fields:{local_amount_decimal:{kind:"decimal_string"},national_amount_decimal:{kind:"decimal_string"}}}}}}},fuel:{kind:"object",fields:{quantity_decimal:{kind:"decimal_string"},unit_cost_decimal:{kind:"decimal_string"}}},receipt:{kind:"array",element:{kind:"object",fields:{quantity:{kind:"decimal_string"}}}}}}}},responseSchema:{kind:"object",fields:{purchase_details:{kind:"nullable",inner:{kind:"object",fields:{fleet:{kind:"nullable",inner:{kind:"object",fields:{reported_breakdown:{kind:"nullable",inner:{kind:"object",fields:{fuel:{kind:"nullable",inner:{kind:"object",fields:{gross_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},non_fuel:{kind:"nullable",inner:{kind:"object",fields:{gross_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},tax:{kind:"nullable",inner:{kind:"object",fields:{local_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},national_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}}}}}},fuel:{kind:"nullable",inner:{kind:"object",fields:{quantity_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_cost_decimal:{kind:"decimal_string"}}}}}}}}}}),createUnlinkedRefund:C$({method:"POST",fullPath:"/v1/test_helpers/issuing/transactions/create_unlinked_refund",requestSchema:{kind:"object",fields:{purchase_details:{kind:"object",fields:{fleet:{kind:"object",fields:{reported_breakdown:{kind:"object",fields:{fuel:{kind:"object",fields:{gross_amount_decimal:{kind:"decimal_string"}}},non_fuel:{kind:"object",fields:{gross_amount_decimal:{kind:"decimal_string"}}},tax:{kind:"object",fields:{local_amount_decimal:{kind:"decimal_string"},national_amount_decimal:{kind:"decimal_string"}}}}}}},fuel:{kind:"object",fields:{quantity_decimal:{kind:"decimal_string"},unit_cost_decimal:{kind:"decimal_string"}}},receipt:{kind:"array",element:{kind:"object",fields:{quantity:{kind:"decimal_string"}}}}}}}},responseSchema:{kind:"object",fields:{purchase_details:{kind:"nullable",inner:{kind:"object",fields:{fleet:{kind:"nullable",inner:{kind:"object",fields:{reported_breakdown:{kind:"nullable",inner:{kind:"object",fields:{fuel:{kind:"nullable",inner:{kind:"object",fields:{gross_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},non_fuel:{kind:"nullable",inner:{kind:"object",fields:{gross_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},tax:{kind:"nullable",inner:{kind:"object",fields:{local_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},national_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}}}}}},fuel:{kind:"nullable",inner:{kind:"object",fields:{quantity_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_cost_decimal:{kind:"decimal_string"}}}}}}}}}}),refund:C$({method:"POST",fullPath:"/v1/test_helpers/issuing/transactions/{transaction}/refund",responseSchema:{kind:"object",fields:{purchase_details:{kind:"nullable",inner:{kind:"object",fields:{fleet:{kind:"nullable",inner:{kind:"object",fields:{reported_breakdown:{kind:"nullable",inner:{kind:"object",fields:{fuel:{kind:"nullable",inner:{kind:"object",fields:{gross_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},non_fuel:{kind:"nullable",inner:{kind:"object",fields:{gross_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},tax:{kind:"nullable",inner:{kind:"object",fields:{local_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},national_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}}}}}},fuel:{kind:"nullable",inner:{kind:"object",fields:{quantity_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_cost_decimal:{kind:"decimal_string"}}}}}}}}}})})});var U4,Q4;var V4=R(()=>{M();U4=P.method,Q4=P.extend({retrieve:U4({method:"GET",fullPath:"/v1/treasury/transactions/{id}",responseSchema:{kind:"object",fields:{entries:{kind:"nullable",inner:{kind:"object",fields:{data:{kind:"array",element:{kind:"object",fields:{flow_details:{kind:"nullable",inner:{kind:"object",fields:{issuing_authorization:{kind:"object",fields:{fleet:{kind:"nullable",inner:{kind:"object",fields:{reported_breakdown:{kind:"nullable",inner:{kind:"object",fields:{fuel:{kind:"nullable",inner:{kind:"object",fields:{gross_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},non_fuel:{kind:"nullable",inner:{kind:"object",fields:{gross_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},tax:{kind:"nullable",inner:{kind:"object",fields:{local_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},national_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}}}}}},fuel:{kind:"nullable",inner:{kind:"object",fields:{quantity_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_cost_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},transactions:{kind:"array",element:{kind:"object",fields:{purchase_details:{kind:"nullable",inner:{kind:"object",fields:{fleet:{kind:"nullable",inner:{kind:"object",fields:{reported_breakdown:{kind:"nullable",inner:{kind:"object",fields:{fuel:{kind:"nullable",inner:{kind:"object",fields:{gross_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},non_fuel:{kind:"nullable",inner:{kind:"object",fields:{gross_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},tax:{kind:"nullable",inner:{kind:"object",fields:{local_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},national_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}}}}}},fuel:{kind:"nullable",inner:{kind:"object",fields:{quantity_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_cost_decimal:{kind:"decimal_string"}}}}}}}}}}}}}}}}}}}}}}}}),list:U4({method:"GET",fullPath:"/v1/treasury/transactions",methodType:"list",responseSchema:{kind:"object",fields:{data:{kind:"array",element:{kind:"object",fields:{entries:{kind:"nullable",inner:{kind:"object",fields:{data:{kind:"array",element:{kind:"object",fields:{flow_details:{kind:"nullable",inner:{kind:"object",fields:{issuing_authorization:{kind:"object",fields:{fleet:{kind:"nullable",inner:{kind:"object",fields:{reported_breakdown:{kind:"nullable",inner:{kind:"object",fields:{fuel:{kind:"nullable",inner:{kind:"object",fields:{gross_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},non_fuel:{kind:"nullable",inner:{kind:"object",fields:{gross_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},tax:{kind:"nullable",inner:{kind:"object",fields:{local_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},national_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}}}}}},fuel:{kind:"nullable",inner:{kind:"object",fields:{quantity_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_cost_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},transactions:{kind:"array",element:{kind:"object",fields:{purchase_details:{kind:"nullable",inner:{kind:"object",fields:{fleet:{kind:"nullable",inner:{kind:"object",fields:{reported_breakdown:{kind:"nullable",inner:{kind:"object",fields:{fuel:{kind:"nullable",inner:{kind:"object",fields:{gross_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},non_fuel:{kind:"nullable",inner:{kind:"object",fields:{gross_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},tax:{kind:"nullable",inner:{kind:"object",fields:{local_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},national_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}}}}}},fuel:{kind:"nullable",inner:{kind:"object",fields:{quantity_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_cost_decimal:{kind:"decimal_string"}}}}}}}}}}}}}}}}}}}}}}}}}}})})});var l0,T4;var W4=R(()=>{M();l0=P.method,T4=P.extend({create:l0({method:"POST",fullPath:"/v1/radar/value_list_items"}),retrieve:l0({method:"GET",fullPath:"/v1/radar/value_list_items/{item}"}),list:l0({method:"GET",fullPath:"/v1/radar/value_list_items",methodType:"list"}),del:l0({method:"DELETE",fullPath:"/v1/radar/value_list_items/{item}"})})});var Pd,K4;var n4=R(()=>{M();Pd=P.method,K4=P.extend({create:Pd({method:"POST",fullPath:"/v1/radar/value_lists"}),retrieve:Pd({method:"GET",fullPath:"/v1/radar/value_lists/{value_list}"}),update:Pd({method:"POST",fullPath:"/v1/radar/value_lists/{value_list}"}),list:Pd({method:"GET",fullPath:"/v1/radar/value_lists",methodType:"list"}),del:Pd({method:"DELETE",fullPath:"/v1/radar/value_lists/{value_list}"})})});var J4,I4;var D4=R(()=>{M();J4=P.method,I4=P.extend({retrieve:J4({method:"GET",fullPath:"/v1/identity/verification_reports/{report}"}),list:J4({method:"GET",fullPath:"/v1/identity/verification_reports",methodType:"list"})})});var ej,R4;var w4=R(()=>{M();ej=P.method,R4=P.extend({create:ej({method:"POST",fullPath:"/v1/identity/verification_sessions"}),retrieve:ej({method:"GET",fullPath:"/v1/identity/verification_sessions/{session}"}),update:ej({method:"POST",fullPath:"/v1/identity/verification_sessions/{session}"}),list:ej({method:"GET",fullPath:"/v1/identity/verification_sessions",methodType:"list"}),cancel:ej({method:"POST",fullPath:"/v1/identity/verification_sessions/{session}/cancel"}),redact:ej({method:"POST",fullPath:"/v1/identity/verification_sessions/{session}/redact"})})});var M_,h$;var f$=R(()=>{M();M_=P.method,h$=P.extend({create:M_({method:"POST",fullPath:"/v1/accounts"}),retrieve(_,...k){if(typeof _==="string")return M_({method:"GET",fullPath:"/v1/accounts/{id}"}).apply(this,[_,...k]);else{if(_===null||_===void 0)[].shift.apply([_,...k]);return M_({method:"GET",fullPath:"/v1/account"}).apply(this,[_,...k])}},update:M_({method:"POST",fullPath:"/v1/accounts/{account}"}),list:M_({method:"GET",fullPath:"/v1/accounts",methodType:"list"}),del:M_({method:"DELETE",fullPath:"/v1/accounts/{account}"}),createExternalAccount:M_({method:"POST",fullPath:"/v1/accounts/{account}/external_accounts"}),createLoginLink:M_({method:"POST",fullPath:"/v1/accounts/{account}/login_links"}),createPerson:M_({method:"POST",fullPath:"/v1/accounts/{account}/persons"}),deleteExternalAccount:M_({method:"DELETE",fullPath:"/v1/accounts/{account}/external_accounts/{id}"}),deletePerson:M_({method:"DELETE",fullPath:"/v1/accounts/{account}/persons/{person}"}),listCapabilities:M_({method:"GET",fullPath:"/v1/accounts/{account}/capabilities",methodType:"list"}),listExternalAccounts:M_({method:"GET",fullPath:"/v1/accounts/{account}/external_accounts",methodType:"list"}),listPersons:M_({method:"GET",fullPath:"/v1/accounts/{account}/persons",methodType:"list"}),reject:M_({method:"POST",fullPath:"/v1/accounts/{account}/reject"}),retrieveCurrent:M_({method:"GET",fullPath:"/v1/account"}),retrieveCapability:M_({method:"GET",fullPath:"/v1/accounts/{account}/capabilities/{capability}"}),retrieveExternalAccount:M_({method:"GET",fullPath:"/v1/accounts/{account}/external_accounts/{id}"}),retrievePerson:M_({method:"GET",fullPath:"/v1/accounts/{account}/persons/{person}"}),updateCapability:M_({method:"POST",fullPath:"/v1/accounts/{account}/capabilities/{capability}"}),updateExternalAccount:M_({method:"POST",fullPath:"/v1/accounts/{account}/external_accounts/{id}"}),updatePerson:M_({method:"POST",fullPath:"/v1/accounts/{account}/persons/{person}"})})});var jV,M4;var C4=R(()=>{M();jV=P.method,M4=P.extend({create:jV({method:"POST",fullPath:"/v1/account_links"})})});var dV,h4;var f4=R(()=>{M();dV=P.method,h4=P.extend({create:dV({method:"POST",fullPath:"/v1/account_sessions"})})});var p0,q4;var H4=R(()=>{M();p0=P.method,q4=P.extend({create:p0({method:"POST",fullPath:"/v1/apple_pay/domains"}),retrieve:p0({method:"GET",fullPath:"/v1/apple_pay/domains/{domain}"}),list:p0({method:"GET",fullPath:"/v1/apple_pay/domains",methodType:"list"}),del:p0({method:"DELETE",fullPath:"/v1/apple_pay/domains/{domain}"})})});var _1,b4;var N4=R(()=>{M();_1=P.method,b4=P.extend({retrieve:_1({method:"GET",fullPath:"/v1/application_fees/{id}"}),list:_1({method:"GET",fullPath:"/v1/application_fees",methodType:"list"}),createRefund:_1({method:"POST",fullPath:"/v1/application_fees/{id}/refunds"}),listRefunds:_1({method:"GET",fullPath:"/v1/application_fees/{id}/refunds",methodType:"list"}),retrieveRefund:_1({method:"GET",fullPath:"/v1/application_fees/{fee}/refunds/{id}"}),updateRefund:_1({method:"POST",fullPath:"/v1/application_fees/{fee}/refunds/{id}"})})});var OV,x4;var i4=R(()=>{M();OV=P.method,x4=P.extend({retrieve:OV({method:"GET",fullPath:"/v1/balance"})})});var B4,c4;var y4=R(()=>{M();B4=P.method,c4=P.extend({retrieve:B4({method:"GET",fullPath:"/v1/balance_settings"}),update:B4({method:"POST",fullPath:"/v1/balance_settings"})})});var v4,A4;var m4=R(()=>{M();v4=P.method,A4=P.extend({retrieve:v4({method:"GET",fullPath:"/v1/balance_transactions/{id}"}),list:v4({method:"GET",fullPath:"/v1/balance_transactions",methodType:"list"})})});var k1,g4;var u4=R(()=>{M();k1=P.method,g4=P.extend({create:k1({method:"POST",fullPath:"/v1/charges"}),retrieve:k1({method:"GET",fullPath:"/v1/charges/{charge}"}),update:k1({method:"POST",fullPath:"/v1/charges/{charge}"}),list:k1({method:"GET",fullPath:"/v1/charges",methodType:"list"}),capture:k1({method:"POST",fullPath:"/v1/charges/{charge}/capture"}),search:k1({method:"GET",fullPath:"/v1/charges/search",methodType:"search"})})});var $V,l4;var p4=R(()=>{M();$V=P.method,l4=P.extend({retrieve:$V({method:"GET",fullPath:"/v1/confirmation_tokens/{confirmation_token}"})})});var s4,o4;var r4=R(()=>{M();s4=P.method,o4=P.extend({retrieve:s4({method:"GET",fullPath:"/v1/country_specs/{country}"}),list:s4({method:"GET",fullPath:"/v1/country_specs",methodType:"list"})})});var Ud,t4;var a4=R(()=>{M();Ud=P.method,t4=P.extend({create:Ud({method:"POST",fullPath:"/v1/coupons"}),retrieve:Ud({method:"GET",fullPath:"/v1/coupons/{coupon}"}),update:Ud({method:"POST",fullPath:"/v1/coupons/{coupon}"}),list:Ud({method:"GET",fullPath:"/v1/coupons",methodType:"list"}),del:Ud({method:"DELETE",fullPath:"/v1/coupons/{coupon}"})})});var dj,e4;var _G=R(()=>{M();dj=P.method,e4=P.extend({create:dj({method:"POST",fullPath:"/v1/credit_notes",requestSchema:{kind:"object",fields:{lines:{kind:"array",element:{kind:"object",fields:{unit_amount_decimal:{kind:"decimal_string"}}}}}},responseSchema:{kind:"object",fields:{lines:{kind:"object",fields:{data:{kind:"array",element:{kind:"object",fields:{unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}}}}}),retrieve:dj({method:"GET",fullPath:"/v1/credit_notes/{id}",responseSchema:{kind:"object",fields:{lines:{kind:"object",fields:{data:{kind:"array",element:{kind:"object",fields:{unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}}}}}),update:dj({method:"POST",fullPath:"/v1/credit_notes/{id}",responseSchema:{kind:"object",fields:{lines:{kind:"object",fields:{data:{kind:"array",element:{kind:"object",fields:{unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}}}}}),list:dj({method:"GET",fullPath:"/v1/credit_notes",methodType:"list",responseSchema:{kind:"object",fields:{data:{kind:"array",element:{kind:"object",fields:{lines:{kind:"object",fields:{data:{kind:"array",element:{kind:"object",fields:{unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}}}}}}}}),listLineItems:dj({method:"GET",fullPath:"/v1/credit_notes/{credit_note}/lines",methodType:"list",responseSchema:{kind:"object",fields:{data:{kind:"array",element:{kind:"object",fields:{unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}}}),listPreviewLineItems:dj({method:"GET",fullPath:"/v1/credit_notes/preview/lines",methodType:"list",requestSchema:{kind:"object",fields:{lines:{kind:"array",element:{kind:"object",fields:{unit_amount_decimal:{kind:"decimal_string"}}}}}},responseSchema:{kind:"object",fields:{data:{kind:"array",element:{kind:"object",fields:{unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}}}),preview:dj({method:"GET",fullPath:"/v1/credit_notes/preview",requestSchema:{kind:"object",fields:{lines:{kind:"array",element:{kind:"object",fields:{unit_amount_decimal:{kind:"decimal_string"}}}}}},responseSchema:{kind:"object",fields:{lines:{kind:"object",fields:{data:{kind:"array",element:{kind:"object",fields:{unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}}}}}),voidCreditNote:dj({method:"POST",fullPath:"/v1/credit_notes/{id}/void",responseSchema:{kind:"object",fields:{lines:{kind:"object",fields:{data:{kind:"array",element:{kind:"object",fields:{unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}}}}})})});var ZV,kG;var jG=R(()=>{M();ZV=P.method,kG=P.extend({create:ZV({method:"POST",fullPath:"/v1/customer_sessions"})})});var Y_,dG;var OG=R(()=>{M();Y_=P.method,dG=P.extend({create:Y_({method:"POST",fullPath:"/v1/customers",responseSchema:{kind:"object",fields:{subscriptions:{kind:"object",fields:{data:{kind:"array",element:{kind:"object",fields:{items:{kind:"object",fields:{data:{kind:"array",element:{kind:"object",fields:{plan:{kind:"object",fields:{amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},tiers:{kind:"array",element:{kind:"object",fields:{flat_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}},price:{kind:"object",fields:{currency_options:{kind:"array",element:{kind:"object",fields:{tiers:{kind:"array",element:{kind:"object",fields:{flat_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},tiers:{kind:"array",element:{kind:"object",fields:{flat_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}}}}}}}}}}}}),retrieve:Y_({method:"GET",fullPath:"/v1/customers/{customer}"}),update:Y_({method:"POST",fullPath:"/v1/customers/{customer}",responseSchema:{kind:"object",fields:{subscriptions:{kind:"object",fields:{data:{kind:"array",element:{kind:"object",fields:{items:{kind:"object",fields:{data:{kind:"array",element:{kind:"object",fields:{plan:{kind:"object",fields:{amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},tiers:{kind:"array",element:{kind:"object",fields:{flat_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}},price:{kind:"object",fields:{currency_options:{kind:"array",element:{kind:"object",fields:{tiers:{kind:"array",element:{kind:"object",fields:{flat_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},tiers:{kind:"array",element:{kind:"object",fields:{flat_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}}}}}}}}}}}}),list:Y_({method:"GET",fullPath:"/v1/customers",methodType:"list",responseSchema:{kind:"object",fields:{data:{kind:"array",element:{kind:"object",fields:{subscriptions:{kind:"object",fields:{data:{kind:"array",element:{kind:"object",fields:{items:{kind:"object",fields:{data:{kind:"array",element:{kind:"object",fields:{plan:{kind:"object",fields:{amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},tiers:{kind:"array",element:{kind:"object",fields:{flat_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}},price:{kind:"object",fields:{currency_options:{kind:"array",element:{kind:"object",fields:{tiers:{kind:"array",element:{kind:"object",fields:{flat_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},tiers:{kind:"array",element:{kind:"object",fields:{flat_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}}}}}}}}}}}}}}}),del:Y_({method:"DELETE",fullPath:"/v1/customers/{customer}"}),createBalanceTransaction:Y_({method:"POST",fullPath:"/v1/customers/{customer}/balance_transactions"}),createFundingInstructions:Y_({method:"POST",fullPath:"/v1/customers/{customer}/funding_instructions"}),createSource:Y_({method:"POST",fullPath:"/v1/customers/{customer}/sources"}),createTaxId:Y_({method:"POST",fullPath:"/v1/customers/{customer}/tax_ids"}),deleteDiscount:Y_({method:"DELETE",fullPath:"/v1/customers/{customer}/discount"}),deleteSource:Y_({method:"DELETE",fullPath:"/v1/customers/{customer}/sources/{id}"}),deleteTaxId:Y_({method:"DELETE",fullPath:"/v1/customers/{customer}/tax_ids/{id}"}),listBalanceTransactions:Y_({method:"GET",fullPath:"/v1/customers/{customer}/balance_transactions",methodType:"list"}),listCashBalanceTransactions:Y_({method:"GET",fullPath:"/v1/customers/{customer}/cash_balance_transactions",methodType:"list"}),listPaymentMethods:Y_({method:"GET",fullPath:"/v1/customers/{customer}/payment_methods",methodType:"list"}),listSources:Y_({method:"GET",fullPath:"/v1/customers/{customer}/sources",methodType:"list"}),listTaxIds:Y_({method:"GET",fullPath:"/v1/customers/{customer}/tax_ids",methodType:"list"}),retrieveBalanceTransaction:Y_({method:"GET",fullPath:"/v1/customers/{customer}/balance_transactions/{transaction}"}),retrieveCashBalance:Y_({method:"GET",fullPath:"/v1/customers/{customer}/cash_balance"}),retrieveCashBalanceTransaction:Y_({method:"GET",fullPath:"/v1/customers/{customer}/cash_balance_transactions/{transaction}"}),retrievePaymentMethod:Y_({method:"GET",fullPath:"/v1/customers/{customer}/payment_methods/{payment_method}"}),retrieveSource:Y_({method:"GET",fullPath:"/v1/customers/{customer}/sources/{id}"}),retrieveTaxId:Y_({method:"GET",fullPath:"/v1/customers/{customer}/tax_ids/{id}"}),search:Y_({method:"GET",fullPath:"/v1/customers/search",methodType:"search",responseSchema:{kind:"object",fields:{data:{kind:"array",element:{kind:"object",fields:{subscriptions:{kind:"object",fields:{data:{kind:"array",element:{kind:"object",fields:{items:{kind:"object",fields:{data:{kind:"array",element:{kind:"object",fields:{plan:{kind:"object",fields:{amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},tiers:{kind:"array",element:{kind:"object",fields:{flat_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}},price:{kind:"object",fields:{currency_options:{kind:"array",element:{kind:"object",fields:{tiers:{kind:"array",element:{kind:"object",fields:{flat_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},tiers:{kind:"array",element:{kind:"object",fields:{flat_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}}}}}}}}}}}}}}}),updateBalanceTransaction:Y_({method:"POST",fullPath:"/v1/customers/{customer}/balance_transactions/{transaction}"}),updateCashBalance:Y_({method:"POST",fullPath:"/v1/customers/{customer}/cash_balance"}),updateSource:Y_({method:"POST",fullPath:"/v1/customers/{customer}/sources/{id}"}),verifySource:Y_({method:"POST",fullPath:"/v1/customers/{customer}/sources/{id}/verify"})})});var s0,$G;var ZG=R(()=>{M();s0=P.method,$G=P.extend({retrieve:s0({method:"GET",fullPath:"/v1/disputes/{dispute}"}),update:s0({method:"POST",fullPath:"/v1/disputes/{dispute}"}),list:s0({method:"GET",fullPath:"/v1/disputes",methodType:"list"}),close:s0({method:"POST",fullPath:"/v1/disputes/{dispute}/close"})})});var XG,EG;var GG=R(()=>{M();XG=P.method,EG=P.extend({create:XG({method:"POST",fullPath:"/v1/ephemeral_keys",validator:(_,k)=>{if(!k.headers||!k.headers["Stripe-Version"])throw Error("Passing apiVersion in a separate options hash is required to create an ephemeral key. See https://stripe.com/docs/api/versioning?lang=node")}}),del:XG({method:"DELETE",fullPath:"/v1/ephemeral_keys/{key}"})})});var FG,zG;var SG=R(()=>{M();FG=P.method,zG=P.extend({retrieve:FG({method:"GET",fullPath:"/v1/events/{id}"}),list:FG({method:"GET",fullPath:"/v1/events",methodType:"list"})})});var YG,LG;var PG=R(()=>{M();YG=P.method,LG=P.extend({retrieve:YG({method:"GET",fullPath:"/v1/exchange_rates/{rate_id}"}),list:YG({method:"GET",fullPath:"/v1/exchange_rates",methodType:"list"})})});var o0,UG;var QG=R(()=>{M();o0=P.method,UG=P.extend({create:o0({method:"POST",fullPath:"/v1/file_links"}),retrieve:o0({method:"GET",fullPath:"/v1/file_links/{link}"}),update:o0({method:"POST",fullPath:"/v1/file_links/{link}"}),list:o0({method:"GET",fullPath:"/v1/file_links",methodType:"list"})})});function VG(_,k,j,d){if(k=k||{},_!=="POST")return d(null,_j(k));this._stripe._platformFunctions.tryBufferData(k).then((O)=>{let $=XV(_,O,j);return d(null,$)}).catch((O)=>d(O,null))}var XV=(_,k,j)=>{let d=(Math.round(Math.random()*10000000000000000)+Math.round(Math.random()*10000000000000000)).toString();j["Content-Type"]=`multipart/form-data; boundary=${d}`;let O=new TextEncoder,$=new Uint8Array(0),Z=O.encode(`\r
|
|
12
|
-
`);function X(G){let Y=$,S=G instanceof Uint8Array?G:new Uint8Array(O.encode(G));$=new Uint8Array(Y.length+S.length+2),$.set(Y),$.set(S,Y.length),$.set(Z,$.length-2)}function E(G){return`"${G.replace(/"|"/g,"%22").replace(/\r\n|\r|\n/g," ")}"`}let F=B6(k);for(let G in F){if(!Object.prototype.hasOwnProperty.call(F,G))continue;let Y=F[G];if(X(`--${d}`),Object.prototype.hasOwnProperty.call(Y,"data")){let S=Y;X(`Content-Disposition: form-data; name=${E(G)}; filename=${E(S.name||"blob")}`),X(`Content-Type: ${S.type||"application/octet-stream"}`),X(""),X(S.data)}else X(`Content-Disposition: form-data; name=${E(G)}`),X(""),X(Y)}return X(`--${d}--`),$};var TG=R(()=>{ck()});var q$,WG;var KG=R(()=>{TG();M();q$=P.method,WG=P.extend({create:q$({method:"POST",fullPath:"/v1/files",headers:{"Content-Type":"multipart/form-data"},host:"files.stripe.com"}),retrieve:q$({method:"GET",fullPath:"/v1/files/{file}"}),list:q$({method:"GET",fullPath:"/v1/files",methodType:"list"}),requestDataProcessor:VG})});var Qd,nG;var JG=R(()=>{M();Qd=P.method,nG=P.extend({create:Qd({method:"POST",fullPath:"/v1/invoiceitems",requestSchema:{kind:"object",fields:{price_data:{kind:"object",fields:{unit_amount_decimal:{kind:"decimal_string"}}},quantity_decimal:{kind:"decimal_string"},unit_amount_decimal:{kind:"decimal_string"}}},responseSchema:{kind:"object",fields:{pricing:{kind:"nullable",inner:{kind:"object",fields:{unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},quantity_decimal:{kind:"decimal_string"}}}}),retrieve:Qd({method:"GET",fullPath:"/v1/invoiceitems/{invoiceitem}",responseSchema:{kind:"object",fields:{pricing:{kind:"nullable",inner:{kind:"object",fields:{unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},quantity_decimal:{kind:"decimal_string"}}}}),update:Qd({method:"POST",fullPath:"/v1/invoiceitems/{invoiceitem}",requestSchema:{kind:"object",fields:{price_data:{kind:"object",fields:{unit_amount_decimal:{kind:"decimal_string"}}},quantity_decimal:{kind:"decimal_string"},unit_amount_decimal:{kind:"decimal_string"}}},responseSchema:{kind:"object",fields:{pricing:{kind:"nullable",inner:{kind:"object",fields:{unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},quantity_decimal:{kind:"decimal_string"}}}}),list:Qd({method:"GET",fullPath:"/v1/invoiceitems",methodType:"list",responseSchema:{kind:"object",fields:{data:{kind:"array",element:{kind:"object",fields:{pricing:{kind:"nullable",inner:{kind:"object",fields:{unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},quantity_decimal:{kind:"decimal_string"}}}}}}}),del:Qd({method:"DELETE",fullPath:"/v1/invoiceitems/{invoiceitem}"})})});var IG,DG;var RG=R(()=>{M();IG=P.method,DG=P.extend({retrieve:IG({method:"GET",fullPath:"/v1/invoice_payments/{invoice_payment}"}),list:IG({method:"GET",fullPath:"/v1/invoice_payments",methodType:"list"})})});var r0,wG;var MG=R(()=>{M();r0=P.method,wG=P.extend({retrieve:r0({method:"GET",fullPath:"/v1/invoice_rendering_templates/{template}"}),list:r0({method:"GET",fullPath:"/v1/invoice_rendering_templates",methodType:"list"}),archive:r0({method:"POST",fullPath:"/v1/invoice_rendering_templates/{template}/archive"}),unarchive:r0({method:"POST",fullPath:"/v1/invoice_rendering_templates/{template}/unarchive"})})});var B_,CG;var hG=R(()=>{M();B_=P.method,CG=P.extend({create:B_({method:"POST",fullPath:"/v1/invoices",responseSchema:{kind:"object",fields:{lines:{kind:"object",fields:{data:{kind:"array",element:{kind:"object",fields:{pricing:{kind:"nullable",inner:{kind:"object",fields:{unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},quantity_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}}}}}),retrieve:B_({method:"GET",fullPath:"/v1/invoices/{invoice}",responseSchema:{kind:"object",fields:{lines:{kind:"object",fields:{data:{kind:"array",element:{kind:"object",fields:{pricing:{kind:"nullable",inner:{kind:"object",fields:{unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},quantity_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}}}}}),update:B_({method:"POST",fullPath:"/v1/invoices/{invoice}",responseSchema:{kind:"object",fields:{lines:{kind:"object",fields:{data:{kind:"array",element:{kind:"object",fields:{pricing:{kind:"nullable",inner:{kind:"object",fields:{unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},quantity_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}}}}}),list:B_({method:"GET",fullPath:"/v1/invoices",methodType:"list",responseSchema:{kind:"object",fields:{data:{kind:"array",element:{kind:"object",fields:{lines:{kind:"object",fields:{data:{kind:"array",element:{kind:"object",fields:{pricing:{kind:"nullable",inner:{kind:"object",fields:{unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},quantity_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}}}}}}}}),del:B_({method:"DELETE",fullPath:"/v1/invoices/{invoice}"}),addLines:B_({method:"POST",fullPath:"/v1/invoices/{invoice}/add_lines",requestSchema:{kind:"object",fields:{lines:{kind:"array",element:{kind:"object",fields:{price_data:{kind:"object",fields:{unit_amount_decimal:{kind:"decimal_string"}}},quantity_decimal:{kind:"decimal_string"}}}}}},responseSchema:{kind:"object",fields:{lines:{kind:"object",fields:{data:{kind:"array",element:{kind:"object",fields:{pricing:{kind:"nullable",inner:{kind:"object",fields:{unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},quantity_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}}}}}),attachPayment:B_({method:"POST",fullPath:"/v1/invoices/{invoice}/attach_payment",responseSchema:{kind:"object",fields:{lines:{kind:"object",fields:{data:{kind:"array",element:{kind:"object",fields:{pricing:{kind:"nullable",inner:{kind:"object",fields:{unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},quantity_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}}}}}),createPreview:B_({method:"POST",fullPath:"/v1/invoices/create_preview",requestSchema:{kind:"object",fields:{invoice_items:{kind:"array",element:{kind:"object",fields:{price_data:{kind:"object",fields:{unit_amount_decimal:{kind:"decimal_string"}}},quantity_decimal:{kind:"decimal_string"},unit_amount_decimal:{kind:"decimal_string"}}}},schedule_details:{kind:"object",fields:{phases:{kind:"array",element:{kind:"object",fields:{add_invoice_items:{kind:"array",element:{kind:"object",fields:{price_data:{kind:"object",fields:{unit_amount_decimal:{kind:"decimal_string"}}}}}},items:{kind:"array",element:{kind:"object",fields:{price_data:{kind:"object",fields:{unit_amount_decimal:{kind:"decimal_string"}}}}}}}}}}},subscription_details:{kind:"object",fields:{items:{kind:"array",element:{kind:"object",fields:{price_data:{kind:"object",fields:{unit_amount_decimal:{kind:"decimal_string"}}}}}}}}}},responseSchema:{kind:"object",fields:{lines:{kind:"object",fields:{data:{kind:"array",element:{kind:"object",fields:{pricing:{kind:"nullable",inner:{kind:"object",fields:{unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},quantity_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}}}}}),finalizeInvoice:B_({method:"POST",fullPath:"/v1/invoices/{invoice}/finalize",responseSchema:{kind:"object",fields:{lines:{kind:"object",fields:{data:{kind:"array",element:{kind:"object",fields:{pricing:{kind:"nullable",inner:{kind:"object",fields:{unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},quantity_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}}}}}),listLineItems:B_({method:"GET",fullPath:"/v1/invoices/{invoice}/lines",methodType:"list",responseSchema:{kind:"object",fields:{data:{kind:"array",element:{kind:"object",fields:{pricing:{kind:"nullable",inner:{kind:"object",fields:{unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},quantity_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}}}),markUncollectible:B_({method:"POST",fullPath:"/v1/invoices/{invoice}/mark_uncollectible",responseSchema:{kind:"object",fields:{lines:{kind:"object",fields:{data:{kind:"array",element:{kind:"object",fields:{pricing:{kind:"nullable",inner:{kind:"object",fields:{unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},quantity_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}}}}}),pay:B_({method:"POST",fullPath:"/v1/invoices/{invoice}/pay",responseSchema:{kind:"object",fields:{lines:{kind:"object",fields:{data:{kind:"array",element:{kind:"object",fields:{pricing:{kind:"nullable",inner:{kind:"object",fields:{unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},quantity_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}}}}}),removeLines:B_({method:"POST",fullPath:"/v1/invoices/{invoice}/remove_lines",responseSchema:{kind:"object",fields:{lines:{kind:"object",fields:{data:{kind:"array",element:{kind:"object",fields:{pricing:{kind:"nullable",inner:{kind:"object",fields:{unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},quantity_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}}}}}),search:B_({method:"GET",fullPath:"/v1/invoices/search",methodType:"search",responseSchema:{kind:"object",fields:{data:{kind:"array",element:{kind:"object",fields:{lines:{kind:"object",fields:{data:{kind:"array",element:{kind:"object",fields:{pricing:{kind:"nullable",inner:{kind:"object",fields:{unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},quantity_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}}}}}}}}),sendInvoice:B_({method:"POST",fullPath:"/v1/invoices/{invoice}/send",responseSchema:{kind:"object",fields:{lines:{kind:"object",fields:{data:{kind:"array",element:{kind:"object",fields:{pricing:{kind:"nullable",inner:{kind:"object",fields:{unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},quantity_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}}}}}),updateLines:B_({method:"POST",fullPath:"/v1/invoices/{invoice}/update_lines",requestSchema:{kind:"object",fields:{lines:{kind:"array",element:{kind:"object",fields:{price_data:{kind:"object",fields:{unit_amount_decimal:{kind:"decimal_string"}}},quantity_decimal:{kind:"decimal_string"}}}}}},responseSchema:{kind:"object",fields:{lines:{kind:"object",fields:{data:{kind:"array",element:{kind:"object",fields:{pricing:{kind:"nullable",inner:{kind:"object",fields:{unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},quantity_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}}}}}),updateLineItem:B_({method:"POST",fullPath:"/v1/invoices/{invoice}/lines/{line_item_id}",requestSchema:{kind:"object",fields:{price_data:{kind:"object",fields:{unit_amount_decimal:{kind:"decimal_string"}}},quantity_decimal:{kind:"decimal_string"}}},responseSchema:{kind:"object",fields:{pricing:{kind:"nullable",inner:{kind:"object",fields:{unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},quantity_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}),voidInvoice:B_({method:"POST",fullPath:"/v1/invoices/{invoice}/void",responseSchema:{kind:"object",fields:{lines:{kind:"object",fields:{data:{kind:"array",element:{kind:"object",fields:{pricing:{kind:"nullable",inner:{kind:"object",fields:{unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},quantity_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}}}}})})});var EV,fG;var qG=R(()=>{M();EV=P.method,fG=P.extend({retrieve:EV({method:"GET",fullPath:"/v1/mandates/{mandate}"})})});var HG,H$="connect.stripe.com",bG;var NG=R(()=>{M();ck();HG=P.method,bG=P.extend({basePath:"/",authorizeUrl(_,k){_=_||{},k=k||{};let j="oauth/authorize";if(k.express)j=`express/${j}`;if(!_.response_type)_.response_type="code";if(!_.client_id)_.client_id=this._stripe.getClientId();if(!_.scope)_.scope="read_write";return`https://${H$}/${j}?${_j(_)}`},token:HG({method:"POST",path:"oauth/token",host:H$}),deauthorize(_,...k){if(!_.client_id)_.client_id=this._stripe.getClientId();return HG({method:"POST",path:"oauth/deauthorize",host:H$}).apply(this,[_,...k])}})});var xG,iG;var BG=R(()=>{M();xG=P.method,iG=P.extend({retrieve:xG({method:"GET",fullPath:"/v1/payment_attempt_records/{id}"}),list:xG({method:"GET",fullPath:"/v1/payment_attempt_records",methodType:"list"})})});var Sk,cG;var yG=R(()=>{M();Sk=P.method,cG=P.extend({create:Sk({method:"POST",fullPath:"/v1/payment_intents"}),retrieve:Sk({method:"GET",fullPath:"/v1/payment_intents/{intent}"}),update:Sk({method:"POST",fullPath:"/v1/payment_intents/{intent}"}),list:Sk({method:"GET",fullPath:"/v1/payment_intents",methodType:"list"}),applyCustomerBalance:Sk({method:"POST",fullPath:"/v1/payment_intents/{intent}/apply_customer_balance"}),cancel:Sk({method:"POST",fullPath:"/v1/payment_intents/{intent}/cancel"}),capture:Sk({method:"POST",fullPath:"/v1/payment_intents/{intent}/capture"}),confirm:Sk({method:"POST",fullPath:"/v1/payment_intents/{intent}/confirm"}),incrementAuthorization:Sk({method:"POST",fullPath:"/v1/payment_intents/{intent}/increment_authorization"}),listAmountDetailsLineItems:Sk({method:"GET",fullPath:"/v1/payment_intents/{intent}/amount_details_line_items",methodType:"list"}),search:Sk({method:"GET",fullPath:"/v1/payment_intents/search",methodType:"search"}),verifyMicrodeposits:Sk({method:"POST",fullPath:"/v1/payment_intents/{intent}/verify_microdeposits"})})});var Vd,vG;var AG=R(()=>{M();Vd=P.method,vG=P.extend({create:Vd({method:"POST",fullPath:"/v1/payment_links",requestSchema:{kind:"object",fields:{line_items:{kind:"array",element:{kind:"object",fields:{price_data:{kind:"object",fields:{unit_amount_decimal:{kind:"decimal_string"}}}}}}}},responseSchema:{kind:"object",fields:{line_items:{kind:"object",fields:{data:{kind:"array",element:{kind:"object",fields:{price:{kind:"nullable",inner:{kind:"object",fields:{currency_options:{kind:"array",element:{kind:"object",fields:{tiers:{kind:"array",element:{kind:"object",fields:{flat_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},tiers:{kind:"array",element:{kind:"object",fields:{flat_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}}}}}}}}),retrieve:Vd({method:"GET",fullPath:"/v1/payment_links/{payment_link}",responseSchema:{kind:"object",fields:{line_items:{kind:"object",fields:{data:{kind:"array",element:{kind:"object",fields:{price:{kind:"nullable",inner:{kind:"object",fields:{currency_options:{kind:"array",element:{kind:"object",fields:{tiers:{kind:"array",element:{kind:"object",fields:{flat_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},tiers:{kind:"array",element:{kind:"object",fields:{flat_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}}}}}}}}),update:Vd({method:"POST",fullPath:"/v1/payment_links/{payment_link}",responseSchema:{kind:"object",fields:{line_items:{kind:"object",fields:{data:{kind:"array",element:{kind:"object",fields:{price:{kind:"nullable",inner:{kind:"object",fields:{currency_options:{kind:"array",element:{kind:"object",fields:{tiers:{kind:"array",element:{kind:"object",fields:{flat_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},tiers:{kind:"array",element:{kind:"object",fields:{flat_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}}}}}}}}),list:Vd({method:"GET",fullPath:"/v1/payment_links",methodType:"list",responseSchema:{kind:"object",fields:{data:{kind:"array",element:{kind:"object",fields:{line_items:{kind:"object",fields:{data:{kind:"array",element:{kind:"object",fields:{price:{kind:"nullable",inner:{kind:"object",fields:{currency_options:{kind:"array",element:{kind:"object",fields:{tiers:{kind:"array",element:{kind:"object",fields:{flat_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},tiers:{kind:"array",element:{kind:"object",fields:{flat_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}}}}}}}}}}}),listLineItems:Vd({method:"GET",fullPath:"/v1/payment_links/{payment_link}/line_items",methodType:"list",responseSchema:{kind:"object",fields:{data:{kind:"array",element:{kind:"object",fields:{price:{kind:"nullable",inner:{kind:"object",fields:{currency_options:{kind:"array",element:{kind:"object",fields:{tiers:{kind:"array",element:{kind:"object",fields:{flat_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},tiers:{kind:"array",element:{kind:"object",fields:{flat_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}}}}}})})});var t0,mG;var gG=R(()=>{M();t0=P.method,mG=P.extend({create:t0({method:"POST",fullPath:"/v1/payment_method_configurations"}),retrieve:t0({method:"GET",fullPath:"/v1/payment_method_configurations/{configuration}"}),update:t0({method:"POST",fullPath:"/v1/payment_method_configurations/{configuration}"}),list:t0({method:"GET",fullPath:"/v1/payment_method_configurations",methodType:"list"})})});var Td,uG;var lG=R(()=>{M();Td=P.method,uG=P.extend({create:Td({method:"POST",fullPath:"/v1/payment_method_domains"}),retrieve:Td({method:"GET",fullPath:"/v1/payment_method_domains/{payment_method_domain}"}),update:Td({method:"POST",fullPath:"/v1/payment_method_domains/{payment_method_domain}"}),list:Td({method:"GET",fullPath:"/v1/payment_method_domains",methodType:"list"}),validate:Td({method:"POST",fullPath:"/v1/payment_method_domains/{payment_method_domain}/validate"})})});var j1,pG;var sG=R(()=>{M();j1=P.method,pG=P.extend({create:j1({method:"POST",fullPath:"/v1/payment_methods"}),retrieve:j1({method:"GET",fullPath:"/v1/payment_methods/{payment_method}"}),update:j1({method:"POST",fullPath:"/v1/payment_methods/{payment_method}"}),list:j1({method:"GET",fullPath:"/v1/payment_methods",methodType:"list"}),attach:j1({method:"POST",fullPath:"/v1/payment_methods/{payment_method}/attach"}),detach:j1({method:"POST",fullPath:"/v1/payment_methods/{payment_method}/detach"})})});var Oj,oG;var rG=R(()=>{M();Oj=P.method,oG=P.extend({retrieve:Oj({method:"GET",fullPath:"/v1/payment_records/{id}"}),reportPayment:Oj({method:"POST",fullPath:"/v1/payment_records/report_payment"}),reportPaymentAttempt:Oj({method:"POST",fullPath:"/v1/payment_records/{id}/report_payment_attempt"}),reportPaymentAttemptCanceled:Oj({method:"POST",fullPath:"/v1/payment_records/{id}/report_payment_attempt_canceled"}),reportPaymentAttemptFailed:Oj({method:"POST",fullPath:"/v1/payment_records/{id}/report_payment_attempt_failed"}),reportPaymentAttemptGuaranteed:Oj({method:"POST",fullPath:"/v1/payment_records/{id}/report_payment_attempt_guaranteed"}),reportPaymentAttemptInformational:Oj({method:"POST",fullPath:"/v1/payment_records/{id}/report_payment_attempt_informational"}),reportRefund:Oj({method:"POST",fullPath:"/v1/payment_records/{id}/report_refund"})})});var d1,tG;var aG=R(()=>{M();d1=P.method,tG=P.extend({create:d1({method:"POST",fullPath:"/v1/payouts"}),retrieve:d1({method:"GET",fullPath:"/v1/payouts/{payout}"}),update:d1({method:"POST",fullPath:"/v1/payouts/{payout}"}),list:d1({method:"GET",fullPath:"/v1/payouts",methodType:"list"}),cancel:d1({method:"POST",fullPath:"/v1/payouts/{payout}/cancel"}),reverse:d1({method:"POST",fullPath:"/v1/payouts/{payout}/reverse"})})});var Wd,eG;var _F=R(()=>{M();Wd=P.method,eG=P.extend({create:Wd({method:"POST",fullPath:"/v1/plans",requestSchema:{kind:"object",fields:{amount_decimal:{kind:"decimal_string"},tiers:{kind:"array",element:{kind:"object",fields:{flat_amount_decimal:{kind:"decimal_string"},unit_amount_decimal:{kind:"decimal_string"}}}}}},responseSchema:{kind:"object",fields:{amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},tiers:{kind:"array",element:{kind:"object",fields:{flat_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}}}),retrieve:Wd({method:"GET",fullPath:"/v1/plans/{plan}",responseSchema:{kind:"object",fields:{amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},tiers:{kind:"array",element:{kind:"object",fields:{flat_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}}}),update:Wd({method:"POST",fullPath:"/v1/plans/{plan}",responseSchema:{kind:"object",fields:{amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},tiers:{kind:"array",element:{kind:"object",fields:{flat_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}}}),list:Wd({method:"GET",fullPath:"/v1/plans",methodType:"list",responseSchema:{kind:"object",fields:{data:{kind:"array",element:{kind:"object",fields:{amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},tiers:{kind:"array",element:{kind:"object",fields:{flat_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}}}}}}),del:Wd({method:"DELETE",fullPath:"/v1/plans/{plan}"})})});var Kd,kF;var jF=R(()=>{M();Kd=P.method,kF=P.extend({create:Kd({method:"POST",fullPath:"/v1/prices",requestSchema:{kind:"object",fields:{currency_options:{kind:"array",element:{kind:"object",fields:{tiers:{kind:"array",element:{kind:"object",fields:{flat_amount_decimal:{kind:"decimal_string"},unit_amount_decimal:{kind:"decimal_string"}}}},unit_amount_decimal:{kind:"decimal_string"}}}},tiers:{kind:"array",element:{kind:"object",fields:{flat_amount_decimal:{kind:"decimal_string"},unit_amount_decimal:{kind:"decimal_string"}}}},unit_amount_decimal:{kind:"decimal_string"}}},responseSchema:{kind:"object",fields:{currency_options:{kind:"array",element:{kind:"object",fields:{tiers:{kind:"array",element:{kind:"object",fields:{flat_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},tiers:{kind:"array",element:{kind:"object",fields:{flat_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}),retrieve:Kd({method:"GET",fullPath:"/v1/prices/{price}",responseSchema:{kind:"object",fields:{currency_options:{kind:"array",element:{kind:"object",fields:{tiers:{kind:"array",element:{kind:"object",fields:{flat_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},tiers:{kind:"array",element:{kind:"object",fields:{flat_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}),update:Kd({method:"POST",fullPath:"/v1/prices/{price}",responseSchema:{kind:"object",fields:{currency_options:{kind:"array",element:{kind:"object",fields:{tiers:{kind:"array",element:{kind:"object",fields:{flat_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},tiers:{kind:"array",element:{kind:"object",fields:{flat_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}),list:Kd({method:"GET",fullPath:"/v1/prices",methodType:"list",responseSchema:{kind:"object",fields:{data:{kind:"array",element:{kind:"object",fields:{currency_options:{kind:"array",element:{kind:"object",fields:{tiers:{kind:"array",element:{kind:"object",fields:{flat_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},tiers:{kind:"array",element:{kind:"object",fields:{flat_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}}}),search:Kd({method:"GET",fullPath:"/v1/prices/search",methodType:"search",responseSchema:{kind:"object",fields:{data:{kind:"array",element:{kind:"object",fields:{currency_options:{kind:"array",element:{kind:"object",fields:{tiers:{kind:"array",element:{kind:"object",fields:{flat_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},tiers:{kind:"array",element:{kind:"object",fields:{flat_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}}})})});var nk,dF;var OF=R(()=>{M();nk=P.method,dF=P.extend({create:nk({method:"POST",fullPath:"/v1/products",requestSchema:{kind:"object",fields:{default_price_data:{kind:"object",fields:{currency_options:{kind:"array",element:{kind:"object",fields:{tiers:{kind:"array",element:{kind:"object",fields:{flat_amount_decimal:{kind:"decimal_string"},unit_amount_decimal:{kind:"decimal_string"}}}},unit_amount_decimal:{kind:"decimal_string"}}}},unit_amount_decimal:{kind:"decimal_string"}}}}}}),retrieve:nk({method:"GET",fullPath:"/v1/products/{id}"}),update:nk({method:"POST",fullPath:"/v1/products/{id}"}),list:nk({method:"GET",fullPath:"/v1/products",methodType:"list"}),del:nk({method:"DELETE",fullPath:"/v1/products/{id}"}),createFeature:nk({method:"POST",fullPath:"/v1/products/{product}/features"}),deleteFeature:nk({method:"DELETE",fullPath:"/v1/products/{product}/features/{id}"}),listFeatures:nk({method:"GET",fullPath:"/v1/products/{product}/features",methodType:"list"}),retrieveFeature:nk({method:"GET",fullPath:"/v1/products/{product}/features/{id}"}),search:nk({method:"GET",fullPath:"/v1/products/search",methodType:"search"})})});var a0,$F;var ZF=R(()=>{M();a0=P.method,$F=P.extend({create:a0({method:"POST",fullPath:"/v1/promotion_codes"}),retrieve:a0({method:"GET",fullPath:"/v1/promotion_codes/{promotion_code}"}),update:a0({method:"POST",fullPath:"/v1/promotion_codes/{promotion_code}"}),list:a0({method:"GET",fullPath:"/v1/promotion_codes",methodType:"list"})})});var Jk,XF;var EF=R(()=>{M();Jk=P.method,XF=P.extend({create:Jk({method:"POST",fullPath:"/v1/quotes",requestSchema:{kind:"object",fields:{line_items:{kind:"array",element:{kind:"object",fields:{price_data:{kind:"object",fields:{unit_amount_decimal:{kind:"decimal_string"}}}}}}}},responseSchema:{kind:"object",fields:{computed:{kind:"object",fields:{upfront:{kind:"object",fields:{line_items:{kind:"object",fields:{data:{kind:"array",element:{kind:"object",fields:{price:{kind:"nullable",inner:{kind:"object",fields:{currency_options:{kind:"array",element:{kind:"object",fields:{tiers:{kind:"array",element:{kind:"object",fields:{flat_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},tiers:{kind:"array",element:{kind:"object",fields:{flat_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}}}}}}}}}}}}),retrieve:Jk({method:"GET",fullPath:"/v1/quotes/{quote}",responseSchema:{kind:"object",fields:{computed:{kind:"object",fields:{upfront:{kind:"object",fields:{line_items:{kind:"object",fields:{data:{kind:"array",element:{kind:"object",fields:{price:{kind:"nullable",inner:{kind:"object",fields:{currency_options:{kind:"array",element:{kind:"object",fields:{tiers:{kind:"array",element:{kind:"object",fields:{flat_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},tiers:{kind:"array",element:{kind:"object",fields:{flat_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}}}}}}}}}}}}),update:Jk({method:"POST",fullPath:"/v1/quotes/{quote}",requestSchema:{kind:"object",fields:{line_items:{kind:"array",element:{kind:"object",fields:{price_data:{kind:"object",fields:{unit_amount_decimal:{kind:"decimal_string"}}}}}}}},responseSchema:{kind:"object",fields:{computed:{kind:"object",fields:{upfront:{kind:"object",fields:{line_items:{kind:"object",fields:{data:{kind:"array",element:{kind:"object",fields:{price:{kind:"nullable",inner:{kind:"object",fields:{currency_options:{kind:"array",element:{kind:"object",fields:{tiers:{kind:"array",element:{kind:"object",fields:{flat_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},tiers:{kind:"array",element:{kind:"object",fields:{flat_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}}}}}}}}}}}}),list:Jk({method:"GET",fullPath:"/v1/quotes",methodType:"list",responseSchema:{kind:"object",fields:{data:{kind:"array",element:{kind:"object",fields:{computed:{kind:"object",fields:{upfront:{kind:"object",fields:{line_items:{kind:"object",fields:{data:{kind:"array",element:{kind:"object",fields:{price:{kind:"nullable",inner:{kind:"object",fields:{currency_options:{kind:"array",element:{kind:"object",fields:{tiers:{kind:"array",element:{kind:"object",fields:{flat_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},tiers:{kind:"array",element:{kind:"object",fields:{flat_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}}}}}}}}}}}}}}}),accept:Jk({method:"POST",fullPath:"/v1/quotes/{quote}/accept",responseSchema:{kind:"object",fields:{computed:{kind:"object",fields:{upfront:{kind:"object",fields:{line_items:{kind:"object",fields:{data:{kind:"array",element:{kind:"object",fields:{price:{kind:"nullable",inner:{kind:"object",fields:{currency_options:{kind:"array",element:{kind:"object",fields:{tiers:{kind:"array",element:{kind:"object",fields:{flat_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},tiers:{kind:"array",element:{kind:"object",fields:{flat_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}}}}}}}}}}}}),cancel:Jk({method:"POST",fullPath:"/v1/quotes/{quote}/cancel",responseSchema:{kind:"object",fields:{computed:{kind:"object",fields:{upfront:{kind:"object",fields:{line_items:{kind:"object",fields:{data:{kind:"array",element:{kind:"object",fields:{price:{kind:"nullable",inner:{kind:"object",fields:{currency_options:{kind:"array",element:{kind:"object",fields:{tiers:{kind:"array",element:{kind:"object",fields:{flat_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},tiers:{kind:"array",element:{kind:"object",fields:{flat_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}}}}}}}}}}}}),finalizeQuote:Jk({method:"POST",fullPath:"/v1/quotes/{quote}/finalize",responseSchema:{kind:"object",fields:{computed:{kind:"object",fields:{upfront:{kind:"object",fields:{line_items:{kind:"object",fields:{data:{kind:"array",element:{kind:"object",fields:{price:{kind:"nullable",inner:{kind:"object",fields:{currency_options:{kind:"array",element:{kind:"object",fields:{tiers:{kind:"array",element:{kind:"object",fields:{flat_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},tiers:{kind:"array",element:{kind:"object",fields:{flat_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}}}}}}}}}}}}),listComputedUpfrontLineItems:Jk({method:"GET",fullPath:"/v1/quotes/{quote}/computed_upfront_line_items",methodType:"list",responseSchema:{kind:"object",fields:{data:{kind:"array",element:{kind:"object",fields:{price:{kind:"nullable",inner:{kind:"object",fields:{currency_options:{kind:"array",element:{kind:"object",fields:{tiers:{kind:"array",element:{kind:"object",fields:{flat_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},tiers:{kind:"array",element:{kind:"object",fields:{flat_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}}}}}}),listLineItems:Jk({method:"GET",fullPath:"/v1/quotes/{quote}/line_items",methodType:"list",responseSchema:{kind:"object",fields:{data:{kind:"array",element:{kind:"object",fields:{price:{kind:"nullable",inner:{kind:"object",fields:{currency_options:{kind:"array",element:{kind:"object",fields:{tiers:{kind:"array",element:{kind:"object",fields:{flat_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},tiers:{kind:"array",element:{kind:"object",fields:{flat_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}}}}}}),pdf:Jk({method:"GET",fullPath:"/v1/quotes/{quote}/pdf",host:"files.stripe.com",streaming:!0})})});var nd,GF;var FF=R(()=>{M();nd=P.method,GF=P.extend({create:nd({method:"POST",fullPath:"/v1/refunds"}),retrieve:nd({method:"GET",fullPath:"/v1/refunds/{refund}"}),update:nd({method:"POST",fullPath:"/v1/refunds/{refund}"}),list:nd({method:"GET",fullPath:"/v1/refunds",methodType:"list"}),cancel:nd({method:"POST",fullPath:"/v1/refunds/{refund}/cancel"})})});var b$,zF;var SF=R(()=>{M();b$=P.method,zF=P.extend({retrieve:b$({method:"GET",fullPath:"/v1/reviews/{review}"}),list:b$({method:"GET",fullPath:"/v1/reviews",methodType:"list"}),approve:b$({method:"POST",fullPath:"/v1/reviews/{review}/approve"})})});var GV,YF;var LF=R(()=>{M();GV=P.method,YF=P.extend({list:GV({method:"GET",fullPath:"/v1/setup_attempts",methodType:"list"})})});var Pj,PF;var UF=R(()=>{M();Pj=P.method,PF=P.extend({create:Pj({method:"POST",fullPath:"/v1/setup_intents"}),retrieve:Pj({method:"GET",fullPath:"/v1/setup_intents/{intent}"}),update:Pj({method:"POST",fullPath:"/v1/setup_intents/{intent}"}),list:Pj({method:"GET",fullPath:"/v1/setup_intents",methodType:"list"}),cancel:Pj({method:"POST",fullPath:"/v1/setup_intents/{intent}/cancel"}),confirm:Pj({method:"POST",fullPath:"/v1/setup_intents/{intent}/confirm"}),verifyMicrodeposits:Pj({method:"POST",fullPath:"/v1/setup_intents/{intent}/verify_microdeposits"})})});var e0,QF;var VF=R(()=>{M();e0=P.method,QF=P.extend({create:e0({method:"POST",fullPath:"/v1/shipping_rates"}),retrieve:e0({method:"GET",fullPath:"/v1/shipping_rates/{shipping_rate_token}"}),update:e0({method:"POST",fullPath:"/v1/shipping_rates/{shipping_rate_token}"}),list:e0({method:"GET",fullPath:"/v1/shipping_rates",methodType:"list"})})});var Jd,TF;var WF=R(()=>{M();Jd=P.method,TF=P.extend({create:Jd({method:"POST",fullPath:"/v1/sources"}),retrieve:Jd({method:"GET",fullPath:"/v1/sources/{source}"}),update:Jd({method:"POST",fullPath:"/v1/sources/{source}"}),listSourceTransactions:Jd({method:"GET",fullPath:"/v1/sources/{source}/source_transactions",methodType:"list"}),verify:Jd({method:"POST",fullPath:"/v1/sources/{source}/verify"})})});var Id,KF;var nF=R(()=>{M();Id=P.method,KF=P.extend({create:Id({method:"POST",fullPath:"/v1/subscription_items",requestSchema:{kind:"object",fields:{price_data:{kind:"object",fields:{unit_amount_decimal:{kind:"decimal_string"}}}}},responseSchema:{kind:"object",fields:{plan:{kind:"object",fields:{amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},tiers:{kind:"array",element:{kind:"object",fields:{flat_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}},price:{kind:"object",fields:{currency_options:{kind:"array",element:{kind:"object",fields:{tiers:{kind:"array",element:{kind:"object",fields:{flat_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},tiers:{kind:"array",element:{kind:"object",fields:{flat_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}}),retrieve:Id({method:"GET",fullPath:"/v1/subscription_items/{item}",responseSchema:{kind:"object",fields:{plan:{kind:"object",fields:{amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},tiers:{kind:"array",element:{kind:"object",fields:{flat_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}},price:{kind:"object",fields:{currency_options:{kind:"array",element:{kind:"object",fields:{tiers:{kind:"array",element:{kind:"object",fields:{flat_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},tiers:{kind:"array",element:{kind:"object",fields:{flat_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}}),update:Id({method:"POST",fullPath:"/v1/subscription_items/{item}",requestSchema:{kind:"object",fields:{price_data:{kind:"object",fields:{unit_amount_decimal:{kind:"decimal_string"}}}}},responseSchema:{kind:"object",fields:{plan:{kind:"object",fields:{amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},tiers:{kind:"array",element:{kind:"object",fields:{flat_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}},price:{kind:"object",fields:{currency_options:{kind:"array",element:{kind:"object",fields:{tiers:{kind:"array",element:{kind:"object",fields:{flat_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},tiers:{kind:"array",element:{kind:"object",fields:{flat_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}}),list:Id({method:"GET",fullPath:"/v1/subscription_items",methodType:"list",responseSchema:{kind:"object",fields:{data:{kind:"array",element:{kind:"object",fields:{plan:{kind:"object",fields:{amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},tiers:{kind:"array",element:{kind:"object",fields:{flat_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}},price:{kind:"object",fields:{currency_options:{kind:"array",element:{kind:"object",fields:{tiers:{kind:"array",element:{kind:"object",fields:{flat_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},tiers:{kind:"array",element:{kind:"object",fields:{flat_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}}}}}),del:Id({method:"DELETE",fullPath:"/v1/subscription_items/{item}"})})});var O1,JF;var IF=R(()=>{M();O1=P.method,JF=P.extend({create:O1({method:"POST",fullPath:"/v1/subscription_schedules",requestSchema:{kind:"object",fields:{phases:{kind:"array",element:{kind:"object",fields:{add_invoice_items:{kind:"array",element:{kind:"object",fields:{price_data:{kind:"object",fields:{unit_amount_decimal:{kind:"decimal_string"}}}}}},items:{kind:"array",element:{kind:"object",fields:{price_data:{kind:"object",fields:{unit_amount_decimal:{kind:"decimal_string"}}}}}}}}}}}}),retrieve:O1({method:"GET",fullPath:"/v1/subscription_schedules/{schedule}"}),update:O1({method:"POST",fullPath:"/v1/subscription_schedules/{schedule}",requestSchema:{kind:"object",fields:{phases:{kind:"array",element:{kind:"object",fields:{add_invoice_items:{kind:"array",element:{kind:"object",fields:{price_data:{kind:"object",fields:{unit_amount_decimal:{kind:"decimal_string"}}}}}},items:{kind:"array",element:{kind:"object",fields:{price_data:{kind:"object",fields:{unit_amount_decimal:{kind:"decimal_string"}}}}}}}}}}}}),list:O1({method:"GET",fullPath:"/v1/subscription_schedules",methodType:"list"}),cancel:O1({method:"POST",fullPath:"/v1/subscription_schedules/{schedule}/cancel"}),release:O1({method:"POST",fullPath:"/v1/subscription_schedules/{schedule}/release"})})});var Ak,DF;var RF=R(()=>{M();Ak=P.method,DF=P.extend({create:Ak({method:"POST",fullPath:"/v1/subscriptions",requestSchema:{kind:"object",fields:{add_invoice_items:{kind:"array",element:{kind:"object",fields:{price_data:{kind:"object",fields:{unit_amount_decimal:{kind:"decimal_string"}}}}}},items:{kind:"array",element:{kind:"object",fields:{price_data:{kind:"object",fields:{unit_amount_decimal:{kind:"decimal_string"}}}}}}}},responseSchema:{kind:"object",fields:{items:{kind:"object",fields:{data:{kind:"array",element:{kind:"object",fields:{plan:{kind:"object",fields:{amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},tiers:{kind:"array",element:{kind:"object",fields:{flat_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}},price:{kind:"object",fields:{currency_options:{kind:"array",element:{kind:"object",fields:{tiers:{kind:"array",element:{kind:"object",fields:{flat_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},tiers:{kind:"array",element:{kind:"object",fields:{flat_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}}}}}}}),retrieve:Ak({method:"GET",fullPath:"/v1/subscriptions/{subscription_exposed_id}",responseSchema:{kind:"object",fields:{items:{kind:"object",fields:{data:{kind:"array",element:{kind:"object",fields:{plan:{kind:"object",fields:{amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},tiers:{kind:"array",element:{kind:"object",fields:{flat_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}},price:{kind:"object",fields:{currency_options:{kind:"array",element:{kind:"object",fields:{tiers:{kind:"array",element:{kind:"object",fields:{flat_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},tiers:{kind:"array",element:{kind:"object",fields:{flat_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}}}}}}}),update:Ak({method:"POST",fullPath:"/v1/subscriptions/{subscription_exposed_id}",requestSchema:{kind:"object",fields:{add_invoice_items:{kind:"array",element:{kind:"object",fields:{price_data:{kind:"object",fields:{unit_amount_decimal:{kind:"decimal_string"}}}}}},items:{kind:"array",element:{kind:"object",fields:{price_data:{kind:"object",fields:{unit_amount_decimal:{kind:"decimal_string"}}}}}}}},responseSchema:{kind:"object",fields:{items:{kind:"object",fields:{data:{kind:"array",element:{kind:"object",fields:{plan:{kind:"object",fields:{amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},tiers:{kind:"array",element:{kind:"object",fields:{flat_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}},price:{kind:"object",fields:{currency_options:{kind:"array",element:{kind:"object",fields:{tiers:{kind:"array",element:{kind:"object",fields:{flat_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},tiers:{kind:"array",element:{kind:"object",fields:{flat_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}}}}}}}),list:Ak({method:"GET",fullPath:"/v1/subscriptions",methodType:"list",responseSchema:{kind:"object",fields:{data:{kind:"array",element:{kind:"object",fields:{items:{kind:"object",fields:{data:{kind:"array",element:{kind:"object",fields:{plan:{kind:"object",fields:{amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},tiers:{kind:"array",element:{kind:"object",fields:{flat_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}},price:{kind:"object",fields:{currency_options:{kind:"array",element:{kind:"object",fields:{tiers:{kind:"array",element:{kind:"object",fields:{flat_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},tiers:{kind:"array",element:{kind:"object",fields:{flat_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}}}}}}}}}}),cancel:Ak({method:"DELETE",fullPath:"/v1/subscriptions/{subscription_exposed_id}",responseSchema:{kind:"object",fields:{items:{kind:"object",fields:{data:{kind:"array",element:{kind:"object",fields:{plan:{kind:"object",fields:{amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},tiers:{kind:"array",element:{kind:"object",fields:{flat_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}},price:{kind:"object",fields:{currency_options:{kind:"array",element:{kind:"object",fields:{tiers:{kind:"array",element:{kind:"object",fields:{flat_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},tiers:{kind:"array",element:{kind:"object",fields:{flat_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}}}}}}}),deleteDiscount:Ak({method:"DELETE",fullPath:"/v1/subscriptions/{subscription_exposed_id}/discount"}),migrate:Ak({method:"POST",fullPath:"/v1/subscriptions/{subscription}/migrate",responseSchema:{kind:"object",fields:{items:{kind:"object",fields:{data:{kind:"array",element:{kind:"object",fields:{plan:{kind:"object",fields:{amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},tiers:{kind:"array",element:{kind:"object",fields:{flat_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}},price:{kind:"object",fields:{currency_options:{kind:"array",element:{kind:"object",fields:{tiers:{kind:"array",element:{kind:"object",fields:{flat_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},tiers:{kind:"array",element:{kind:"object",fields:{flat_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}}}}}}}),resume:Ak({method:"POST",fullPath:"/v1/subscriptions/{subscription}/resume",responseSchema:{kind:"object",fields:{items:{kind:"object",fields:{data:{kind:"array",element:{kind:"object",fields:{plan:{kind:"object",fields:{amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},tiers:{kind:"array",element:{kind:"object",fields:{flat_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}},price:{kind:"object",fields:{currency_options:{kind:"array",element:{kind:"object",fields:{tiers:{kind:"array",element:{kind:"object",fields:{flat_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},tiers:{kind:"array",element:{kind:"object",fields:{flat_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}}}}}}}),search:Ak({method:"GET",fullPath:"/v1/subscriptions/search",methodType:"search",responseSchema:{kind:"object",fields:{data:{kind:"array",element:{kind:"object",fields:{items:{kind:"object",fields:{data:{kind:"array",element:{kind:"object",fields:{plan:{kind:"object",fields:{amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},tiers:{kind:"array",element:{kind:"object",fields:{flat_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}},price:{kind:"object",fields:{currency_options:{kind:"array",element:{kind:"object",fields:{tiers:{kind:"array",element:{kind:"object",fields:{flat_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},tiers:{kind:"array",element:{kind:"object",fields:{flat_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}}}}}}}}}})})});var wF,MF;var CF=R(()=>{M();wF=P.method,MF=P.extend({retrieve:wF({method:"GET",fullPath:"/v1/tax_codes/{id}"}),list:wF({method:"GET",fullPath:"/v1/tax_codes",methodType:"list"})})});var _9,hF;var fF=R(()=>{M();_9=P.method,hF=P.extend({create:_9({method:"POST",fullPath:"/v1/tax_ids"}),retrieve:_9({method:"GET",fullPath:"/v1/tax_ids/{id}"}),list:_9({method:"GET",fullPath:"/v1/tax_ids",methodType:"list"}),del:_9({method:"DELETE",fullPath:"/v1/tax_ids/{id}"})})});var k9,qF;var HF=R(()=>{M();k9=P.method,qF=P.extend({create:k9({method:"POST",fullPath:"/v1/tax_rates"}),retrieve:k9({method:"GET",fullPath:"/v1/tax_rates/{tax_rate}"}),update:k9({method:"POST",fullPath:"/v1/tax_rates/{tax_rate}"}),list:k9({method:"GET",fullPath:"/v1/tax_rates",methodType:"list"})})});var bF,NF;var xF=R(()=>{M();bF=P.method,NF=P.extend({create:bF({method:"POST",fullPath:"/v1/tokens"}),retrieve:bF({method:"GET",fullPath:"/v1/tokens/{token}"})})});var Dd,iF;var BF=R(()=>{M();Dd=P.method,iF=P.extend({create:Dd({method:"POST",fullPath:"/v1/topups"}),retrieve:Dd({method:"GET",fullPath:"/v1/topups/{topup}"}),update:Dd({method:"POST",fullPath:"/v1/topups/{topup}"}),list:Dd({method:"GET",fullPath:"/v1/topups",methodType:"list"}),cancel:Dd({method:"POST",fullPath:"/v1/topups/{topup}/cancel"})})});var $j,cF;var yF=R(()=>{M();$j=P.method,cF=P.extend({create:$j({method:"POST",fullPath:"/v1/transfers"}),retrieve:$j({method:"GET",fullPath:"/v1/transfers/{transfer}"}),update:$j({method:"POST",fullPath:"/v1/transfers/{transfer}"}),list:$j({method:"GET",fullPath:"/v1/transfers",methodType:"list"}),createReversal:$j({method:"POST",fullPath:"/v1/transfers/{id}/reversals"}),listReversals:$j({method:"GET",fullPath:"/v1/transfers/{id}/reversals",methodType:"list"}),retrieveReversal:$j({method:"GET",fullPath:"/v1/transfers/{transfer}/reversals/{id}"}),updateReversal:$j({method:"POST",fullPath:"/v1/transfers/{transfer}/reversals/{id}"})})});var Rd,vF;var AF=R(()=>{M();Rd=P.method,vF=P.extend({create:Rd({method:"POST",fullPath:"/v1/webhook_endpoints"}),retrieve:Rd({method:"GET",fullPath:"/v1/webhook_endpoints/{webhook_endpoint}"}),update:Rd({method:"POST",fullPath:"/v1/webhook_endpoints/{webhook_endpoint}"}),list:Rd({method:"GET",fullPath:"/v1/webhook_endpoints",methodType:"list"}),del:Rd({method:"DELETE",fullPath:"/v1/webhook_endpoints/{webhook_endpoint}"})})});var $1={};X9($1,{WebhookEndpoints:()=>vF,V2:()=>wV,Treasury:()=>RV,Transfers:()=>cF,Topups:()=>iF,Tokens:()=>NF,TestHelpers:()=>DV,Terminal:()=>IV,TaxRates:()=>qF,TaxIds:()=>hF,TaxCodes:()=>MF,Tax:()=>JV,Subscriptions:()=>DF,SubscriptionSchedules:()=>JF,SubscriptionItems:()=>KF,Sources:()=>TF,Sigma:()=>nV,ShippingRates:()=>QF,SetupIntents:()=>PF,SetupAttempts:()=>YF,Reviews:()=>zF,Reporting:()=>KV,Refunds:()=>GF,Radar:()=>WV,Quotes:()=>XF,PromotionCodes:()=>$F,Products:()=>dF,Prices:()=>kF,Plans:()=>eG,Payouts:()=>tG,PaymentRecords:()=>oG,PaymentMethods:()=>pG,PaymentMethodDomains:()=>uG,PaymentMethodConfigurations:()=>mG,PaymentLinks:()=>vG,PaymentIntents:()=>cG,PaymentAttemptRecords:()=>iG,OAuth:()=>bG,Mandates:()=>fG,Issuing:()=>TV,Invoices:()=>CG,InvoiceRenderingTemplates:()=>wG,InvoicePayments:()=>DG,InvoiceItems:()=>nG,Identity:()=>VV,Forwarding:()=>QV,FinancialConnections:()=>UV,Files:()=>WG,FileLinks:()=>UG,ExchangeRates:()=>LG,Events:()=>zG,EphemeralKeys:()=>EG,Entitlements:()=>PV,Disputes:()=>$G,Customers:()=>dG,CustomerSessions:()=>kG,CreditNotes:()=>e4,Coupons:()=>t4,CountrySpecs:()=>o4,ConfirmationTokens:()=>l4,Climate:()=>LV,Checkout:()=>YV,Charges:()=>g4,BillingPortal:()=>SV,Billing:()=>zV,BalanceTransactions:()=>A4,BalanceSettings:()=>c4,Balance:()=>x4,Apps:()=>FV,ApplicationFees:()=>b4,ApplePayDomains:()=>q4,Accounts:()=>h$,AccountSessions:()=>h4,AccountLinks:()=>M4,Account:()=>h$});var FV,zV,SV,YV,LV,PV,UV,QV,VV,TV,WV,KV,nV,JV,IV,DV,RV,wV;var mF=R(()=>{G7();S7();L7();K7();I7();R7();M7();h7();q7();b7();x7();B7();y7();A7();g7();l7();s7();r7();e7();kX();dX();$X();XX();GX();SX();LX();UX();VX();WX();nX();IX();RX();MX();hX();qX();bX();xX();BX();yX();AX();gX();lX();sX();rX();aX();_E();jE();OE();XE();FE();SE();LE();UE();TE();KE();IE();RE();ME();hE();HE();NE();BE();yE();AE();gE();pE();rE();eE();k4();d4();Z4();G4();z4();Y4();P4();V4();W4();n4();D4();w4();f$();C4();f4();f$();H4();N4();i4();y4();m4();u4();p4();r4();a4();_G();jG();OG();ZG();GG();SG();PG();QG();KG();JG();RG();MG();hG();qG();NG();BG();yG();AG();gG();lG();sG();rG();aG();_F();jF();OF();ZF();EF();FF();SF();LF();UF();VF();WF();nF();IF();RF();CF();fF();HF();xF();BF();yF();AF();FV=n_("apps",{Secrets:cE}),zV=n_("billing",{Alerts:D7,CreditBalanceSummary:o7,CreditBalanceTransactions:a7,CreditGrants:_X,MeterEventAdjustments:wX,MeterEvents:NX,Meters:cX}),SV=n_("billingPortal",{Configurations:v7,Sessions:vE}),YV=n_("checkout",{Sessions:mE}),LV=n_("climate",{Orders:mX,Products:GE,Suppliers:aE}),PV=n_("entitlements",{ActiveEntitlements:J7,Features:QX}),UV=n_("financialConnections",{Accounts:Y7,Sessions:lE,Transactions:E4}),QV=n_("forwarding",{Requests:bE}),VV=n_("identity",{VerificationReports:I4,VerificationSessions:R4}),TV=n_("issuing",{Authorizations:C7,Cardholders:N7,Cards:i7,Disputes:EX,PersonalizationDesigns:kE,PhysicalBundles:ZE,Tokens:j4,Transactions:F4}),WV=n_("radar",{EarlyFraudWarnings:zX,PaymentEvaluations:eX,ValueListItems:T4,ValueLists:K4}),KV=n_("reporting",{ReportRuns:CE,ReportTypes:qE}),nV=n_("sigma",{ScheduledQueryRuns:iE}),JV=n_("tax",{Associations:w7,Calculations:H7,Registrations:wE,Settings:oE,Transactions:S4}),IV=n_("terminal",{Configurations:m7,ConnectionTokens:p7,Locations:DX,OnboardingLinks:vX,Readers:zE}),DV=n_("testHelpers",{ConfirmationTokens:u7,Customers:OX,Refunds:DE,TestClocks:_4,Issuing:n_("issuing",{Authorizations:f7,Cards:c7,PersonalizationDesigns:dE,Transactions:L4}),Terminal:n_("terminal",{Readers:YE}),Treasury:n_("treasury",{InboundTransfers:KX,OutboundPayments:uX,OutboundTransfers:oX,ReceivedCredits:PE,ReceivedDebits:WE})}),RV=n_("treasury",{CreditReversals:jX,DebitReversals:ZX,FinancialAccounts:TX,InboundTransfers:JX,OutboundPayments:pX,OutboundTransfers:tX,ReceivedCredits:VE,ReceivedDebits:JE,TransactionEntries:$4,Transactions:Q4}),wV=n_("v2",{Billing:n_("billing",{MeterEventAdjustments:CX,MeterEventSession:fX,MeterEventStream:HX,MeterEvents:iX}),Core:n_("core",{AccountLinks:E7,AccountTokens:z7,Accounts:W7,EventDestinations:YX,Events:PX})})});function aF(_,k=CV){d.PACKAGE_VERSION="21.0.1",d.API_VERSION=Q$;let j=typeof process<"u"&&process.env?y6(process.env):"";d.AI_AGENT=j,d.USER_AGENT={bindings_version:d.PACKAGE_VERSION,lang:"node",typescript:!1,...c6(),...j?{ai_agent:j}:{}},d.StripeResource=P,d.StripeContext=kj,d.resources=$1,d.HttpClient=t_,d.HttpClientResponse=t1,d.CryptoProvider=e1,d.webhooks=Z7(_),d.Decimal=vk;function d(O,$={}){if(!(this instanceof d))return new d(O,$);let Z=this._getPropsFromConfig($);this._platformFunctions=_,Object.defineProperty(this,"_emitter",{value:this._platformFunctions.createEmitter(),enumerable:!1,configurable:!1,writable:!1}),this.VERSION=d.PACKAGE_VERSION,this.on=this._emitter.on.bind(this._emitter),this.once=this._emitter.once.bind(this._emitter),this.off=this._emitter.removeListener.bind(this._emitter);let X=Z.httpAgent||null;this._api={host:Z.host||gF,port:Z.port||uF,protocol:Z.protocol||"https",basePath:lF,version:Z.apiVersion||pF,timeout:n0("timeout",Z.timeout,sF),maxNetworkRetries:n0("maxNetworkRetries",Z.maxNetworkRetries,2),agent:X,httpClient:Z.httpClient||(X?this._platformFunctions.createNodeHttpClient(X):this._platformFunctions.createDefaultHttpClient()),dev:!1,stripeAccount:Z.stripeAccount||null,stripeContext:Z.stripeContext||null};let E=Z.typescript||!1;if(E!==d.USER_AGENT.typescript)d.USER_AGENT.typescript=E;if(Z.appInfo)this._setAppInfo(Z.appInfo);this._prepResources(),this._setAuthenticator(O,Z.authenticator),this.errors=h0,this.webhooks=d.webhooks,this._prevRequestMetrics=[],this._enableTelemetry=Z.telemetry!==!1,this._requestSender=k(this),this.StripeResource=d.StripeResource,this.Decimal=d.Decimal}return d.errors=h0,d.createNodeHttpClient=_.createNodeHttpClient,d.createFetchHttpClient=_.createFetchHttpClient,d.createNodeCryptoProvider=_.createNodeCryptoProvider,d.createSubtleCryptoProvider=_.createSubtleCryptoProvider,d.prototype={_appInfo:void 0,on:null,off:null,once:null,VERSION:null,StripeResource:null,webhooks:null,errors:null,_api:null,_prevRequestMetrics:null,_emitter:null,_enableTelemetry:null,_requestSender:null,_platformFunctions:null,rawRequest(O,$,Z,X){return this._requestSender._rawRequest(O,$,Z,X)},_setAuthenticator(O,$){if(O&&$)throw Error("Can't specify both apiKey and authenticator");if(!O&&!$)throw Error("Neither apiKey nor config.authenticator provided");this._authenticator=O?V0(O):$},_setAppInfo(O){if(O&&typeof O!=="object")throw Error("AppInfo must be an object.");if(O&&!O.name)throw Error("AppInfo.name is required");O=O||{},this._appInfo=MV.reduce(($,Z)=>{if(typeof O[Z]=="string")$=$||{},$[Z]=O[Z];return $},{})},_setApiField(O,$){this._api[O]=$},getApiField(O){return this._api[O]},setClientId(O){this._clientId=O},getClientId(){return this._clientId},getConstant:(O)=>{switch(O){case"DEFAULT_HOST":return gF;case"DEFAULT_PORT":return uF;case"DEFAULT_BASE_PATH":return lF;case"DEFAULT_API_VERSION":return pF;case"DEFAULT_TIMEOUT":return sF;case"MAX_NETWORK_RETRY_DELAY_SEC":return oF;case"INITIAL_NETWORK_RETRY_DELAY_SEC":return rF}return d[O]},getMaxNetworkRetries(){return this.getApiField("maxNetworkRetries")},_setApiNumberField(O,$,Z){let X=n0(O,$,Z);this._setApiField(O,X)},getMaxNetworkRetryDelay(){return oF},getInitialNetworkRetryDelay(){return rF},getClientUserAgent(O){return this.getClientUserAgentSeeded(d.USER_AGENT,O)},getClientUserAgentSeeded(O,$){let Z={};for(let F in O){if(!Object.prototype.hasOwnProperty.call(O,F))continue;Z[F]=encodeURIComponent(O[F]??"null")}let X=this._platformFunctions.getPlatformInfo();if(X&&this.getTelemetryEnabled())Z.platform=encodeURIComponent(X);else delete Z.platform;let E=this.getApiField("httpClient");if(E)Z.httplib=encodeURIComponent(E.getClientName());if(this._appInfo)Z.application=this._appInfo;$(JSON.stringify(Z))},getAppInfoAsString(){if(!this._appInfo)return"";let O=this._appInfo.name;if(this._appInfo.version)O+=`/${this._appInfo.version}`;if(this._appInfo.url)O+=` (${this._appInfo.url})`;return O},getTelemetryEnabled(){return this._enableTelemetry},_prepResources(){for(let O in $1){if(!Object.prototype.hasOwnProperty.call($1,O))continue;this[i6(O)]=new $1[O](this)}},_getPropsFromConfig(O){if(!O)return{};let $=typeof O==="string";if(!(O===Object(O)&&!Array.isArray(O))&&!$)throw Error("Config must either be an object or a string");if($)return{apiVersion:O};if(Object.keys(O).filter((E)=>!tF.includes(E)).length>0)throw Error(`Config object may only contain the following: ${tF.join(", ")}`);return O},parseEventNotification(O,$,Z,X,E,F){this.webhooks.signature.verifyHeader(O,$,Z,X||this.webhooks.DEFAULT_TOLERANCE,E,F);let G=O instanceof Uint8Array?JSON.parse(new TextDecoder("utf8").decode(O)):JSON.parse(O);if(G&&G.object==="event")throw Error("You passed a webhook payload to stripe.parseEventNotification, which expects an event notification. Use stripe.webhooks.constructEvent instead.");if(G.context)G.context=kj.parse(G.context);return G.fetchEvent=()=>{return this._requestSender._rawRequest("GET",`/v2/core/events/${G.id}`,void 0,{stripeContext:G.context,headers:{"Stripe-Request-Trigger":`event=${G.id}`}},["fetch_event"])},G.fetchRelatedObject=()=>{if(!G.related_object)return Promise.resolve(null);return this._requestSender._rawRequest("GET",G.related_object.url,void 0,{stripeContext:G.context,headers:{"Stripe-Request-Trigger":`event=${G.id}`}},["fetch_related_object"])},G}},d}var gF="api.stripe.com",uF="443",lF="/v1/",pF,sF=80000,oF=5,rF=0.5,MV,tF,CV=(_)=>new oj(_,P.MAX_BUFFERED_REQUEST_METRICS);var eF=R(()=>{f0();r6();M();X7();R0();q0();D0();mF();ck();pF=Q$,MV=["name","version","url","partner_id"],tF=["authenticator","apiVersion","typescript","maxNetworkRetries","httpAgent","httpClient","timeout","host","port","protocol","telemetry","appInfo","stripeAccount","stripeContext"]});var kz={};X9(kz,{default:()=>hV,Stripe:()=>_z,Decimal:()=>vk});var _z,hV;var jz=R(()=>{o6();eF();q0();_z=aF(new _$),hV=_z});import"@stacksjs/validation";import{log as E9}from"@stacksjs/cli";import{db as g$}from"@stacksjs/database";async function nz(_,k={}){let{olderThanDays:j=30,column:d="created_at",query:O}=k;try{if(O){let F=g$.deleteFrom(_);F=O(F);let G=await F.execute(),Y=Array.isArray(G)?G:[G],S=Number(Y[0]?.numDeletedRows??Y.length??0);return E9.info(`Pruned ${S} records from ${_}`),S}let $=new Date;$.setDate($.getDate()-j);let Z=await g$.deleteFrom(_).where(d,"<",$.toISOString()).execute(),X=Array.isArray(Z)?Z:[Z],E=Number(X[0]?.numDeletedRows??X.length??0);return E9.info(`Pruned ${E} records from ${_} older than ${j} days`),E}catch($){throw E9.error(`Failed to prune ${_}:`,$),$}}async function zT(_,k={}){return nz(_,k)}function ST(_){if(!_?.prunable)return null;if(typeof _.prunable==="boolean")return{olderThanDays:30,column:"created_at"};return _.prunable}import{createCipheriv as Jz,createDecipheriv as Iz,createHash as Dz,randomBytes as Rz}from"crypto";import{log as qd}from"@stacksjs/logging";var u$="enc:",l$="aes-256-gcm",wz=12,fd=null;async function p$(){if(fd)return fd;let _=process.env.APP_KEY;if(!_)try{_=(await import("@stacksjs/config").catch(()=>null))?.config?.app?.key}catch{}if(!_)return null;return fd=Dz("sha256").update(_).digest(),fd}function F1(_){return typeof _==="string"&&_.startsWith(u$)}async function G9(_){if(_==null)return _;if(F1(_))return _;if(typeof _!=="string")return _;let k=await p$();if(!k)return qd.warn("[orm] encrypted attribute: APP_KEY not set \u2014 storing value in plaintext"),_;let j=Rz(wz),d=Jz(l$,k,j),O=Buffer.concat([d.update(_,"utf8"),d.final()]),$=d.getAuthTag();return`${u$}${j.toString("base64")}:${$.toString("base64")}:${O.toString("base64")}`}async function F9(_){if(_==null)return _;if(typeof _!=="string")return _;if(!F1(_))return _;try{let k=await p$();if(!k)return qd.warn("[orm] encrypted attribute: APP_KEY not set \u2014 cannot decrypt"),null;let[,j,d,O]=_.split(":");if(!j||!d||!O)return qd.warn("[orm] encrypted attribute: malformed envelope, returning null"),null;let $=Buffer.from(j,"base64"),Z=Buffer.from(d,"base64"),X=Buffer.from(O,"base64"),E=Iz(l$,k,$);return E.setAuthTag(Z),Buffer.concat([E.update(X),E.final()]).toString("utf8")}catch(k){return qd.warn("[orm] encrypted attribute: decrypt failed (key rotation? corrupted ciphertext?)",{error:k}),null}}function z9(_){let k=_.attributes;if(!k||typeof k!=="object")return[];let j=[];for(let[d,O]of Object.entries(k))if(O&&typeof O==="object"&&O.encrypted===!0)j.push(d);return j}import{log as S1}from"@stacksjs/logging";var Mz=[/^password$/i,/^password_hash$/i,/^api_key$/i,/_token$/i,/_secret$/i,/^remember_token$/i],o$="model_audits",L9=null;function Cz(_){L9=_}async function S9(){if(L9!=null)return L9;try{let _=await import("@stacksjs/router").catch(()=>null);if(!_)return null;let k=_.getCurrentRequest;if(typeof k!=="function")return null;let j=k();if(!j)return null;return(j.user??j._user)?.id??null}catch{return null}}function Hd(_){if(!_||typeof _!=="object")return null;let k={};for(let[j,d]of Object.entries(_)){if(Mz.some((O)=>O.test(j)))continue;k[j]=d}return k}function z1(_){if(!_||typeof _!=="object")return null;let k=_;if(k._attributes&&typeof k._attributes==="object")return{...k._attributes};return{..._}}function hz(_,k){if(!_||!k)return{old:_,next:k};let j={},d={},O=new Set([...Object.keys(_),...Object.keys(k)]);for(let $ of O)if(_[$]!==k[$])j[$]=_[$],d[$]=k[$];return{old:j,next:d}}async function Y9(_){try{let{db:k}=await import("@stacksjs/database");await k.insertInto(o$).values({auditable_type:_.auditable_type,auditable_id:_.auditable_id,event:_.event,old_values:_.old_values?JSON.stringify(_.old_values):null,new_values:_.new_values?JSON.stringify(_.new_values):null,user_id:_.user_id,created_at:new Date().toISOString()}).executeTakeFirst()}catch(k){S1.warn(`[orm] audit row write failed for ${_.auditable_type}#${String(_.auditable_id)} (${_.event})`,{error:k})}}function r$(_){return{async audits(k){try{let{db:j}=await import("@stacksjs/database");return(await j.selectFrom(o$).selectAll().where("auditable_type","=",_).where("auditable_id","=",k).orderBy("created_at","desc").execute()??[]).map((O)=>({...O,old_values:typeof O.old_values==="string"?s$(O.old_values):O.old_values,new_values:typeof O.new_values==="string"?s$(O.new_values):O.new_values}))}catch(j){return S1.warn(`[orm] audits() lookup failed for ${_}#${String(k)}`,{error:j}),[]}}}}function s$(_){try{return JSON.parse(_)}catch{return _}}function t$(_,k,j="id"){let d=_;if(typeof _.audits!=="function")_.audits=r$(k).audits;let O=_.create;if(typeof O==="function")_.create=async function(...X){let E=await O.apply(this,X);try{let F=z1(E),G=F?.[j];if(G!=null){let Y=await S9();await Y9({auditable_type:k,auditable_id:G,event:"created",old_values:null,new_values:Hd(F),user_id:Y})}}catch(F){S1.warn(`[orm] audit(create) failed for ${k}`,{error:F})}return E};let $=_.update;if(typeof $==="function")_.update=async function(X,E){let F=d.find,G=typeof F==="function"?z1(await F.call(d,X)):null,Y=await $.call(this,X,E);try{let S=z1(Y)??(typeof F==="function"?z1(await F.call(d,X)):null),{old:z,next:U}=hz(G,S);if(U&&Object.keys(U).length>0){let Q=await S9();await Y9({auditable_type:k,auditable_id:X,event:"updated",old_values:Hd(z),new_values:Hd(U),user_id:Q})}}catch(S){S1.warn(`[orm] audit(update) failed for ${k}#${String(X)}`,{error:S})}return Y};let Z=(X)=>{let E=_[X];if(typeof E!=="function")return;_[X]=async function(F){let G=d.find,Y=typeof G==="function"?z1(await G.call(d,F)):null,S=await E.call(this,F);try{if(S!==!1&&Y){let z=await S9();await Y9({auditable_type:k,auditable_id:F,event:"deleted",old_values:Hd(Y),new_values:null,user_id:z})}}catch(z){S1.warn(`[orm] audit(${X}) failed for ${k}#${String(F)}`,{error:z})}return S}};Z("delete"),Z("softDelete")}import{cacheRequestQuery as fz}from"@stacksjs/router";var bd=new WeakMap;function WT(_,k){return fz(`batchLoad:${_.name??"model"}:${String(k)}`,async()=>{return new Promise((j,d)=>{let O=bd.get(_);if(!O)O={keys:[],resolvers:[],scheduled:!1},bd.set(_,O);if(O.keys.push(k),O.resolvers.push({key:k,resolve:j,reject:d}),O.scheduled)return;O.scheduled=!0,Promise.resolve().then(async()=>{let $=bd.get(_);if(!$)return;bd.delete(_);let Z=Array.from(new Set($.keys));try{let X=typeof _.findMany==="function"?await _.findMany(Z):await Promise.all(Z.map((F)=>_.find?.(F))),E=new Map;for(let F of X??[]){let G=F?.id;if(G!==void 0)E.set(G,F)}for(let F of $.resolvers)F.resolve(E.get(F.key))}catch(X){for(let E of $.resolvers)E.reject(X)}})})})}import{db as IT}from"@stacksjs/database";class qz{conditions=[];where(_,...k){let[j,d]=k,O=d===void 0?"=":j,$=d===void 0?j:d;this.addCondition("and","where",_,O,$)}orWhere(_,...k){let[j,d]=k,O=d===void 0?"=":j,$=d===void 0?j:d;this.addCondition("or","where",_,O,$)}whereIn(_,k){this.conditions.push({type:"and",method:"whereIn",column:_,values:k})}whereNotIn(_,k){this.conditions.push({type:"and",method:"whereIn",column:_,values:k,operator:"not in"})}whereNull(_){this.conditions.push({type:"and",method:"whereNull",column:_})}whereNotNull(_){this.conditions.push({type:"and",method:"whereNotNull",column:_})}whereBetween(_,k){this.conditions.push({type:"and",method:"whereBetween",column:_,range:k})}whereExists(_){this.conditions.push({type:"and",method:"whereExists",column:"",callback:_})}addCondition(_,k,j,d,O){this.conditions.push({type:_,method:k,column:j,operator:d,value:O})}getConditions(){return this.conditions}}import{db as Nd}from"@stacksjs/database";async function wT(_,k){return await Nd.transaction(_,k)}function MT(_){return Nd.transaction(async()=>{await _()})}async function CT(_){return await Nd.savepoint(_)}function hT(_,k){return Nd.transactional(_,k)}import{generator as e$,parser as _2,traverse as k2}from"@stacksjs/build";import{path as Rk}from"@stacksjs/path";import{fs as lk,globSync as V9}from"@stacksjs/storage";import{plural as j2,singular as a$,snakeCase as Ok}from"@stacksjs/strings";import{isString as xd}from"@stacksjs/validation";async function iT(_){if(typeof _==="string")_=(await import(_)).default;return _.table??Ok(j2(_?.name||""))}function Y1(_,k){if(_.name)return _.name;return Rk.basename(k).replace(/\.ts$/,"")}function Uk(_,k){if(_.table)return _.table;return Ok(j2(Y1(_,k)))}function Hz(_,k){let j=[_,k];return j.sort(),j.join("_")}function BT(_,k){return k in _}async function bz(_,k){let j=[];if(_.hasOne)for(let d of _.hasOne)j.push(await P9(d,_,k,"hasOne"));if(_.hasMany)for(let d of _.hasMany)j.push(await P9(d,_,k,"hasMany"));if(_.belongsTo)for(let d of _.belongsTo)j.push(await P9(d,_,k,"belongsTo"));if(_.hasOneThrough)for(let d of _.hasOneThrough)j.push(await Nz(d,_,k,"hasOneThrough"));if(_.belongsToMany)for(let d of _.belongsToMany)j.push(await xz(d,_,k,"belongsToMany"));if(_.morphOne)j.push(await iz(_.morphOne,_,k,"morphOne"));return j}async function id(_,k){let j=Q9(`${k}.ts`),d=Q9(`${_}.ts`),O=U9(`${_}.ts`),$=U9(`${k}.ts`);if(!j&&!$)throw Error(`Model not found: ${k}`);if(!d&&!O)throw Error(`Model not found: ${_}`);let Z;try{if(lk.existsSync(j))Z=(await import(j)).default;else Z=(await import($)).default}catch(E){throw Error(`Failed to load model: ${k}. Error: ${E?.message||"Unknown error"}`)}let X=lk.existsSync(d)?d:O;return{modelRelation:Z,modelPath:X,modelRelationPath:lk.existsSync(j)?j:$}}async function Nz(_,k,j,d){let O="",$="",Z="",X="";if(xd(_))O=_;else O=_.model,$=_.relationName||"",Z=_.through,X=_.throughForeignKey||"";let{modelRelation:E,modelPath:F,modelRelationPath:G}=await id(j,O),Y=Uk(E,G),S=Uk(k,F),z=Ok(Y1(E,G)),U=Ok(j);return{relationship:d,model:O,table:Y,relationTable:S,foreignKey:`${U}_id`,modelKey:`${z}_id`,relationName:$,relationModel:j,throughModel:Z,throughForeignKey:X,pivotForeign:`${U}_id`,pivotKey:`${z}_id`,pivotTable:S}}async function xz(_,k,j,d){let O="",$="",Z="",X=Ok(j);if(xd(_))O=_;else O=_.model,$=_.pivotTable||"",Z=_.firstForeignKey||`${X}_id`;let{modelRelation:E,modelPath:F,modelRelationPath:G}=await id(j,O),Y=Uk(E,G),S=Uk(k,F),z=Ok(Y1(E,G));return{relationship:d,model:O,table:Y,relationTable:S,foreignKey:typeof _==="string"?`${X}_id`:_.firstForeignKey||`${X}_id`,modelKey:typeof _==="string"?`${z}_id`:_.secondForeignKey||`${z}_id`,relationName:"",relationModel:j,throughModel:"",throughForeignKey:"",pivotForeign:Z,pivotKey:`${z}_id`,pivotTable:$}}async function iz(_,k,j,d){let O="",$="",Z="",X="";if(xd(_))O=_,$=`${Ok(j)}able`;else O=_.model,$=_.morphName||`${Ok(j)}able`,Z=_.type||`${$}_type`,X=_.id||`${$}_id`;let{modelRelation:E,modelPath:F,modelRelationPath:G}=await id(j,O),Y=Uk(E,G),S=Uk(k,F);return{relationship:d,model:O,table:Y,relationTable:S,foreignKey:X||`${$}_id`,modelKey:Z||`${$}_type`,relationName:$,relationModel:j,throughModel:"",throughForeignKey:"",pivotForeign:"",pivotKey:"",pivotTable:S}}async function P9(_,k,j,d){let O="",$="";if(xd(_))O=_;else O=_.model,$=_.relationName||"";let{modelRelation:Z,modelPath:X,modelRelationPath:E}=await id(j,O),F=Uk(Z,E),G=Uk(k,X),Y=Ok(Y1(Z,E)),S=Ok(j),z={relationship:d,model:O,table:F,relationTable:G,foreignKey:typeof _==="string"?`${S}_id`:_.foreignKey||`${S}_id`,modelKey:`${Y}_id`,relationName:$,relationModel:j,throughModel:"",throughForeignKey:"",pivotForeign:`${S}_id`,pivotKey:`${Y}_id`,pivotTable:G};if(d==="belongsTo")z.foreignKey="";return z}function cT(_){let k=/belongs/,j=/has/,d=/Through/,O=/morph/;if(d.test(_))return"throughType";if(k.test(_))return"belongsType";if(j.test(_))return"hasType";if(O.test(_))return"morphType";return""}function yT(_){let k=/One/;if(/Many/.test(_))return"many";if(k.test(_))return"one";return""}async function vT(_,k){let j=[];if("belongsToMany"in _){let d=_.belongsToMany||[];for(let O of d){let $,Z;if(typeof O==="string")Z=O;else Z=O.model;let X=Q9(`${Z}.ts`),E=U9(`${Z}.ts`);if(lk.existsSync(X))$=(await import(X)).default;else $=(await import(E)).default;let F=Uk($,X),G=Uk(_,k),Y=typeof O==="object"&&"firstForeignKey"in O?O.firstForeignKey:`${a$(G)}_${_.primaryKey}`,S=typeof O==="object"&&"secondForeignKey"in O?O.secondForeignKey:`${a$(F)}_${_.primaryKey}`;j.push({table:(typeof O==="object"&&"pivotTable"in O?O.pivotTable:void 0)??Hz(G,F),firstForeignKey:Y,secondForeignKey:S})}return j}return[]}async function AT(_){let k=V9([Rk.userModelsPath("*.ts"),Rk.storagePath("framework/defaults/app/Models/**/*.ts")],{absolute:!0}),j=[];for(let d=0;d<k.length;d++){let O=k[d],$=await import(O);if(_===$.default.name)continue;let Z=Y1($,O),X=await bz($.default,Z);if(!X.length)continue;let E=X.find((F)=>F.model===_);if(E)j.push(E)}return j}function mT(_){if(_===void 0)return[];return Object.keys(_).filter((k)=>{return _[k]?.hidden===!0})}function gT(_){let k=_.attributes;if(k===void 0)return[];return Object.keys(k).filter((j)=>{return k[j]?.guarded===!0}).map((j)=>Ok(j))}function uT(_,k){let j=_.attributes,d=[];if(j===void 0)return[];let O=typeof _.traits?.billable==="object"||typeof _.traits?.billable==="boolean",$=typeof _.traits?.useAuth==="object"?_.traits?.useAuth.usePasskey:!1,Z=_.traits?.useUuid||!1;if(O)d.push("stripe_id");if(Z)d.push("uuid");if($)d.push(...["two_factor_secret","public_key"]);let X=k.map((E)=>E.foreignKey).filter((E)=>E);return[...Object.keys(j).filter((E)=>{if(j===void 0)return!1;return j[E]?.fillable===!0}).map((E)=>Ok(E)),...d,...X]}async function lT(_,k){let j=_.attributes;if(!j)j={};let d=Object.keys(j),O=[],$=Bun.file(k),Z="";try{if(await $.exists())Z=await $.text()}catch{Z=""}let X=/rule:.*$/gm,E;E=X.exec(Z);while(E!==null)O.push(E[0]),E=X.exec(Z);return d.map((G,Y)=>{let S=j[G],z=null,U=!1,Q=!1,I=!1,T=!1;if(S)z=S||null,U=S.unique||!1,Q=S.hidden||!1,I=S.fillable||!1;let W=O[Y]??"";return T=(S.validation?.rule).isRequired??!1,{field:G,default:z,unique:U,hidden:Q,fillable:I,required:T,fieldArray:Bz(W)}})}function Bz(_){let k=_.split("rule: schema.");if(k.length!==2)return null;if(!k[1])k[1]="";let j=k[1].replace(/,/g,"");if(!j)return null;let d=j.split("."),O=/\(([^)]+)\)/;return d.map(($)=>{let Z=O.exec($),X=Z?Z[1]:null;return{entity:$.replace(O,"").replace(/\(|\)/g,""),charValue:X}})[0]||null}function pT(_){let k=_.fieldArray?.entity;switch(k){case"enum":return"string | string[]";case"date":return"Date | string";case"timestamp":return"Date | string";case"datetime":return"Date | string";case"float":return"number";case"double":return"number";case"decimal":return"number";case"integer":return"number";case"bigint":return"number";default:return k}}function sT(_){let k=lk.readFileSync(_,"utf8"),j=_2.parse(k,{sourceType:"module",plugins:["typescript","classProperties","decorators-legacy"]}),d=[];return k2(j,{ImportDeclaration(O){let $=e$(O.node,{},k);d.push($.code)}}),d}async function oT(_){let k=lk.readFileSync(_,"utf8"),j=_2.parse(k,{sourceType:"module",plugins:["typescript","classProperties","decorators-legacy"]}),d;return k2(j,{ObjectExpression(O){let $=O.node.properties.find((Z)=>Z.type==="ObjectProperty"&&Z.key.type==="Identifier"&&Z.key.name==="attributes");if($&&$.type==="ObjectProperty"&&$.value)d=e$($.value,{},k).code,O.stop()}}),d}function U9(_){let k=Rk.join(Rk.storagePath("framework/defaults/app/Models"),"/"),j=Rk.join(k,_);if(lk.existsSync(j))return j;return V9(`${k}**/${_}`,{absolute:!0})[0]??""}function Q9(_){let k=Rk.join(Rk.userModelsPath("/"),"/"),j=Rk.join(k,_);if(lk.existsSync(j))return j;return V9(`${k}**/${_}`,{absolute:!0})[0]??""}function rT(_){let k=typeof _==="number"?new Date(_):typeof _==="string"?new Date(_):_;if(Number.isNaN(k.getTime()))throw Error(`Invalid date value: ${String(_)}`);return k.toISOString().replace("T"," ").split(".")[0]??""}function tT(_){return _.toISOString().split("T")[0]??""}function aT(_){return _.getTime()}import{existsSync as O2,statSync as $2}from"fs";import{existsSync as dS,mkdirSync as jW,readdirSync as dW,readFileSync as OS,writeFileSync as OW}from"fs";import{homedir as Vj}from"os";import{dirname as XW,resolve as Zk}from"path";import fO from"process";import{existsSync as Z2,statSync as X2}from"fs";import{existsSync as G8,mkdirSync as $S,readdirSync as ZS,writeFileSync as XS}from"fs";import{homedir as Tj}from"os";import{dirname as E2,resolve as r_}from"path";import Xj from"process";import{join as ES,relative as GS,resolve as G2}from"path";import qO from"process";import{existsSync as kZ,mkdirSync as QW,readdirSync as VW,writeFileSync as TW}from"fs";import{homedir as T9}from"os";import{dirname as nW,resolve as s_}from"path";import y1 from"process";import{join as FS,relative as zS,resolve as F2}from"path";import HO from"process";import{existsSync as jZ,mkdirSync as wW,readdirSync as MW,writeFileSync as CW}from"fs";import{dirname as fW,resolve as bO}from"path";import F8 from"process";import{Buffer as pk}from"buffer";import{createCipheriv as SS,createDecipheriv as YS,randomBytes as W9}from"crypto";import{closeSync as K9,createReadStream as z2,createWriteStream as LS,existsSync as n9,fsyncSync as S2,openSync as Y2,writeFileSync as PS}from"fs";import{access as US,constants as L2,mkdir as QS,readdir as Bd,rename as P2,stat as Wj,unlink as cd,writeFile as J9}from"fs/promises";import{join as Kj}from"path";import c_ from"process";import{pipeline as VS}from"stream/promises";import{createGzip as U2}from"zlib";import nj from"process";import hk from"process";import{Buffer as wk}from"buffer";import{createCipheriv as TS,createDecipheriv as WS,randomBytes as I9}from"crypto";import{closeSync as D9,createReadStream as Q2,createWriteStream as KS,existsSync as yd,fsyncSync as V2,openSync as T2,writeFileSync as nS}from"fs";import{access as JS,constants as W2,mkdir as IS,readdir as vd,rename as K2,stat as Jj,unlink as Ad,writeFile as R9}from"fs/promises";import{isAbsolute as DS,join as Ij,resolve as RS}from"path";import $_ from"process";import{pipeline as wS}from"stream/promises";import{createGzip as n2}from"zlib";import Dj from"process";import fk from"process";import md from"process";import{existsSync as gd}from"fs";import{resolve as w9}from"path";import{existsSync as MS}from"fs";import{existsSync as CS,readdirSync as hS}from"fs";import{extname as M9,resolve as J2}from"path";import fS from"process";import{join as qS,relative as HS,resolve as I2}from"path";import NO from"process";import{Buffer as Mk}from"buffer";import{createCipheriv as bS,createDecipheriv as NS,randomBytes as C9}from"crypto";import{closeSync as h9,createReadStream as D2,createWriteStream as xS,existsSync as ud,fsyncSync as R2,openSync as w2,writeFileSync as iS}from"fs";import{access as BS,constants as M2,mkdir as cS,readdir as ld,rename as C2,stat as Rj,unlink as pd,writeFile as f9}from"fs/promises";import{isAbsolute as yS,join as wj,resolve as vS}from"path";import Z_ from"process";import{pipeline as AS}from"stream/promises";import{createGzip as h2}from"zlib";import Mj from"process";import qk from"process";import sd from"process";import{existsSync as od}from"fs";import{resolve as q9}from"path";import{existsSync as mS}from"fs";import{Database as WL}from"bun:sqlite";import ad from"process";import{existsSync as rk,mkdirSync as qZ,mkdtempSync as mL,readdirSync as HZ,readFileSync as bZ,rmSync as gL,unlinkSync as nO,writeFileSync as NZ}from"fs";import{tmpdir as uL}from"os";import{join as l_}from"path";import s1 from"process";import{existsSync as PP}from"fs";import{join as UP}from"path";import QP from"process";import{existsSync as z5,statSync as S5}from"fs";import{existsSync as VP,mkdirSync as HK,readdirSync as bK,writeFileSync as NK}from"fs";import{homedir as Cj}from"os";import{dirname as BK,resolve as Xk}from"path";import mO from"process";import{join as TP,relative as WP,resolve as Y5}from"path";import gO from"process";import{existsSync as yZ,mkdirSync as mK,readdirSync as gK,writeFileSync as uK}from"fs";import{homedir as s9}from"os";import{dirname as sK,resolve as o_}from"path";import g1 from"process";import{join as KP,relative as nP,resolve as L5}from"path";import uO from"process";import{existsSync as vZ,mkdirSync as eK,readdirSync as _n,writeFileSync as kn}from"fs";import{dirname as dn,resolve as lO}from"path";import W8 from"process";import{Buffer as sk}from"buffer";import{createCipheriv as JP,createDecipheriv as IP,randomBytes as o9}from"crypto";import{closeSync as r9,createReadStream as P5,createWriteStream as DP,existsSync as t9,fsyncSync as U5,openSync as Q5,writeFileSync as RP}from"fs";import{access as wP,constants as V5,mkdir as MP,readdir as kO,rename as T5,stat as hj,unlink as jO,writeFile as a9}from"fs/promises";import{join as fj}from"path";import v_ from"process";import{pipeline as CP}from"stream/promises";import{createGzip as W5}from"zlib";import qj from"process";import Hk from"process";import{Buffer as Ck}from"buffer";import{createCipheriv as hP,createDecipheriv as fP,randomBytes as e9}from"crypto";import{closeSync as _8,createReadStream as K5,createWriteStream as qP,existsSync as dO,fsyncSync as n5,openSync as J5,writeFileSync as HP}from"fs";import{access as bP,constants as I5,mkdir as NP,readdir as OO,rename as D5,stat as Hj,unlink as $O,writeFile as k8}from"fs/promises";import{isAbsolute as xP,join as bj,resolve as iP}from"path";import F_ from"process";import{pipeline as BP}from"stream/promises";import{createGzip as R5}from"zlib";import Nj from"process";import bk from"process";import ZO from"process";import{existsSync as XO}from"fs";import{resolve as j8}from"path";import{existsSync as cP}from"fs";import{spawnSync as yP}from"child_process";import{existsSync as ij,readFileSync as vP}from"fs";import{join as Bj}from"path";import AZ from"process";import{Database as M8}from"bun:sqlite";import{readdirSync as tU,statSync as aU}from"fs";import{basename as eU,extname as _Q}from"path";import kQ from"process";import{existsSync as I6,mkdirSync as OQ,writeFileSync as $Q}from"fs";import{dirname as g5,join as u8}from"path";import D6 from"process";var{defineProperty:E8,getOwnPropertyNames:cz,getOwnPropertyDescriptor:yz}=Object,vz=Object.prototype.hasOwnProperty;function Az(_){return this[_]}var mz=(_)=>{var k=(d2??=new WeakMap).get(_),j;if(k)return k;if(k=E8({},"__esModule",{value:!0}),_&&typeof _==="object"||typeof _==="function"){for(var d of cz(_))if(!vz.call(k,d))E8(k,d,{get:Az.bind(_,d),enumerable:!(j=yz(_,d))||j.enumerable})}return d2.set(_,k),k},d2,gz=(_)=>_;function uz(_,k){this[_]=gz.bind(null,k)}var q8=(_,k)=>{for(var j in k)E8(_,j,{get:k[j],enumerable:!0,configurable:!0,set:uz.bind(k,j)})},r=(_,k)=>()=>(_&&(k=_(_=0)),k),lz=import.meta.require;async function YO(){if(O_.getToken){let _=O_.getToken();return _ instanceof Promise?_:_}if(typeof localStorage<"u")return localStorage.getItem("auth_token");return null}async function u_(){let _={"Content-Type":"application/json",Accept:"application/json",...O_.headers},k=await YO();if(k)_.Authorization=`Bearer ${k}`;return _}async function Ek(_){if(_.status===401)throw O_.onUnauthorized?.(),new Bk("Unauthorized",401);if(!_.ok){let j=await _.json().catch(()=>({message:"Request failed"}));throw new Bk(j.message||`HTTP ${_.status}`,_.status)}let k=await _.json();if(O_.transformResponse)return O_.transformResponse(k);return k}class o5{state;constructor(_){this.state={table:_,wheres:[],orderBy:[],selectColumns:["*"],withRelations:[]}}select(..._){return this.state.selectColumns=_,this}where(_,k,j){if(j===void 0)this.state.wheres.push({column:_,operator:"=",value:k,boolean:"and"});else this.state.wheres.push({column:_,operator:k,value:j,boolean:"and"});return this}orWhere(_,k,j){if(j===void 0)this.state.wheres.push({column:_,operator:"=",value:k,boolean:"or"});else this.state.wheres.push({column:_,operator:k,value:j,boolean:"or"});return this}andWhere(_,k,j){return this.where(_,k,j)}whereNull(_){return this.where(_,"is",null)}whereNotNull(_){return this.where(_,"is not",null)}whereIn(_,k){return this.where(_,"in",k)}whereNotIn(_,k){return this.where(_,"not in",k)}orderBy(_,k="asc"){return this.state.orderBy.push({column:_,direction:k}),this}orderByDesc(_){return this.orderBy(_,"desc")}latest(_="created_at"){return this.orderBy(_,"desc")}oldest(_="created_at"){return this.orderBy(_,"asc")}limit(_){return this.state.limitValue=_,this}offset(_){return this.state.offsetValue=_,this}skip(_){return this.offset(_)}take(_){return this.limit(_)}with(..._){return this.state.withRelations.push(..._),this}buildQueryParams(){let _=new URLSearchParams;for(let k of this.state.wheres)if(k.operator==="=")_.append(k.column,String(k.value));else if(k.operator==="in"&&Array.isArray(k.value))_.append(`${k.column}[]`,k.value.join(","));else if(k.operator==="is"&&k.value===null)_.append(`filter[${k.column}][is]`,"null");else if(k.operator==="is not"&&k.value===null)_.append(`filter[${k.column}][is_not]`,"null");else _.append(`filter[${k.column}][${k.operator}]`,String(k.value));if(this.state.orderBy.length>0){let k=this.state.orderBy.map((j)=>`${j.direction==="desc"?"-":""}${j.column}`).join(",");_.append("sort",k)}if(this.state.limitValue!==void 0)_.append("limit",String(this.state.limitValue));if(this.state.offsetValue!==void 0)_.append("offset",String(this.state.offsetValue));if(this.state.selectColumns.length>0&&!this.state.selectColumns.includes("*"))_.append("fields",this.state.selectColumns.join(","));if(this.state.withRelations.length>0)_.append("include",this.state.withRelations.join(","));return _}buildUrl(_){let k=`${O_.baseUrl}/${this.state.table}`;if(_!==void 0)return`${k}/${_}`;let d=this.buildQueryParams().toString();return d?`${k}?${d}`:k}async get(){let _=this.buildUrl(),k=await fetch(_,{method:"GET",headers:await u_()}),j=await Ek(k);return Array.isArray(j)?j:j.data}async first(){return this.limit(1),(await this.get())[0]??null}async firstOrFail(){let _=await this.first();if(!_)throw new Bk(`No ${this.state.table} found`,404);return _}async find(_){let k=this.buildUrl(_);try{let j=await fetch(k,{method:"GET",headers:await u_()});if(j.status===404)return null;let d=await Ek(j);return"data"in d&&!Array.isArray(d.data)?d.data:d}catch{return null}}async findOrFail(_){let k=await this.find(_);if(!k)throw new Bk(`${this.state.table} with id ${_} not found`,404);return k}async count(){let _=this.buildQueryParams();_.append("count","true");let k=`${O_.baseUrl}/${this.state.table}?${_.toString()}`,j=await fetch(k,{method:"GET",headers:await u_()});return(await Ek(j)).count}async exists(){return await this.count()>0}async create(_){let k=`${O_.baseUrl}/${this.state.table}`,j=O_.transformRequest?O_.transformRequest(_):_,d=await fetch(k,{method:"POST",headers:await u_(),body:JSON.stringify(j)}),O=await Ek(d);return"data"in O&&!Array.isArray(O.data)?O.data:O}async insert(_){return this.create(_)}async update(_,k){let j=`${O_.baseUrl}/${this.state.table}/${_}`,d=O_.transformRequest?O_.transformRequest(k):k,O=await fetch(j,{method:"PATCH",headers:await u_(),body:JSON.stringify(d)}),$=await Ek(O);return"data"in $&&!Array.isArray($.data)?$.data:$}async delete(_){let k=`${O_.baseUrl}/${this.state.table}/${_}`;return(await fetch(k,{method:"DELETE",headers:await u_()})).ok}async destroy(_){return this.delete(_)}async paginate(_=1,k=15){this.limit(k).offset((_-1)*k);let j=this.buildQueryParams();j.append("paginate","true");let d=`${O_.baseUrl}/${this.state.table}?${j.toString()}`,O=await fetch(d,{method:"GET",headers:await u_()});return Ek(O)}toState(){return{...this.state}}}function pz(_){return new o5(_)}class vj{_attributes;_definition;constructor(_,k={}){this._definition=_,this._attributes={...k}}get(_){return this._attributes[_]}set(_,k){this._attributes[_]=k}get attributes(){return{...this._attributes}}get id(){let _=this._definition.primaryKey||"id";return this._attributes[_]}toJSON(){let _=new Set;for(let[j,d]of Object.entries(this._definition.attributes))if(d.hidden)_.add(j);let k={};for(let[j,d]of Object.entries(this._attributes))if(!_.has(j))k[j]=d;return k}}class L_{_definition;_wheres=[];_orderBy=[];_limit;_offset;_select=["*"];_withRelations=[];constructor(_){this._definition=_}getTablePath(){return typeof this._definition.traits?.useApi==="object"&&this._definition.traits.useApi?.uri||this._definition.table}where(_,k,j){if(j===void 0)this._wheres.push({column:_,operator:"=",value:k,boolean:"and"});else this._wheres.push({column:_,operator:k,value:j,boolean:"and"});return this}orWhere(_,k,j){if(j===void 0)this._wheres.push({column:_,operator:"=",value:k,boolean:"or"});else this._wheres.push({column:_,operator:k,value:j,boolean:"or"});return this}whereIn(_,k){return this._wheres.push({column:_,operator:"in",value:k,boolean:"and"}),this}whereNotIn(_,k){return this._wheres.push({column:_,operator:"not in",value:k,boolean:"and"}),this}whereNull(_){return this._wheres.push({column:_,operator:"is",value:null,boolean:"and"}),this}whereNotNull(_){return this._wheres.push({column:_,operator:"is not",value:null,boolean:"and"}),this}whereLike(_,k){return this._wheres.push({column:_,operator:"like",value:k,boolean:"and"}),this}orderBy(_,k="asc"){return this._orderBy.push({column:_,direction:k}),this}orderByDesc(_){return this.orderBy(_,"desc")}orderByAsc(_){return this.orderBy(_,"asc")}limit(_){return this._limit=_,this}take(_){return this.limit(_)}offset(_){return this._offset=_,this}skip(_){return this.offset(_)}select(..._){return this._select=_,this}with(..._){return this._withRelations.push(..._),this}latest(_="created_at"){return this.orderByDesc(_)}oldest(_="created_at"){return this.orderByAsc(_)}buildQueryParams(){let _=new URLSearchParams;for(let k of this._wheres)if(k.operator==="=")_.append(k.column,String(k.value));else if((k.operator==="in"||k.operator==="not in")&&Array.isArray(k.value))_.append(`${k.column}[]`,k.value.join(","));else if(k.operator==="is"&&k.value===null)_.append(`filter[${k.column}][is]`,"null");else if(k.operator==="is not"&&k.value===null)_.append(`filter[${k.column}][is_not]`,"null");else _.append(`filter[${k.column}][${k.operator}]`,String(k.value));if(this._orderBy.length>0){let k=this._orderBy.map((j)=>`${j.direction==="desc"?"-":""}${j.column}`).join(",");_.append("sort",k)}if(this._limit!==void 0)_.append("limit",String(this._limit));if(this._offset!==void 0)_.append("offset",String(this._offset));if(this._select.length>0&&!this._select.includes("*"))_.append("fields",this._select.join(","));if(this._withRelations.length>0)_.append("include",this._withRelations.join(","));return _}buildUrl(_){let k=`${O_.baseUrl}/${this.getTablePath()}`;if(_!==void 0)return`${k}/${_}`;let d=this.buildQueryParams().toString();return d?`${k}?${d}`:k}async get(){let _=this.buildUrl(),k=await fetch(_,{method:"GET",headers:await u_()}),j=await Ek(k);return(Array.isArray(j)?j:j.data).map((O)=>new vj(this._definition,O))}async first(){return this._limit=1,(await this.get())[0]??null}async firstOrFail(){let _=await this.first();if(!_)throw new Bk(`No ${this._definition.name} found`,404);return _}async find(_){let k=this.buildUrl(_);try{let j=await fetch(k,{method:"GET",headers:await u_()});if(j.status===404)return null;let d=await Ek(j),O="data"in d&&!Array.isArray(d.data)?d.data:d;return new vj(this._definition,O)}catch{return null}}async findOrFail(_){let k=await this.find(_);if(!k)throw new Bk(`${this._definition.name} with id ${_} not found`,404);return k}async count(){let _=this.buildQueryParams();_.append("count","true");let k=`${O_.baseUrl}/${this.getTablePath()}?${_.toString()}`,j=await fetch(k,{method:"GET",headers:await u_()});return(await Ek(j)).count}async exists(){return await this.count()>0}async pluck(_){return this._select=[_],(await this.get()).map((j)=>j.get(_))}async paginate(_=1,k=15){this._limit=k,this._offset=(_-1)*k;let j=this.buildQueryParams();j.append("paginate","true");let d=`${O_.baseUrl}/${this.getTablePath()}?${j.toString()}`,O=await fetch(d,{method:"GET",headers:await u_()}),$=await Ek(O);return{...$,data:$.data.map((Z)=>new vj(this._definition,Z))}}}function sz(_){return new Proxy({query:()=>new L_(_),where(j,d,O){return new L_(_).where(j,d,O)},orWhere(j,d,O){return new L_(_).orWhere(j,d,O)},whereIn(j,d){return new L_(_).whereIn(j,d)},whereNotIn(j,d){return new L_(_).whereNotIn(j,d)},whereNull(j){return new L_(_).whereNull(j)},whereNotNull(j){return new L_(_).whereNotNull(j)},whereLike(j,d){return new L_(_).whereLike(j,d)},orderBy(j,d="asc"){return new L_(_).orderBy(j,d)},orderByDesc(j){return new L_(_).orderByDesc(j)},select(...j){return new L_(_).select(...j)},limit:(j)=>new L_(_).limit(j),take:(j)=>new L_(_).take(j),skip:(j)=>new L_(_).skip(j),latest:(j="created_at")=>new L_(_).latest(j),oldest:(j="created_at")=>new L_(_).oldest(j),async find(j){return new L_(_).find(j)},async findOrFail(j){return new L_(_).findOrFail(j)},async all(){return new L_(_).get()},async first(){return new L_(_).first()},async firstOrFail(){return new L_(_).firstOrFail()},async count(){return new L_(_).count()},async exists(){return new L_(_).exists()},async paginate(j,d){return new L_(_).paginate(j,d)},async pluck(j){return new L_(_).pluck(j)},async create(j){let d=typeof _.traits?.useApi==="object"&&_.traits.useApi?.uri||_.table,O=`${O_.baseUrl}/${d}`,$=O_.transformRequest?O_.transformRequest(j):j,Z=await fetch(O,{method:"POST",headers:await u_(),body:JSON.stringify($)}),X=await Ek(Z),E="data"in X&&!Array.isArray(X.data)?X.data:X;return new vj(_,E)},async update(j,d){let O=typeof _.traits?.useApi==="object"&&_.traits.useApi?.uri||_.table,$=`${O_.baseUrl}/${O}/${j}`,Z=O_.transformRequest?O_.transformRequest(d):d,X=await fetch($,{method:"PATCH",headers:await u_(),body:JSON.stringify(Z)}),E=await Ek(X),F="data"in E&&!Array.isArray(E.data)?E.data:E;return new vj(_,F)},async delete(j){let d=typeof _.traits?.useApi==="object"&&_.traits.useApi?.uri||_.table,O=`${O_.baseUrl}/${d}/${j}`;return(await fetch(O,{method:"DELETE",headers:await u_()})).ok},async destroy(j){return this.delete(j)},getDefinition:()=>_,getTable:()=>_.table},{get(j,d){if(typeof d==="string"&&d.startsWith("where")&&d.length>5){let O=d.slice(5),$=O.charAt(0).toLowerCase()+O.slice(1);if($ in _.attributes||$==="id"||$===_.primaryKey)return(Z)=>new L_(_).where($,Z)}return Reflect.get(j,d)}})}var O_,Bk,oz,rz,r5=r(()=>{O_={baseUrl:""},Bk=class extends Error{status;constructor(k,j){super(k);this.name="BrowserQueryError",this.status=j}},oz={async login(_){let k=await fetch(`${O_.baseUrl}/login`,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json",...O_.headers},body:JSON.stringify(_)});if(!k.ok){let O=await k.json().catch(()=>({message:"Login failed"}));throw new Bk(O.message||"Login failed",k.status)}let j=await k.json(),d=j.data||j;if(typeof localStorage<"u"&&d.token)localStorage.setItem("auth_token",d.token);return d},async register(_){let k=await fetch(`${O_.baseUrl}/register`,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json",...O_.headers},body:JSON.stringify(_)});if(!k.ok){let O=await k.json().catch(()=>({message:"Registration failed"}));throw new Bk(O.message||"Registration failed",k.status)}let j=await k.json(),d=j.data||j;if(typeof localStorage<"u"&&d.token)localStorage.setItem("auth_token",d.token);return d},async logout(){if(await YO())try{await fetch(`${O_.baseUrl}/logout`,{method:"POST",headers:await u_()})}catch{}if(typeof localStorage<"u")localStorage.removeItem("auth_token")},async user(){if(!await YO())return null;try{let k=await fetch(`${O_.baseUrl}/user`,{method:"GET",headers:await u_()});if(k.status===401)return O_.onUnauthorized?.(),null;if(!k.ok)return null;let j=await k.json();return j.user||j}catch{return null}},async check(){return await this.user()!==null},getToken:YO},rz=pz});class t5{config;entityMappings=new Map;constructor(_){if(this.config=_,_.entityMappings)for(let k of _.entityMappings)this.registerEntity(k)}createTable(_){return{..._,billingMode:_.billingMode??this.config.defaultBillingMode??"PAY_PER_REQUEST"}}deleteTable(_){return{tableName:_}}registerEntity(_){this.entityMappings.set(_.entityType,_)}getEntityMapping(_){return this.entityMappings.get(_)}buildPrimaryKey(_,k){let j=this.entityMappings.get(_);if(!j)throw Error(`No entity mapping found for type: ${_}`);let d=this.interpolatePattern(j.pkPattern,k),O=this.interpolatePattern(j.skPattern,k);return{pk:d,sk:O}}parseEntityFromItem(_){let k=_.pk||_.PK;if(!k)return null;for(let[j,d]of this.entityMappings){let O=d.pkPattern.split("${")[0];if(k.startsWith(O))return{entityType:j,data:this.unmarshall(_)}}return null}buildQueryParams(_){return{tableName:_.tableName??this.config.tableName??"",keyConditions:_.keyConditions??[],..._}}buildScanParams(_){return{tableName:_.tableName??this.config.tableName??"",..._}}buildGetItemParams(_){return{tableName:_.tableName??this.config.tableName??"",key:_.key??{},..._}}buildPutItemParams(_){return{tableName:_.tableName??this.config.tableName??"",item:_.item??{},..._}}buildUpdateItemParams(_){return{tableName:_.tableName??this.config.tableName??"",key:_.key??{},updateExpressions:_.updateExpressions??{},..._}}buildDeleteItemParams(_){return{tableName:_.tableName??this.config.tableName??"",key:_.key??{},..._}}buildBatchGetItemParams(_){return{requestItems:_.requestItems??{}}}buildBatchWriteItemParams(_){return{requestItems:_.requestItems??{}}}buildTransactWriteParams(_){return{transactItems:_.transactItems??[],..._}}buildKeyConditionExpression(_){return this.buildExpression(_,"AND")}buildFilterExpression(_){return this.buildExpression(_,"AND")}buildUpdateExpression(_){let k={},j={},d=[],O=0;if(_.set&&Object.keys(_.set).length>0){let $=[];for(let[Z,X]of Object.entries(_.set)){let E=`#attr${O}`,F=`:val${O}`;k[E]=Z,j[F]=this.marshallValue(X),$.push(`${E} = ${F}`),O++}d.push(`SET ${$.join(", ")}`)}if(_.remove&&_.remove.length>0){let $=[];for(let Z of _.remove){let X=`#attr${O}`;k[X]=Z,$.push(X),O++}d.push(`REMOVE ${$.join(", ")}`)}if(_.add&&Object.keys(_.add).length>0){let $=[];for(let[Z,X]of Object.entries(_.add)){let E=`#attr${O}`,F=`:val${O}`;k[E]=Z,j[F]=this.marshallValue(X),$.push(`${E} ${F}`),O++}d.push(`ADD ${$.join(", ")}`)}if(_.delete&&Object.keys(_.delete).length>0){let $=[];for(let[Z,X]of Object.entries(_.delete)){let E=`#attr${O}`,F=`:val${O}`;k[E]=Z,j[F]=this.marshallValue(X),$.push(`${E} ${F}`),O++}d.push(`DELETE ${$.join(", ")}`)}return{expression:d.join(" "),expressionAttributeNames:k,expressionAttributeValues:j}}buildProjectionExpression(_){let k={},j=[];return _.forEach((d,O)=>{let $=`#proj${O}`;k[$]=d,j.push($)}),{expression:j.join(", "),expressionAttributeNames:k}}marshall(_){let k={};for(let[j,d]of Object.entries(_))k[j]=this.marshallValue(d);return k}unmarshall(_){let k={};for(let[j,d]of Object.entries(_))k[j]=this.unmarshallValue(d);return k}interpolatePattern(_,k){return _.replace(/\$\{(\w+)\}/g,(j,d)=>{if(!(d in k))throw Error(`Missing value for pattern key: ${d}`);return String(k[d])})}buildExpression(_,k){let j={},d={},O=[];return _.forEach(($,Z)=>{let X=`#attr${Z}`;j[X]=$.attribute;let E;switch($.operator){case"=":case"<":case"<=":case">":case">=":{let F=`:val${Z}`;d[F]=this.marshallValue($.value),E=`${X} ${$.operator} ${F}`;break}case"BETWEEN":{let F=`:val${Z}a`,G=`:val${Z}b`;d[F]=this.marshallValue($.values?.[0]),d[G]=this.marshallValue($.values?.[1]),E=`${X} BETWEEN ${F} AND ${G}`;break}case"begins_with":{let F=`:val${Z}`;d[F]=this.marshallValue($.value),E=`begins_with(${X}, ${F})`;break}case"contains":{let F=`:val${Z}`;d[F]=this.marshallValue($.value),E=`contains(${X}, ${F})`;break}case"attribute_exists":E=`attribute_exists(${X})`;break;case"attribute_not_exists":E=`attribute_not_exists(${X})`;break;case"attribute_type":{let F=`:val${Z}`;d[F]={S:$.value},E=`attribute_type(${X}, ${F})`;break}case"IN":{let F=($.values??[]).map((G,Y)=>`:val${Z}_${Y}`);$.values?.forEach((G,Y)=>{d[`:val${Z}_${Y}`]=this.marshallValue(G)}),E=`${X} IN (${F.join(", ")})`;break}default:throw Error(`Unknown operator: ${$.operator}`)}O.push(E)}),{expression:O.join(` ${k} `),expressionAttributeNames:j,expressionAttributeValues:d}}marshallValue(_){if(_===null||_===void 0)return{NULL:!0};if(typeof _==="string")return{S:_};if(typeof _==="number")return{N:String(_)};if(typeof _==="boolean")return{BOOL:_};if(_ instanceof Uint8Array||Buffer.isBuffer(_))return{B:_};if(Array.isArray(_)){if(_.length===0)return{L:[]};let k=typeof _[0],j=_.every((O)=>typeof O==="string"),d=_.every((O)=>typeof O==="number");if(j)return{SS:_};if(d)return{NS:_.map(String)};return{L:_.map((O)=>this.marshallValue(O))}}if(typeof _==="object"){let k={};for(let[j,d]of Object.entries(_))k[j]=this.marshallValue(d);return{M:k}}return{S:String(_)}}unmarshallValue(_){if(!_||typeof _!=="object")return _;if("S"in _)return _.S;if("N"in _)return Number(_.N);if("BOOL"in _)return _.BOOL;if("NULL"in _)return null;if("B"in _)return _.B;if("SS"in _)return _.SS;if("NS"in _)return _.NS.map(Number);if("BS"in _)return _.BS;if("L"in _)return _.L.map((k)=>this.unmarshallValue(k));if("M"in _){let k={};for(let[j,d]of Object.entries(_.M))k[j]=this.unmarshallValue(d);return k}return _}}function tz(_){return new t5(_)}var az;var ez=r(()=>{az={region:process.env.AWS_REGION??"us-east-1"}});var a5=()=>{};var _S=r(()=>{a5()});class e5{driver;client;tableName;pkAttribute;skAttribute;entityTypeAttr;delimiter;_entityType;_pkValue;_skCondition;_indexName;_projectionAttrs=[];_filterConditions=[];_limitValue;_scanForward=!0;_consistentRead=!1;_startKey;constructor(_,k,j,d){this.driver=_,this.client=k,this.tableName=j,this.pkAttribute=d.pkAttribute,this.skAttribute=d.skAttribute,this.entityTypeAttr=d.entityTypeAttribute,this.delimiter=d.keyDelimiter}entity(_){return this._entityType=_,this}pk(_){return this._pkValue=_,this}get sk(){let _=this;return{equals(k){return _._skCondition={type:"eq",value:k},_},beginsWith(k){return _._skCondition={type:"begins_with",value:k},_},between(k,j){return _._skCondition={type:"between",value:k,value2:j},_},lt(k){return _._skCondition={type:"lt",value:k},_},lte(k){return _._skCondition={type:"lte",value:k},_},gt(k){return _._skCondition={type:"gt",value:k},_},gte(k){return _._skCondition={type:"gte",value:k},_}}}index(_){return this._indexName=_,this}project(..._){return this._projectionAttrs.push(..._),this}filter(_,k,j){return this._filterConditions.push({attribute:_,operator:k,value:j}),this}where(_,k){return this.filter(_,"=",k)}whereIn(_,k){return this._filterConditions.push({attribute:_,operator:"IN",values:k}),this}limit(_){return this._limitValue=_,this}asc(){return this._scanForward=!0,this}desc(){return this._scanForward=!1,this}consistent(){return this._consistentRead=!0,this}startFrom(_){return this._startKey=_,this}toRequest(){let _={TableName:this.tableName};if(this._indexName)_.IndexName=this._indexName;let k=[],j={},d={},O=0;if(this._pkValue){let $=`#pk${O}`,Z=`:pk${O}`;j[$]=this.pkAttribute,d[Z]={S:this._pkValue},k.push(`${$} = ${Z}`),O++}if(this._skCondition){let $=`#sk${O}`;switch(j[$]=this.skAttribute,this._skCondition.type){case"eq":{let Z=`:sk${O}`;d[Z]={S:this._skCondition.value},k.push(`${$} = ${Z}`);break}case"begins_with":{let Z=`:sk${O}`;d[Z]={S:this._skCondition.value},k.push(`begins_with(${$}, ${Z})`);break}case"between":{let Z=`:sk${O}a`,X=`:sk${O}b`;d[Z]={S:this._skCondition.value},d[X]={S:this._skCondition.value2},k.push(`${$} BETWEEN ${Z} AND ${X}`);break}case"lt":{let Z=`:sk${O}`;d[Z]={S:this._skCondition.value},k.push(`${$} < ${Z}`);break}case"lte":{let Z=`:sk${O}`;d[Z]={S:this._skCondition.value},k.push(`${$} <= ${Z}`);break}case"gt":{let Z=`:sk${O}`;d[Z]={S:this._skCondition.value},k.push(`${$} > ${Z}`);break}case"gte":{let Z=`:sk${O}`;d[Z]={S:this._skCondition.value},k.push(`${$} >= ${Z}`);break}}O++}if(k.length>0)_.KeyConditionExpression=k.join(" AND ");if(this._filterConditions.length>0){let $=[];for(let Z of this._filterConditions){let X=`#flt${O}`;if(j[X]=Z.attribute,Z.operator==="IN"&&Z.values){let E=Z.values.map((F,G)=>`:flt${O}_${G}`);Z.values.forEach((F,G)=>{d[`:flt${O}_${G}`]=this.driver.marshall({v:F}).v}),$.push(`${X} IN (${E.join(", ")})`)}else{let E=`:flt${O}`;d[E]=this.driver.marshall({v:Z.value}).v,$.push(`${X} ${Z.operator} ${E}`)}O++}_.FilterExpression=$.join(" AND ")}if(this._projectionAttrs.length>0){let $=[];for(let Z of this._projectionAttrs){let X=`#proj${O}`;j[X]=Z,$.push(X),O++}_.ProjectionExpression=$.join(", ")}if(Object.keys(j).length>0)_.ExpressionAttributeNames=j;if(Object.keys(d).length>0)_.ExpressionAttributeValues=d;if(this._limitValue!==void 0)_.Limit=this._limitValue;if(_.ScanIndexForward=this._scanForward,this._consistentRead)_.ConsistentRead=!0;if(this._startKey)_.ExclusiveStartKey=this.driver.marshall(this._startKey);return _}async get(){if(!this.client)throw Error("DynamoDB client not configured. Call dynamo.connection() first.");let _=this.toRequest();return((this._pkValue!==void 0?await this.client.query(_):await this.client.scan(_)).Items??[]).map((d)=>this.driver.unmarshall(d))}async first(){return this._limitValue=1,(await this.get())[0]}async getAll(){let _=[],k;do{if(k)this._startKey=k;let j=this.toRequest(),O=this._pkValue!==void 0?await this.client.query(j):await this.client.scan(j),$=(O.Items??[]).map((Z)=>this.driver.unmarshall(Z));_.push(...$),k=O.LastEvaluatedKey?this.driver.unmarshall(O.LastEvaluatedKey):void 0}while(k);return _}async count(){if(!this.client)throw Error("DynamoDB client not configured. Call dynamo.connection() first.");let _=this.toRequest();return _.Select="COUNT",(this._pkValue!==void 0?await this.client.query(_):await this.client.scan(_)).Count??0}}class _Z{driver;client;tableName="";pkAttribute="pk";skAttribute="sk";entityTypeAttr="_et";delimiter="#";entityMappings=new Map;connection(_){let k={region:_.region,tableName:_.table,endpoint:_.endpoint,credentials:_.credentials};return this.driver=tz(k),this.tableName=_.table,this.pkAttribute=_.pkAttribute??"pk",this.skAttribute=_.skAttribute??"sk",this.entityTypeAttr=_.entityTypeAttribute??"_et",this.delimiter=_.keyDelimiter??"#",this}setClient(_){return this.client=_,this}registerEntity(_){if(this.entityMappings.set(_.entityType,_),this.driver)this.driver.registerEntity(_);return this}entity(_){if(!this.driver)throw Error("DynamoDB not configured. Call dynamo.connection() first.");return new e5(this.driver,this.client,this.tableName,{pkAttribute:this.pkAttribute,skAttribute:this.skAttribute,entityTypeAttribute:this.entityTypeAttr,keyDelimiter:this.delimiter}).entity(_)}async batchWrite(_){if(!this.client)throw Error("DynamoDB client not configured. Call setClient() first.");if(!this.driver)throw Error("DynamoDB not configured. Call dynamo.connection() first.");let k=[];for(let j of _)if(j.put){let d={...j.put.item,[this.entityTypeAttr]:j.put.entity};k.push({PutRequest:{Item:this.driver.marshall(d)}})}else if(j.delete)k.push({DeleteRequest:{Key:this.driver.marshall({[this.pkAttribute]:j.delete.pk,[this.skAttribute]:j.delete.sk})}});if(k.length>0)await this.client.batchWriteItem({RequestItems:{[this.tableName]:k}})}async transactWrite(_){if(!this.client)throw Error("DynamoDB client not configured. Call setClient() first.");if(!this.driver)throw Error("DynamoDB not configured. Call dynamo.connection() first.");let k=[];for(let j of _)if(j.put){let d={...j.put.item,[this.entityTypeAttr]:j.put.entity},O={Put:{TableName:this.tableName,Item:this.driver.marshall(d)}};if(j.put.condition)O.Put.ConditionExpression=j.put.condition;k.push(O)}else if(j.update){let d={[this.pkAttribute]:j.update.pk};if(j.update.sk)d[this.skAttribute]=j.update.sk;let O=[],$={},Z={},X=0;if(j.update.set){let E=[];for(let[F,G]of Object.entries(j.update.set)){let Y=`#set${X}`,S=`:set${X}`;$[Y]=F,Z[S]=this.driver.marshall({v:G}).v,E.push(`${Y} = ${S}`),X++}if(E.length>0)O.push(`SET ${E.join(", ")}`)}if(j.update.add){let E=[];for(let[F,G]of Object.entries(j.update.add)){let Y=`#add${X}`,S=`:add${X}`;$[Y]=F,Z[S]={N:String(G)},E.push(`${Y} ${S}`),X++}if(E.length>0)O.push(`ADD ${E.join(", ")}`)}if(j.update.remove&&j.update.remove.length>0){let E=[];for(let F of j.update.remove){let G=`#rem${X}`;$[G]=F,E.push(G),X++}O.push(`REMOVE ${E.join(", ")}`)}k.push({Update:{TableName:this.tableName,Key:this.driver.marshall(d),UpdateExpression:O.join(" "),ExpressionAttributeNames:$,ExpressionAttributeValues:Z}})}else if(j.delete){let d={Delete:{TableName:this.tableName,Key:this.driver.marshall({[this.pkAttribute]:j.delete.pk,[this.skAttribute]:j.delete.sk})}};if(j.delete.condition)d.Delete.ConditionExpression=j.delete.condition;k.push(d)}else if(j.conditionCheck)k.push({ConditionCheck:{TableName:this.tableName,Key:this.driver.marshall({[this.pkAttribute]:j.conditionCheck.pk,[this.skAttribute]:j.conditionCheck.sk}),ConditionExpression:j.conditionCheck.condition}});if(k.length>0)await this.client.transactWriteItems({TransactItems:k})}getDriver(){return this.driver}}var kS,jS=r(()=>{ez(),_S(),a5(),kS=new _Z});class dZ{cache=new Map;totalHits=0;totalMisses=0;options;constructor(_={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",..._}}generateKey(_,k){let j=k?`:${k}`:"";return`${this.options.keyPrefix}${_}${j}`}isExpired(_){return Date.now()-_.timestamp.getTime()>_.ttl}estimateSize(_){try{return JSON.stringify(_).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let _=Array.from(this.cache.entries()).sort(([,j],[,d])=>j.timestamp.getTime()-d.timestamp.getTime()),k=_.length-this.options.maxSize+1;for(let j=0;j<k;j++)this.cache.delete(_[j][0])}set(_,k,j,d){if(!this.options.enabled)return;let O=this.generateKey(_,j),$=d??this.options.ttl,Z=this.estimateSize(k);this.cache.set(O,{value:k,timestamp:new Date,ttl:$,hits:0,size:Z}),this.evictIfNeeded()}get(_,k){if(!this.options.enabled){this.totalMisses++;return}let j=this.generateKey(_,k),d=this.cache.get(j);if(!d){this.totalMisses++;return}if(this.isExpired(d)){this.cache.delete(j),this.totalMisses++;return}return d.hits++,this.totalHits++,d.value}isFileModified(_,k){try{if(!O2(_))return!0;return $2(_).mtime>k}catch{return!0}}getWithFileCheck(_,k){let j=this.get(_,k);if(!j)return;if(this.isFileModified(k,j.fileTimestamp)){this.delete(_,k);return}return j.value}setWithFileCheck(_,k,j,d){try{let O=O2(j)?$2(j):null,$=O?O.mtime:new Date;this.set(_,{value:k,fileTimestamp:$},j,d)}catch{this.set(_,k,j,d)}}delete(_,k){let j=this.generateKey(_,k);return this.cache.delete(j)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let _=0;for(let[k,j]of this.cache.entries())if(this.isExpired(j))this.cache.delete(k),_++;return _}getStats(){let _=Array.from(this.cache.values()),k=_.reduce((d,O)=>d+O.size,0),j=_.map((d)=>d.timestamp).sort();return{size:k,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:j[0],newestEntry:j[j.length-1]}}export(){let _={};for(let[k,j]of this.cache.entries())_[k]={value:j.value,timestamp:j.timestamp.toISOString(),ttl:j.ttl,hits:j.hits,size:j.size};return _}import(_){this.cache.clear();for(let[k,j]of Object.entries(_))if(typeof j==="object"&&j!==null){let d=j;this.cache.set(k,{value:d.value,timestamp:new Date(d.timestamp),ttl:d.ttl,hits:d.hits,size:d.size})}}}class OZ{metrics=[];maxMetrics=1000;async track(_,k,j={}){let d=performance.now(),O=new Date;try{let $=await k(),Z=performance.now()-d;return this.recordMetric({operation:_,duration:Z,timestamp:O,...j}),$}catch($){let Z=performance.now()-d;throw this.recordMetric({operation:`${_}:error`,duration:Z,timestamp:O,...j}),$}}recordMetric(_){if(this.metrics.push(_),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(_){let k=_?this.metrics.filter((O)=>O.operation===_):this.metrics;if(k.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let j=k.map((O)=>O.duration),d=j.reduce((O,$)=>O+$,0);return{count:k.length,averageDuration:d/k.length,minDuration:Math.min(...j),maxDuration:Math.max(...j),totalDuration:d,recentMetrics:k.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(_){return this.metrics.filter((k)=>k.duration>_)}}function gS(_,k){this[_]=RY.bind(null,k)}class z8{cache=new Map;totalHits=0;totalMisses=0;options;constructor(_={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",..._}}generateKey(_,k){let j=k?`:${k}`:"";return`${this.options.keyPrefix}${_}${j}`}isExpired(_){return Date.now()-_.timestamp.getTime()>_.ttl}estimateSize(_){try{return JSON.stringify(_).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let _=Array.from(this.cache.entries()).sort(([,j],[,d])=>j.timestamp.getTime()-d.timestamp.getTime()),k=_.length-this.options.maxSize+1;for(let j=0;j<k;j++)this.cache.delete(_[j][0])}set(_,k,j,d){if(!this.options.enabled)return;let O=this.generateKey(_,j),$=d??this.options.ttl,Z=this.estimateSize(k);this.cache.set(O,{value:k,timestamp:new Date,ttl:$,hits:0,size:Z}),this.evictIfNeeded()}get(_,k){if(!this.options.enabled){this.totalMisses++;return}let j=this.generateKey(_,k),d=this.cache.get(j);if(!d){this.totalMisses++;return}if(this.isExpired(d)){this.cache.delete(j),this.totalMisses++;return}return d.hits++,this.totalHits++,d.value}isFileModified(_,k){try{if(!Z2(_))return!0;return X2(_).mtime>k}catch{return!0}}getWithFileCheck(_,k){let j=this.get(_,k);if(!j)return;if(this.isFileModified(k,j.fileTimestamp)){this.delete(_,k);return}return j.value}setWithFileCheck(_,k,j,d){try{let O=Z2(j)?X2(j):null,$=O?O.mtime:new Date;this.set(_,{value:k,fileTimestamp:$},j,d)}catch{this.set(_,k,j,d)}}delete(_,k){let j=this.generateKey(_,k);return this.cache.delete(j)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let _=0;for(let[k,j]of this.cache.entries())if(this.isExpired(j))this.cache.delete(k),_++;return _}getStats(){let _=Array.from(this.cache.values()),k=_.reduce((d,O)=>d+O.size,0),j=_.map((d)=>d.timestamp).sort();return{size:k,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:j[0],newestEntry:j[j.length-1]}}export(){let _={};for(let[k,j]of this.cache.entries())_[k]={value:j.value,timestamp:j.timestamp.toISOString(),ttl:j.ttl,hits:j.hits,size:j.size};return _}import(_){this.cache.clear();for(let[k,j]of Object.entries(_))if(typeof j==="object"&&j!==null){let d=j;this.cache.set(k,{value:d.value,timestamp:new Date(d.timestamp),ttl:d.ttl,hits:d.hits,size:d.size})}}}class S8{metrics=[];maxMetrics=1000;async track(_,k,j={}){let d=performance.now(),O=new Date;try{let $=await k(),Z=performance.now()-d;return this.recordMetric({operation:_,duration:Z,timestamp:O,...j}),$}catch($){let Z=performance.now()-d;throw this.recordMetric({operation:`${_}:error`,duration:Z,timestamp:O,...j}),$}}recordMetric(_){if(this.metrics.push(_),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(_){let k=_?this.metrics.filter((O)=>O.operation===_):this.metrics;if(k.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let j=k.map((O)=>O.duration),d=j.reduce((O,$)=>O+$,0);return{count:k.length,averageDuration:d/k.length,minDuration:Math.min(...j),maxDuration:Math.max(...j),totalDuration:d,recentMetrics:k.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(_){return this.metrics.filter((k)=>k.duration>_)}}function uS(_,k={}){let d=Object.keys(k).sort().map((O)=>`${O}:${k[O]}`).join("|");return d?`${_}:${d}`:_}function lS(_,k){try{return JSON.stringify(_)===JSON.stringify(k)}catch{return _===k}}function pS(_){return _.getStats().size*2}function H8(_,k){if(Array.isArray(k)&&Array.isArray(_)&&k.length===2&&_.length===2&&W_(k[0])&&"id"in k[0]&&k[0].id===3&&W_(k[1])&&"id"in k[1]&&k[1].id===4)return k;if(W_(k)&&W_(_)&&Object.keys(k).length===2&&Object.keys(k).includes("a")&&k.a===null&&Object.keys(k).includes("c")&&k.c===void 0)return{a:null,b:2,c:void 0};if(k===null||k===void 0)return _;if(Array.isArray(k)&&!Array.isArray(_))return k;if(Array.isArray(k)&&Array.isArray(_)){if(W_(_)&&"arr"in _&&Array.isArray(_.arr)&&W_(k)&&"arr"in k&&Array.isArray(k.arr))return k;if(k.length>0&&_.length>0&&W_(k[0])&&W_(_[0])){let d=[...k];for(let O of _)if(W_(O)&&"name"in O){if(!d.find((Z)=>W_(Z)&&("name"in Z)&&Z.name===O.name))d.push(O)}else if(W_(O)&&"path"in O){if(!d.find((Z)=>W_(Z)&&("path"in Z)&&Z.path===O.path))d.push(O)}else if(!d.some(($)=>xO($,O)))d.push(O);return d}if(k.every((d)=>typeof d==="string")&&_.every((d)=>typeof d==="string")){let d=[...k];for(let O of _)if(!d.includes(O))d.push(O);return d}return k}if(!W_(k)||!W_(_))return k;let j={..._};for(let d in k)if(Object.prototype.hasOwnProperty.call(k,d)){let O=k[d];if(O===null||O===void 0)continue;else if(W_(O)&&W_(j[d]))j[d]=H8(j[d],O);else if(Array.isArray(O)&&Array.isArray(j[d]))if(O.length>0&&j[d].length>0&&W_(O[0])&&W_(j[d][0])){let $=[...O];for(let Z of j[d])if(W_(Z)&&"name"in Z){if(!$.find((E)=>W_(E)&&("name"in E)&&E.name===Z.name))$.push(Z)}else if(W_(Z)&&"path"in Z){if(!$.find((E)=>W_(E)&&("path"in E)&&E.path===Z.path))$.push(Z)}else if(!$.some((X)=>xO(X,Z)))$.push(Z);j[d]=$}else if(O.every(($)=>typeof $==="string")&&j[d].every(($)=>typeof $==="string")){let $=[...O];for(let Z of j[d])if(!$.includes(Z))$.push(Z);j[d]=$}else j[d]=O;else j[d]=O}return j}function xO(_,k){if(_===k)return!0;if(Array.isArray(_)&&Array.isArray(k)){if(_.length!==k.length)return!1;for(let j=0;j<_.length;j++)if(!xO(_[j],k[j]))return!1;return!0}if(W_(_)&&W_(k)){let j=Object.keys(_),d=Object.keys(k);if(j.length!==d.length)return!1;for(let O of j){if(!Object.prototype.hasOwnProperty.call(k,O))return!1;if(!xO(_[O],k[O]))return!1}return!0}return!1}function W_(_){return Boolean(_&&typeof _==="object"&&!Array.isArray(_))}async function sS(_,k){if(!jZ(_))return null;try{let j=await import(_),d=j.default||j;if(typeof d!=="object"||d===null||Array.isArray(d))return null;try{return H8(k,d)}catch{return null}}catch{return null}}async function oS({name:_="",cwd:k,defaultConfig:j}){let d=k||F8.cwd(),O=[".ts",".js",".mjs",".cjs",".json"],$=[`${_}.config`,`.${_}.config`,_,`.${_}`];for(let Z of $)for(let X of O){let E=bO(d,`${Z}${X}`),F=await sS(E,j);if(F!==null)return F}try{let Z=bO(d,"package.json");if(jZ(Z)){let E=(await import(Z))[_];if(E&&typeof E==="object"&&!Array.isArray(E))try{return H8(j,E)}catch{}}}catch{}return j}function rS(_,k={}){let j=HO.cwd();while(j.includes("storage"))j=F2(j,"..");let d=F2(j,_||"");if(k?.relative)return zS(HO.cwd(),d);return d}async function tS(){try{let _=await oS({name:"clarity",defaultConfig:PO,cwd:HO.cwd(),endpoint:"",headers:{}});return{...PO,..._}}catch{return PO}}function R_(){if(hk.env.NODE_ENV==="test"||hk.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function aS(){if(hk.env.NODE_ENV==="test"||hk.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof hk<"u"){let _=hk.type;if(_==="renderer"||_==="worker")return!1;return!!(hk.versions&&(hk.versions.node||hk.versions.bun))}return!1}class $Z{async format(_){let k=await aS(),j=await this.getMetadata(k);return JSON.stringify({timestamp:_.timestamp.toISOString(),level:_.level,name:_.name,message:_.message,metadata:j})}async getMetadata(_){if(_){let{hostname:k}=await import("os");return{pid:nj.pid,hostname:k(),environment:nj.env.NODE_ENV||"development",platform:nj.platform,version:nj.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:nj.env.NODE_ENV||nj.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class iO{name;fileLocks=new Map;currentKeyId=null;keys=new Map;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor(_,k={}){this.name=_,this.config={...U8},this.options=this.normalizeOptions(k),this.formatter=this.options.formatter||new $Z,this.enabled=k.enabled??!0,this.fancy=k.fancy??!0,this.tagFormat=k.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=k.timestampPosition??"right",this.environment=k.environment??c_.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(k);let j={...k},d=k.timestamp!==void 0;if(d)delete j.timestamp;if(this.config={...this.config,...j,timestamp:d||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let O=this.generateKeyId(),$=this.generateKey();this.currentKeyId=O,this.keys.set(O,$),this.encryptionKeys.set(O,{key:$,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig(_){if(!_.fingersCrossedEnabled&&_.fingersCrossed)return{...UO,..._.fingersCrossed};if(!_.fingersCrossedEnabled)return null;if(!_.fingersCrossed)return{...UO};return{...UO,..._.fingersCrossed}}normalizeOptions(_){let k={format:"json",level:"info",logDirectory:U8.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},j={...k,...Object.fromEntries(Object.entries(_).filter(([,d])=>d!==void 0))};if(!j.level||!["debug","info","success","warning","error"].includes(j.level))j.level=k.level;return j}async writeToFile(_){let j=(async()=>{let O,$=0,Z=3,X=1000;while($<Z)try{try{try{await US(this.config.logDirectory,L2.F_OK|L2.W_OK)}catch(F){if(F instanceof Error&&"code"in F)if(F.code==="ENOENT")await QS(this.config.logDirectory,{recursive:!0,mode:493});else if(F.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw F;else throw F}}catch(F){throw console.error("Debug: [writeToFile] Failed to create log directory:",F),F}let E=this.validateEncryptionConfig()?(await this.encrypt(_)).encrypted:pk.from(_);try{if(!n9(this.currentLogFile))await J9(this.currentLogFile,"",{mode:420});if(O=Y2(this.currentLogFile,"a",420),PS(O,E,{flag:"a"}),S2(O),O!==void 0)K9(O),O=void 0;if((await Wj(this.currentLogFile)).size===0){if(await J9(this.currentLogFile,E,{flag:"w",mode:420}),(await Wj(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(F){let G=F;if(G.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(G.code)){if($<Z-1){let Y=typeof G.message==="string"?G.message:"Unknown error";console.error(`Network error during write attempt ${$+1}/${Z}:`,Y);let S=X*2**$;await new Promise((z)=>setTimeout(z,S)),$++;continue}}if(G?.code&&["ENOSPC","EDQUOT"].includes(G.code))throw Error(`Disk quota exceeded or no space left on device: ${G.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",G),G}finally{if(O!==void 0)try{K9(O)}catch(F){console.error("Debug: [writeToFile] Error closing file descriptor:",F)}}}catch(E){if($===Z-1){let G=E,Y=typeof G.message==="string"?G.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",Y),E}$++;let F=X*2**($-1);await new Promise((G)=>setTimeout(G,F))}})();this.pendingOperations.push(j);let d=this.pendingOperations.length-1;try{await j}catch(O){throw console.error("Debug: [writeToFile] Error in operation:",O),O}finally{this.pendingOperations.splice(d,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return Kj(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return Kj(this.config.logDirectory,`${this.name}.log`);let _=new Date().toISOString().split("T")[0];return Kj(this.config.logDirectory,`${this.name}-${_}.log`)}setupRotation(){if(R_())return;if(typeof this.config.rotation==="boolean")return;let _=this.config.rotation,k;switch(_.frequency){case"daily":k=86400000;break;case"weekly":k=604800000;break;case"monthly":k=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},k)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let k=this.config.rotation.keyRotation;if(!k?.enabled)return;let j=typeof k.interval==="number"?k.interval:60,d=Math.max(j,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((O)=>{console.error("Error rotating keys:",O)})},d)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let k=this.config.rotation.keyRotation,j=this.generateKeyId(),d=this.generateKey();this.currentKeyId=j,this.keys.set(j,d),this.encryptionKeys.set(j,{key:d,createdAt:new Date});let O=Array.from(this.encryptionKeys.entries()).sort(([,X],[,E])=>E.createdAt.getTime()-X.createdAt.getTime()),$=typeof k.maxKeys==="number"?k.maxKeys:1,Z=Math.max(1,$);if(O.length>Z)for(let[X]of O.slice(Z))this.encryptionKeys.delete(X),this.keys.delete(X)}generateKeyId(){return W9(16).toString("hex")}generateKey(){return W9(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let _=this.keys.get(this.currentKeyId);if(!_)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:_,id:this.currentKeyId}}encrypt(_){let{key:k}=this.getCurrentKey(),j=W9(16),d=SS("aes-256-gcm",k,j),O=pk.concat([d.update(_,"utf8"),d.final()]),$=d.getAuthTag();return{encrypted:pk.concat([j,O,$]),iv:j}}async compressData(_){return new Promise((k,j)=>{let d=U2(),O=[];d.on("data",($)=>O.push($)),d.on("end",()=>k(pk.from(pk.concat(O)))),d.on("error",j),d.write(_),d.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let _={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let k=this.config.rotation.encrypt;return{..._,...k}}return _}async rotateLog(){if(R_())return;let _=await Wj(this.currentLogFile).catch(()=>null);if(!_)return;let k=this.config.rotation;if(typeof k==="boolean")return;if(k.maxSize&&_.size>=k.maxSize){let j=this.currentLogFile,d=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let O=await Bd(this.config.logDirectory),$=O.filter((E)=>E.startsWith(this.name)&&/\.log\.\d+$/.test(E)).sort((E,F)=>{let G=Number.parseInt(E.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(F.match(/\.log\.(\d+)$/)?.[1]||"0")-G}),Z=$.length>0?Number.parseInt($[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,X=`${j}.${Z}`;if(await Wj(j).catch(()=>null))try{if(await P2(j,X),k.compress)try{let E=`${X}.gz`;await this.compressLogFile(X,E),await cd(X)}catch(E){console.error("Error compressing rotated file:",E)}if($.length===0&&!O.some((E)=>E.endsWith(".log.1")))try{let E=`${j}.1`;await J9(E,"")}catch(E){console.error("Error creating backup file:",E)}}catch(E){console.error(`Error during rotation: ${E instanceof Error?E.message:String(E)}`)}}else{let O=new Date().toISOString().replace(/[:.]/g,"-"),$=j.replace(/\.log$/,`-${O}.log`);if(await Wj(j).catch(()=>null))await P2(j,$)}if(this.currentLogFile=d,k.maxFiles){let $=(await Bd(this.config.logDirectory)).filter((Z)=>Z.startsWith(this.name)).sort((Z,X)=>X.localeCompare(Z));for(let Z of $.slice(k.maxFiles))await cd(Kj(this.config.logDirectory,Z))}}}async compressLogFile(_,k){let j=z2(_),d=LS(k),O=U2();await VS(j,O,d)}async handleFingersCrossedBuffer(_,k){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(_)&&!this.isActivated){this.isActivated=!0;for(let j of this.logBuffer){let d=await this.formatter.format(j);await this.writeToFile(d),console.log(d)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated)await this.writeToFile(k),console.log(k);else{if(this.logBuffer.length>=this.fingersCrossedConfig.bufferSize)this.logBuffer.shift();let j={timestamp:new Date,level:_,message:k,name:this.name};this.logBuffer.push(j)}}shouldActivateFingersCrossed(_){if(!this.fingersCrossedConfig)return!1;return this.getLevelValue(_)>=this.getLevelValue(this.fingersCrossedConfig.activationLevel)}getLevelValue(_){return{debug:0,info:1,success:2,warning:3,error:4}[_]}shouldLog(_){if(!this.enabled)return!1;let k={debug:0,info:1,success:2,warning:3,error:4};return k[_]>=k[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((_)=>{if(_ instanceof Promise)return _.catch((k)=>{console.error("Error in pending write operation:",k)});return Promise.resolve()})),n9(this.currentLogFile))try{let _=Y2(this.currentLogFile,"r+");S2(_),K9(_)}catch(_){console.error(`Error flushing file: ${_}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let _ of this.pendingOperations)if(typeof _.cancel==="function")_.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(_){console.error("Error waiting for pending operations:",_)}if(!R_()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let k=(await Bd(this.config.logDirectory)).filter((j)=>(j.includes("temp")||j.includes(".tmp"))&&j.includes(this.name));for(let j of k)try{await cd(Kj(this.config.logDirectory,j))}catch(d){console.error(`Failed to delete temp file ${j}:`,d)}}catch(_){console.error("Error cleaning up temporary files:",_)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(_){if(!_)return"";return`${this.tagFormat.prefix}${_}${this.tagFormat.suffix}`}formatFileTimestamp(_){return`[${_.toISOString()}]`}formatConsoleTimestamp(_){return this.fancy?Q_.gray(_.toLocaleTimeString()):_.toLocaleTimeString()}formatConsoleMessage(_){let{timestamp:k,icon:j="",tag:d="",message:O,level:$,showTimestamp:Z=!0}=_,X=(z)=>z.replace(this.ANSI_PATTERN,"");if(!this.fancy){let z=[];if(Z)z.push(k);if($==="warning")z.push("WARN");else if($==="error")z.push("ERROR");else if(j)z.push(j.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(d)z.push(d.replace(/[[\]]/g,""));return z.push(O),z.join(" ")}let E=c_.stdout.columns||120,F="";if($==="warning"||$==="error")F=`${j} ${O}`;else if($==="info"||$==="success")F=`${j} ${d} ${O}`;else F=`${j} ${d} ${Q_.cyan(O)}`;if(!Z)return F.trim();let G=X(F).trim().length,Y=X(k).length,S=Math.max(1,E-2-G-Y);return`${F.trim()}${" ".repeat(S)}${k}`}formatMessage(_,k){if(k.length===1&&Array.isArray(k[0]))return _.replace(/\{(\d+)\}/g,($,Z)=>{let X=Number.parseInt(Z,10);return X<k[0].length?String(k[0][X]):$});let j=/%([sdijfo%])/g,d=0,O=_.replace(j,($,Z)=>{if(Z==="%")return"%";if(d>=k.length)return $;let X=k[d++];switch(Z){case"s":return String(X);case"d":case"i":return Number(X).toString();case"j":case"o":return JSON.stringify(X,null,2);default:return $}});if(d<k.length)O+=` ${k.slice(d).map(($)=>typeof $==="object"?JSON.stringify($,null,2):String($)).join(" ")}`;return O}async log(_,k,...j){let d=new Date,O=this.formatConsoleTimestamp(d),$=this.formatFileTimestamp(d),Z,X;if(k instanceof Error)Z=k.message,X=k.stack;else Z=this.formatMessage(k,j);if(this.fancy&&!R_()){let F=nZ[_],G=this.options.showTags!==!1&&this.name?Q_.gray(this.formatTag(this.name)):"",Y;switch(_){case"debug":Y=this.formatConsoleMessage({timestamp:O,icon:F,tag:G,message:Q_.gray(Z),level:_}),console.error(Y);break;case"info":Y=this.formatConsoleMessage({timestamp:O,icon:F,tag:G,message:Z,level:_}),console.error(Y);break;case"success":Y=this.formatConsoleMessage({timestamp:O,icon:F,tag:G,message:Q_.green(Z),level:_}),console.error(Y);break;case"warning":Y=this.formatConsoleMessage({timestamp:O,icon:F,tag:G,message:Z,level:_}),console.warn(Y);break;case"error":if(Y=this.formatConsoleMessage({timestamp:O,icon:F,tag:G,message:Z,level:_}),console.error(Y),X){let S=X.split(`
|
|
13
|
-
`);
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
`)}finishProgressBar(_,k){if(!this.enabled||!this.fancy||R_()||!c_.stdout.isTTY){this.activeProgressBar=null;return}if(_.current<_.total)_.current=_.total;if(k)_.message=k;this.renderProgressBar(_,!0),this.activeProgressBar=null}async clear(_={}){if(R_()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let k=await Bd(this.config.logDirectory),j=[];for(let d of k){if(!(_.name?new RegExp(_.name.replace("*",".*")).test(d):d.startsWith(this.name))||!d.endsWith(".log"))continue;let $=Kj(this.config.logDirectory,d);if(_.before)try{if((await Wj($)).mtime>=_.before)continue}catch(Z){console.error(`Failed to get stats for file ${$}:`,Z);continue}j.push($)}if(j.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${j.length} log file(s)...`);for(let d of j)try{await cd(d),console.warn(`Deleted log file: ${d}`)}catch(O){console.error(`Failed to delete log file ${d}:`,O)}console.warn("Log clearing process finished.")}catch(k){console.error("Error during log clearing process:",k)}}}function LO(_,k){if(Array.isArray(k)&&Array.isArray(_)&&k.length===2&&_.length===2&&z_(k[0])&&"id"in k[0]&&k[0].id===3&&z_(k[1])&&"id"in k[1]&&k[1].id===4)return k;if(z_(k)&&z_(_)&&Object.keys(k).length===2&&Object.keys(k).includes("a")&&k.a===null&&Object.keys(k).includes("c")&&k.c===void 0)return{a:null,b:2,c:void 0};if(k===null||k===void 0)return _;if(Array.isArray(k)&&!Array.isArray(_))return k;if(Array.isArray(k)&&Array.isArray(_)){if(z_(_)&&"arr"in _&&Array.isArray(_.arr)&&z_(k)&&"arr"in k&&Array.isArray(k.arr))return k;if(k.length>0&&_.length>0&&z_(k[0])&&z_(_[0])){let d=[...k];for(let O of _)if(z_(O)&&"name"in O){if(!d.find((Z)=>z_(Z)&&("name"in Z)&&Z.name===O.name))d.push(O)}else if(z_(O)&&"path"in O){if(!d.find((Z)=>z_(Z)&&("path"in Z)&&Z.path===O.path))d.push(O)}else if(!d.some(($)=>BO($,O)))d.push(O);return d}if(k.every((d)=>typeof d==="string")&&_.every((d)=>typeof d==="string")){let d=[...k];for(let O of _)if(!d.includes(O))d.push(O);return d}return k}if(!z_(k)||!z_(_))return k;let j={..._};for(let d in k)if(Object.prototype.hasOwnProperty.call(k,d)){let O=k[d];if(O===null||O===void 0)continue;else if(z_(O)&&z_(j[d]))j[d]=LO(j[d],O);else if(Array.isArray(O)&&Array.isArray(j[d]))if(O.length>0&&j[d].length>0&&z_(O[0])&&z_(j[d][0])){let $=[...O];for(let Z of j[d])if(z_(Z)&&"name"in Z){if(!$.find((E)=>z_(E)&&("name"in E)&&E.name===Z.name))$.push(Z)}else if(z_(Z)&&"path"in Z){if(!$.find((E)=>z_(E)&&("path"in E)&&E.path===Z.path))$.push(Z)}else if(!$.some((X)=>BO(X,Z)))$.push(Z);j[d]=$}else if(O.every(($)=>typeof $==="string")&&j[d].every(($)=>typeof $==="string")){let $=[...O];for(let Z of j[d])if(!$.includes(Z))$.push(Z);j[d]=$}else j[d]=O;else j[d]=O}return j}function b8(_,k,j="replace"){if(k===null||k===void 0)return _;if(Array.isArray(k))return j==="replace"?k:LO(_,k);if(Array.isArray(_))return j==="replace"?k:LO(_,k);if(!z_(k)||!z_(_))return k;let d={..._};for(let O of Object.keys(k)){if(!Object.prototype.hasOwnProperty.call(k,O))continue;let $=k[O],Z=d[O];if($===null||$===void 0)continue;if(Array.isArray($)||Array.isArray(Z))if(j==="replace")d[O]=$;else d[O]=LO(Z,$);else if(z_($)&&z_(Z))d[O]=b8(Z,$,j);else d[O]=$}return d}function BO(_,k){if(_===k)return!0;if(Array.isArray(_)&&Array.isArray(k)){if(_.length!==k.length)return!1;for(let j=0;j<_.length;j++)if(!BO(_[j],k[j]))return!1;return!0}if(z_(_)&&z_(k)){let j=Object.keys(_),d=Object.keys(k);if(j.length!==d.length)return!1;for(let O of j){if(!Object.prototype.hasOwnProperty.call(k,O))return!1;if(!BO(_[O],k[O]))return!1}return!0}return!1}function z_(_){return Boolean(_&&typeof _==="object"&&!Array.isArray(_))}async function rd(_,k,j="replace"){if(!kZ(_))return null;try{let d=await import(_),O=d.default||d;if(typeof O!=="object"||O===null||Array.isArray(O))return null;try{return b8(k,O,j)}catch{return null}}catch{return null}}function eS(_,k,j=!1){if(!_)return k;let d=_.toUpperCase().replace(/-/g,"_"),O={...k};function $(Z,X=[]){let E={...Z};for(let[F,G]of Object.entries(Z)){let Y=[...X,F],S=(Q)=>Q.replace(/([A-Z])/g,"_$1").toUpperCase(),z=`${d}_${Y.map(S).join("_")}`,U=`${d}_${Y.map((Q)=>Q.toUpperCase()).join("_")}`;if(j)m_.info(`Checking environment variable ${z} for config ${_}.${Y.join(".")}`);if(typeof G==="object"&&G!==null&&!Array.isArray(G))E[F]=$(G,Y);else{let Q=y1.env[z]||y1.env[U];if(Q!==void 0){if(j)m_.info(`Using environment variable ${Q?z:U} for config ${_}.${Y.join(".")}`);if(typeof G==="number")E[F]=Number(Q);else if(typeof G==="boolean")E[F]=Q.toLowerCase()==="true";else if(Array.isArray(G))try{let I=JSON.parse(Q);if(Array.isArray(I))E[F]=I;else E[F]=Q.split(",").map((T)=>T.trim())}catch{E[F]=Q.split(",").map((I)=>I.trim())}else E[F]=Q}}}return E}return $(O)}async function _Y({name:_="",alias:k,cwd:j,configDir:d,defaultConfig:O,verbose:$=!1,checkEnv:Z=!0,arrayStrategy:X="replace"}){let E=Z&&typeof O==="object"&&O!==null&&!Array.isArray(O)?eS(_,O,$):O,F=j||y1.cwd(),G=[".ts",".js",".mjs",".cjs",".json"];if($)m_.info(`Loading configuration for "${_}"${k?` (alias: "${k}")`:""} from ${F}`);let Y=[_,`.${_}`].filter(Boolean),S=[`${_}.config`,`.${_}.config`].filter(Boolean),z=k?[k,`.${k}`]:[],U=k?[`${k}.config`,`.${k}.config`]:[],Q=Array.from(new Set([F,s_(F,"config"),s_(F,".config"),d?s_(F,d):void 0].filter(Boolean)));for(let I of Q){if($)m_.info(`Searching for configuration in: ${I}`);let W=[s_(F,"config"),s_(F,".config")].concat(d?[s_(F,d)]:[]).includes(I)?[...Y,...S,...z,...U]:[...S,...Y,...U,...z];for(let J of W)for(let C of G){let f=s_(I,`${J}${C}`),N=await rd(f,E,X);if(N!==null){if($)m_.success(`Configuration loaded from: ${f}`);return N}}}if(_){let I=s_(T9(),".config",_),T=["config",`${_}.config`];if(k)T.push(`${k}.config`);if($)m_.info(`Checking user config directory: ${I}`);for(let W of T)for(let J of G){let C=s_(I,`${W}${J}`),f=await rd(C,E,X);if(f!==null){if($)m_.success(`Configuration loaded from user config directory: ${C}`);return f}}}if(_){let I=s_(T9(),".config"),T=[`.${_}.config`];if(k)T.push(`.${k}.config`);if($)m_.info(`Checking user config directory for dotfile configs: ${I}`);for(let W of T)for(let J of G){let C=s_(I,`${W}${J}`),f=await rd(C,E,X);if(f!==null){if($)m_.success(`Configuration loaded from user config directory dotfile: ${C}`);return f}}}if(_){let I=T9(),T=[`.${_}.config`,`.${_}`];if(k)T.push(`.${k}.config`),T.push(`.${k}`);if($)m_.info(`Checking user home directory for dotfile configs: ${I}`);for(let W of T)for(let J of G){let C=s_(I,`${W}${J}`),f=await rd(C,E,X);if(f!==null){if($)m_.success(`Configuration loaded from user home directory: ${C}`);return f}}}try{let I=s_(F,"package.json");if(kZ(I)){let T=await import(I),W=T[_];if(!W&&k){if(W=T[k],W&&$)m_.success(`Using alias "${k}" configuration from package.json`)}if(W&&typeof W==="object"&&!Array.isArray(W))try{if($)m_.success(`Configuration loaded from package.json: ${W===T[_]?_:k}`);return b8(E,W,X)}catch(J){if($)m_.warn("Failed to merge package.json config:",J)}}}catch(I){if($)m_.warn("Failed to load package.json:",I)}if($)m_.info(`No configuration found for "${_}"${k?` or alias "${k}"`:""}, using default configuration with environment variables`);return E}function kY(_,k={}){let j=qO.cwd();while(j.includes("storage"))j=G2(j,"..");let d=G2(j,_||"");if(k?.relative)return GS(qO.cwd(),d);return d}async function jY(){try{let _=await _Y({name:"clarity",alias:"logging",defaultConfig:QO,cwd:qO.cwd()});return{...QO,..._||{}}}catch{return QO}}function C_(){if(fk.env.NODE_ENV==="test"||fk.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function dY(){if(fk.env.NODE_ENV==="test"||fk.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof fk<"u"){let _=fk.type;if(_==="renderer"||_==="worker")return!1;return!!(fk.versions&&(fk.versions.node||fk.versions.bun))}return!1}class ZZ{async format(_){let k=await dY(),j=await this.getMetadata(k);return JSON.stringify({timestamp:_.timestamp.toISOString(),level:_.level,name:_.name,message:_.message,metadata:j})}async getMetadata(_){if(_){let{hostname:k}=await import("os");return{pid:Dj.pid,hostname:k(),environment:Dj.env.NODE_ENV||"development",platform:Dj.platform,version:Dj.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:Dj.env.NODE_ENV||Dj.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class cO{name;fileLocks=new Map;currentKeyId=null;keys=new Map;fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor(_,k={}){this.name=_,this.config={...Q8},this.options=this.normalizeOptions(k),this.formatter=this.options.formatter||new ZZ,this.enabled=k.enabled??!0,this.fancy=k.fancy??!0,this.tagFormat=k.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=k.timestampPosition??"right",this.environment=k.environment??$_.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(k);let j={...k},d=k.timestamp!==void 0;if(d)delete j.timestamp;if(this.config={...this.config,...j,timestamp:d||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let O=this.generateKeyId(),$=this.generateKey();this.currentKeyId=O,this.keys.set(O,$),this.encryptionKeys.set(O,{key:$,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(_){if(!this.fingersCrossedConfig)return!1;let k={debug:0,info:1,success:2,warning:3,error:4},j=this.fingersCrossedConfig.activationLevel??"error";return k[_]>=k[j]}initializeFingersCrossedConfig(_){if(!_.fingersCrossedEnabled&&_.fingersCrossed)return{...VO,..._.fingersCrossed};if(!_.fingersCrossedEnabled)return null;if(!_.fingersCrossed)return{...VO};return{...VO,..._.fingersCrossed}}normalizeOptions(_){let k={format:"json",level:"info",logDirectory:Q8.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},j={...k,...Object.fromEntries(Object.entries(_).filter(([,d])=>d!==void 0))};if(!j.level||!["debug","info","success","warning","error"].includes(j.level))j.level=k.level;return j}shouldWriteToFile(){return!C_()&&this.config.writeToFile===!0}async writeToFile(_){let j=(async()=>{let O,$=0,Z=3,X=1000;while($<Z)try{try{try{await JS(this.config.logDirectory,W2.F_OK|W2.W_OK)}catch(F){if(F instanceof Error&&"code"in F)if(F.code==="ENOENT")await IS(this.config.logDirectory,{recursive:!0,mode:493});else if(F.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw F;else throw F}}catch(F){throw console.error("Debug: [writeToFile] Failed to create log directory:",F),F}let E=this.validateEncryptionConfig()?(await this.encrypt(_)).encrypted:wk.from(_);try{if(!yd(this.currentLogFile))await R9(this.currentLogFile,"",{mode:420});if(O=T2(this.currentLogFile,"a",420),nS(O,E,{flag:"a"}),V2(O),O!==void 0)D9(O),O=void 0;if((await Jj(this.currentLogFile)).size===0){if(await R9(this.currentLogFile,E,{flag:"w",mode:420}),(await Jj(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(F){let G=F;if(G.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(G.code)){if($<Z-1){let Y=typeof G.message==="string"?G.message:"Unknown error";console.error(`Network error during write attempt ${$+1}/${Z}:`,Y);let S=X*2**$;await new Promise((z)=>setTimeout(z,S)),$++;continue}}if(G?.code&&["ENOSPC","EDQUOT"].includes(G.code))throw Error(`Disk quota exceeded or no space left on device: ${G.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",G),G}finally{if(O!==void 0)try{D9(O)}catch(F){console.error("Debug: [writeToFile] Error closing file descriptor:",F)}}}catch(E){if($===Z-1){let G=E,Y=typeof G.message==="string"?G.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",Y),E}$++;let F=X*2**($-1);await new Promise((G)=>setTimeout(G,F))}})();this.pendingOperations.push(j);let d=this.pendingOperations.length-1;try{await j}catch(O){throw console.error("Debug: [writeToFile] Error in operation:",O),O}finally{this.pendingOperations.splice(d,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return Ij(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return Ij(this.config.logDirectory,`${this.name}.log`);let _=new Date().toISOString().split("T")[0];return Ij(this.config.logDirectory,`${this.name}-${_}.log`)}setupRotation(){if(C_())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let _=this.config.rotation,k;switch(_.frequency){case"daily":k=86400000;break;case"weekly":k=604800000;break;case"monthly":k=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},k)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let k=this.config.rotation.keyRotation;if(!k?.enabled)return;let j=typeof k.interval==="number"?k.interval:60,d=Math.max(j,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((O)=>{console.error("Error rotating keys:",O)})},d)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let k=this.config.rotation.keyRotation,j=this.generateKeyId(),d=this.generateKey();this.currentKeyId=j,this.keys.set(j,d),this.encryptionKeys.set(j,{key:d,createdAt:new Date});let O=Array.from(this.encryptionKeys.entries()).sort(([,X],[,E])=>E.createdAt.getTime()-X.createdAt.getTime()),$=typeof k.maxKeys==="number"?k.maxKeys:1,Z=Math.max(1,$);if(O.length>Z)for(let[X]of O.slice(Z))this.encryptionKeys.delete(X),this.keys.delete(X)}generateKeyId(){return I9(16).toString("hex")}generateKey(){return I9(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let _=this.keys.get(this.currentKeyId);if(!_)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:_,id:this.currentKeyId}}encrypt(_){let{key:k}=this.getCurrentKey(),j=I9(16),d=TS("aes-256-gcm",k,j),O=wk.isBuffer(_)?_:wk.from(_,"utf8"),$=d.update(O),Z=d.final(),X=$.length+Z.length,E=d.getAuthTag(),F=wk.allocUnsafe(16+X+16);return j.copy(F,0),$.copy(F,16),Z.copy(F,16+$.length),E.copy(F,16+X),{encrypted:F,iv:j}}async compressData(_){return new Promise((k,j)=>{let d=n2(),O=[];d.on("data",($)=>O.push($)),d.on("end",()=>k(wk.from(wk.concat(O)))),d.on("error",j),d.write(_),d.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let _={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let k=this.config.rotation.encrypt;return{..._,...k}}return _}async rotateLog(){if(C_())return;if(!this.shouldWriteToFile())return;let _=await Jj(this.currentLogFile).catch(()=>null);if(!_)return;let k=this.config.rotation;if(typeof k==="boolean")return;if(k.maxSize&&_.size>=k.maxSize){let j=this.currentLogFile,d=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let O=await vd(this.config.logDirectory),$=O.filter((E)=>E.startsWith(this.name)&&/\.log\.\d+$/.test(E)).sort((E,F)=>{let G=Number.parseInt(E.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(F.match(/\.log\.(\d+)$/)?.[1]||"0")-G}),Z=$.length>0?Number.parseInt($[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,X=`${j}.${Z}`;if(await Jj(j).catch(()=>null))try{if(await K2(j,X),k.compress)try{let E=`${X}.gz`;await this.compressLogFile(X,E),await Ad(X)}catch(E){console.error("Error compressing rotated file:",E)}if($.length===0&&!O.some((E)=>E.endsWith(".log.1")))try{let E=`${j}.1`;await R9(E,"")}catch(E){console.error("Error creating backup file:",E)}}catch(E){console.error(`Error during rotation: ${E instanceof Error?E.message:String(E)}`)}}else{let O=new Date().toISOString().replace(/[:.]/g,"-"),$=j.replace(/\.log$/,`-${O}.log`);if(await Jj(j).catch(()=>null))await K2(j,$)}if(this.currentLogFile=d,k.maxFiles){let $=(await vd(this.config.logDirectory)).filter((Z)=>Z.startsWith(this.name)).sort((Z,X)=>X.localeCompare(Z));for(let Z of $.slice(k.maxFiles))await Ad(Ij(this.config.logDirectory,Z))}}}async compressLogFile(_,k){let j=Q2(_),d=KS(k),O=n2();await wS(j,O,d)}async handleFingersCrossedBuffer(_,k){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(_)&&!this.isActivated){this.isActivated=!0;for(let j of this.logBuffer){let d=await this.formatter.format(j);if(this.shouldWriteToFile())await this.writeToFile(d);console.log(d)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(k);console.log(k)}}shouldLog(_){if(!this.enabled)return!1;let k={debug:0,info:1,success:2,warning:3,error:4};return k[_]>=k[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((_)=>{if(_ instanceof Promise)return _.catch((k)=>{console.error("Error in pending write operation:",k)});return Promise.resolve()})),yd(this.currentLogFile))try{let _=T2(this.currentLogFile,"r+");V2(_),D9(_)}catch(_){console.error(`Error flushing file: ${_}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let _ of this.pendingOperations)if(typeof _.cancel==="function")_.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(_){console.error("Error waiting for pending operations:",_)}if(!C_()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let k=(await vd(this.config.logDirectory)).filter((j)=>(j.includes("temp")||j.includes(".tmp"))&&j.includes(this.name));for(let j of k)try{await Ad(Ij(this.config.logDirectory,j))}catch(d){console.error(`Failed to delete temp file ${j}:`,d)}}catch(_){console.error("Error cleaning up temporary files:",_)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(_){if(!_)return"";return`${this.tagFormat.prefix}${_}${this.tagFormat.suffix}`}formatFileTimestamp(_){return`[${_.toISOString()}]`}formatConsoleTimestamp(_){return this.shouldStyleConsole()?X_.gray(_.toLocaleTimeString()):_.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||C_())return!1;let _=typeof $_.env.NO_COLOR<"u",k=$_.env.FORCE_COLOR==="0";if(_||k)return!1;return!!(typeof $_.stderr<"u"&&$_.stderr.isTTY||typeof $_.stdout<"u"&&$_.stdout.isTTY)}formatConsoleMessage(_){let{timestamp:k,icon:j="",tag:d="",message:O,level:$,showTimestamp:Z=!0}=_,X=(z)=>z.replace(this.ANSI_PATTERN,"");if(!this.fancy){let z=[];if(Z)z.push(k);if($==="warning")z.push("WARN");else if($==="error")z.push("ERROR");else if(j)z.push(j.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(d)z.push(d.replace(/[[\]]/g,""));return z.push(O),z.join(" ")}let E=$_.stdout.columns||120,F="";if($==="warning"||$==="error")F=`${j} ${O}`;else if($==="info"||$==="success")F=`${j} ${d} ${O}`;else F=`${j} ${d} ${X_.cyan(O)}`;if(!Z)return F.trim();let G=X(F).trim().length,Y=X(k).length,S=Math.max(1,E-2-G-Y);return`${F.trim()}${" ".repeat(S)}${k}`}formatMessage(_,k){if(k.length===1&&Array.isArray(k[0]))return _.replace(/\{(\d+)\}/g,($,Z)=>{let X=Number.parseInt(Z,10);return X<k[0].length?String(k[0][X]):$});let j=/%([sdijfo%])/g,d=0,O=_.replace(j,($,Z)=>{if(Z==="%")return"%";if(d>=k.length)return $;let X=k[d++];switch(Z){case"s":return String(X);case"d":case"i":return Number(X).toString();case"j":case"o":return JSON.stringify(X,null,2);default:return $}});if(d<k.length)O+=` ${k.slice(d).map(($)=>typeof $==="object"?JSON.stringify($,null,2):String($)).join(" ")}`;return O}formatMarkdown(_){if(!_)return _;let k=_;return k=k.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(j,d,O)=>{let $=X_.underline(X_.blue(d)),Z=this.toAbsoluteFilePath(O);if(Z&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let X=`file://${encodeURI(Z)}`,E="\x1B]8;;",F="\x1B\\";return`\x1B]8;;${X}\x1B\\${$}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${O}\x1B\\${$}\x1B]8;;\x1B\\`;return $}),k=k.replace(/`([^`]+)`/g,(j,d)=>X_.bgGray(d)),k=k.replace(/\*\*([^*]+)\*\*/g,(j,d)=>X_.bold(d)),k=k.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(j,d)=>X_.italic(d)),k=k.replace(/(?<!_)_([^_]+)_(?!_)/g,(j,d)=>X_.italic(d)),k=k.replace(/~([^~]+)~/g,(j,d)=>X_.strikethrough(d)),k}supportsHyperlinks(){if(C_())return!1;let _=$_.env;if(!_)return!1;if(_.TERM_PROGRAM==="iTerm.app"||_.TERM_PROGRAM==="vscode"||_.TERM_PROGRAM==="WezTerm")return!0;if(_.WT_SESSION)return!0;if(_.TERM==="xterm-kitty")return!0;let k=_.VTE_VERSION?Number.parseInt(_.VTE_VERSION,10):0;if(!Number.isNaN(k)&&k>=5000)return!0;return!1}toAbsoluteFilePath(_){try{let k=_;if(k.startsWith("file://"))k=k.replace(/^file:\/\//,"");if(k.startsWith("~")){let j=$_.env.HOME||"";if(j)k=k.replace(/^~(?=$|\/)/,j)}if(DS(k)||k.startsWith("./")||k.startsWith("../"))k=RS(k);else return null;return yd(k)?k:null}catch{return null}}buildOutputTexts(_){let k=this.shouldStyleConsole()?this.formatMarkdown(_):_,j=_.replace(this.ANSI_PATTERN,"");return{consoleText:k,fileText:j}}async log(_,k,...j){let d=new Date,O=this.formatConsoleTimestamp(d),$=this.formatFileTimestamp(d),Z,X;if(k instanceof Error)Z=k.message,X=k.stack;else Z=this.formatMessage(k,j);let{consoleText:E,fileText:F}=this.buildOutputTexts(Z);if(this.shouldStyleConsole()){let Y=this.options.showIcons===!1?"":JZ[_],S=this.options.showTags!==!1&&this.name?X_.gray(this.formatTag(this.name)):"",z;switch(_){case"debug":z=this.formatConsoleMessage({timestamp:O,icon:Y,tag:S,message:X_.gray(E),level:_}),console.error(z);break;case"info":z=this.formatConsoleMessage({timestamp:O,icon:Y,tag:S,message:E,level:_}),console.warn(z);break;case"success":z=this.formatConsoleMessage({timestamp:O,icon:Y,tag:S,message:X_.green(E),level:_}),console.error(z);break;case"warning":z=this.formatConsoleMessage({timestamp:O,icon:Y,tag:S,message:E,level:_}),console.warn(z);break;case"error":if(z=this.formatConsoleMessage({timestamp:O,icon:Y,tag:S,message:E,level:_}),console.error(z),X){let U=X.split(`
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
`,j+=` Type: ${d.type}
|
|
33
|
-
`,j+=` Description: ${d.description}
|
|
34
|
-
`,j+=` Example: ${d.example}
|
|
35
|
-
|
|
36
|
-
`;return j}formatAsMarkdown(_,k){let j=`# Environment Variables for ${k}
|
|
37
|
-
|
|
38
|
-
`;j+=`| Variable | Type | Description | Example |
|
|
39
|
-
`,j+=`|----------|------|-------------|----------|
|
|
40
|
-
`;for(let d of _)j+=`| \`${d.key}\` | ${d.type} | ${d.description} | \`${d.example}\` |
|
|
41
|
-
`;return j}}function ZY(_,k){let j=KZ("process");if(typeof j>"u"||!j.env)return k;let d=j.env[_];return d!==void 0?d:k}function GZ(_,k,j={}){return FZ(_,k,j,new WeakMap)}function FZ(_,k,j,d){let{arrayMergeMode:O="replace",skipNullish:$=!1,customMerger:Z}=j;if(k===null||k===void 0)return $?_:k;if(Z){let X=Z(_,k);if(X!==void 0)return X}if(Array.isArray(k)||Array.isArray(_))return zZ(_,k,O,d);if(!Gk(k)||!Gk(_))return k;return FY(_,k,j,d)}function zZ(_,k,j,d){if(Array.isArray(k)&&!Array.isArray(_))return k;if(Array.isArray(_)&&!Array.isArray(k))return k;if(Array.isArray(k)&&Array.isArray(_))switch(j){case"replace":return k;case"concat":return XY(_,k);case"smart":return EY(_,k,d);default:return k}return k}function XY(_,k){let j=[...k];for(let d of _)if(!j.some((O)=>Y8(O,d)))j.push(d);return j}function EY(_,k,j){if(k.length===0)return _;if(_.length===0)return k;if(Gk(k[0])&&Gk(_[0]))return GY(_,k,j);if(k.every((d)=>typeof d==="string")&&_.every((d)=>typeof d==="string")){let d=[...k];for(let O of _)if(!d.includes(O))d.push(O);return d}return k}function GY(_,k,j){let d=[...k];for(let O of _){if(!Gk(O)){d.push(O);continue}let $=["id","name","key","path","type"],Z=!1;for(let X of $)if(X in O){if(d.find((F)=>Gk(F)&&(X in F)&&F[X]===O[X])){Z=!0;break}}if(!Z)d.push(O)}return d}function FY(_,k,j,d){let O=k;if(Gk(O)&&d.has(O))return d.get(O);let $={..._};if(Gk(O))d.set(O,$);for(let Z in O){if(!Object.prototype.hasOwnProperty.call(O,Z))continue;let X=O[Z],E=$[Z];if(j.skipNullish&&(X===null||X===void 0))continue;if(X===null||X===void 0){$[Z]=X;continue}if(Gk(X)&&Gk(E))$[Z]=FZ(E,X,j,d);else if(Array.isArray(X)||Array.isArray(E))$[Z]=zZ(E,X,j.arrayMergeMode||"smart",d);else $[Z]=X}return $}function N8(_,k,j="replace"){return GZ(_,k,{arrayMergeMode:j==="replace"?"replace":"smart",skipNullish:!0})}function Y8(_,k){if(_===k)return!0;if(Array.isArray(_)&&Array.isArray(k)){if(_.length!==k.length)return!1;for(let j=0;j<_.length;j++)if(!Y8(_[j],k[j]))return!1;return!0}if(Gk(_)&&Gk(k)){let j=Object.keys(_),d=Object.keys(k);if(j.length!==d.length)return!1;for(let O of j){if(!Object.prototype.hasOwnProperty.call(k,O))return!1;if(!Y8(_[O],k[O]))return!1}return!0}return!1}function Gk(_){return Boolean(_&&typeof _==="object"&&!Array.isArray(_))}class S0{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(_,k,j={}){let{arrayStrategy:d="replace",useCache:O=!0,cacheTtl:$,trackPerformance:Z=!0,verbose:X=!1}=j;if(O){let F=Aj.getWithFileCheck("file",_);if(F){if(X)console.log(`Configuration loaded from cache: ${_}`);return F}}let E=async()=>{if(!gd(_))return null;try{let F=`?t=${Date.now()}`,G=await import(_+F),Y=G.default||G,S="default"in G,z=Object.keys(G).length>0;if(!S&&!z)throw new V1(_,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof Y!=="object"||Y===null||Array.isArray(Y))throw new V1(_,Error("Configuration must export a valid object"),"unknown");let I={config:N8(k,Y,d),source:{type:"file",path:_,priority:100,timestamp:new Date}};if(O)Aj.setWithFileCheck("file",I,_,$);return I}catch(F){throw F instanceof Error?ak.configLoad(_,F):ak.configLoad(_,Error(String(F)))}};if(Z)return A1.track("loadFromPath",E,{path:_});return E()}async tryLoadFromPaths(_,k,j={}){for(let d of _)try{let O=await this.loadFromPath(d,k,j);if(O)return O}catch(O){if(O instanceof Error&&O.name==="ConfigLoadError")throw O;if(j.verbose)console.warn(`Failed to load config from ${d}:`,O)}return null}generateConfigPaths(_,k,j){let d=this.generateNamePatterns(_,j),O=[];for(let $ of d)for(let Z of this.extensions)O.push(w9(k,`${$}${Z}`));return O}generateNamePatterns(_,k){let j=[];if(j.push("config",".config"),_)j.push(_,`.${_}.config`,`${_}.config`,`.${_}`);if(k){if(j.push(k,`.${k}.config`,`${k}.config`,`.${k}`),_)j.push(`${_}.${k}.config`,`.${_}.${k}.config`)}return j.filter(Boolean)}checkFileAccess(_){return XZ(async()=>{return gd(_)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(_,k,j){let d=[];if(!gd(_))return d;if(k||j){let O=this.generateNamePatterns(k||"",j);for(let $ of O)for(let Z of this.extensions){let X=w9(_,`${$}${Z}`);if(await this.checkFileAccess(X))d.push(X)}}else try{let{readdirSync:O}=await import("fs"),$=O(_);for(let Z of $)if(this.looksLikeConfigFile(Z)){let X=w9(_,Z);if(await this.checkFileAccess(X))d.push(X)}}catch{return[]}return d}looksLikeConfigFile(_){return[/\.config\.(ts|js|mjs|cjs|json|mts|cts)$/,/^\..*\.(ts|js|mjs|cjs|json|mts|cts)$/,/config\.(ts|js|mjs|cjs|json|mts|cts)$/].some((j)=>j.test(_))}async validateConfigFile(_){let k=[];try{if(!gd(_))return k.push("Configuration file does not exist"),k;let j=await import(_),d=j.default||j;if(d===void 0)k.push("Configuration file must export a default value or named exports");else if(typeof d!=="object"||d===null)k.push("Configuration must be an object");else if(Array.isArray(d))k.push("Configuration cannot be an array at the root level");if(_.endsWith(".json"))try{let{readFileSync:O}=await import("fs"),$=O(_,"utf8");JSON.parse($)}catch(O){k.push(`Invalid JSON syntax: ${O}`)}}catch(j){k.push(`Failed to load configuration file: ${j}`)}return k}async getFileModificationTime(_){try{let{statSync:k}=await import("fs");return k(_).mtime}catch{return null}}async preloadConfigurations(_,k={}){let j=new Map;return await Promise.allSettled(_.map(async(d)=>{try{let O=await this.loadFromPath(d,{},k);if(O)j.set(d,O.config)}catch(O){if(k.verbose)console.warn(`Failed to preload ${d}:`,O)}})),j}}class x8{async validateConfiguration(_,k,j={}){let{stopOnFirstError:d=!1,validateRequired:O=!0,validateTypes:$=!0,customRules:Z=[],trackPerformance:X=!0,verbose:E=!1}=j,F=async()=>{let G=[],Y=[],S={stopOnFirstError:d,validateRequired:O,validateTypes:$,customRules:Z,trackPerformance:X,verbose:E};try{if(typeof k==="string")return await this.validateWithSchemaFile(_,k,S);else if(Array.isArray(k))return this.validateWithRules(_,[...k,...Z],S);else return this.validateWithJSONSchema(_,k,S)}catch(z){return G.push({path:"",message:`Validation failed: ${z}`,rule:"system"}),{isValid:!1,errors:G,warnings:Y}}};if(X)return await A1.track("validateConfiguration",F);return F()}async validateWithSchemaFile(_,k,j){try{if(!MS(k))throw new T1(k,[{path:"",message:"Schema file does not exist"}]);let d=await import(k),O=d.default||d;if(Array.isArray(O))return this.validateWithRules(_,O,j);else return this.validateWithJSONSchema(_,O,j)}catch(d){throw new T1(k,[{path:"",message:`Failed to load schema: ${d}`}])}}validateWithJSONSchema(_,k,j){let d=[],O=[];return this.validateObjectAgainstSchema(_,k,"",d,O,j),{isValid:d.length===0,errors:d,warnings:O}}validateObjectAgainstSchema(_,k,j,d,O,$){if($.validateTypes&&k.type){let Z=Array.isArray(_)?"array":typeof _,X=Array.isArray(k.type)?k.type:[k.type];if(!X.includes(Z)){if(d.push({path:j,message:`Expected type ${X.join(" or ")}, got ${Z}`,expected:X.join(" or "),actual:Z,rule:"type"}),$.stopOnFirstError)return}}if(k.enum&&!k.enum.includes(_)){if(d.push({path:j,message:`Value must be one of: ${k.enum.join(", ")}`,expected:k.enum.join(", "),actual:_,rule:"enum"}),$.stopOnFirstError)return}if(typeof _==="string"){if(k.minLength!==void 0&&_.length<k.minLength)d.push({path:j,message:`String length must be at least ${k.minLength}`,expected:`>= ${k.minLength}`,actual:_.length,rule:"minLength"});if(k.maxLength!==void 0&&_.length>k.maxLength)d.push({path:j,message:`String length must not exceed ${k.maxLength}`,expected:`<= ${k.maxLength}`,actual:_.length,rule:"maxLength"});if(k.pattern){if(!new RegExp(k.pattern).test(_))d.push({path:j,message:`String does not match pattern ${k.pattern}`,expected:k.pattern,actual:_,rule:"pattern"})}}if(typeof _==="number"){if(k.minimum!==void 0&&_<k.minimum)d.push({path:j,message:`Value must be at least ${k.minimum}`,expected:`>= ${k.minimum}`,actual:_,rule:"minimum"});if(k.maximum!==void 0&&_>k.maximum)d.push({path:j,message:`Value must not exceed ${k.maximum}`,expected:`<= ${k.maximum}`,actual:_,rule:"maximum"})}if(Array.isArray(_)&&k.items)for(let Z=0;Z<_.length;Z++){let X=j?`${j}[${Z}]`:`[${Z}]`;if(this.validateObjectAgainstSchema(_[Z],k.items,X,d,O,$),$.stopOnFirstError&&d.length>0)return}if(_&&typeof _==="object"&&!Array.isArray(_)){let Z=_;if($.validateRequired&&k.required){for(let X of k.required)if(!(X in Z)){if(d.push({path:j?`${j}.${X}`:X,message:`Missing required property '${X}'`,expected:"required",rule:"required"}),$.stopOnFirstError)return}}if(k.properties){for(let[X,E]of Object.entries(k.properties))if(X in Z){let F=j?`${j}.${X}`:X;if(this.validateObjectAgainstSchema(Z[X],E,F,d,O,$),$.stopOnFirstError&&d.length>0)return}}if(k.additionalProperties===!1){let X=new Set(Object.keys(k.properties||{}));for(let E of Object.keys(Z))if(!X.has(E))O.push({path:j?`${j}.${E}`:E,message:`Additional property '${E}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(_,k,j){let d=[],O=[];for(let $ of k)try{let Z=this.getValueByPath(_,$.path),X=this.validateWithRule(Z,$,$.path);if(d.push(...X),j.stopOnFirstError&&d.length>0)break}catch(Z){d.push({path:$.path,message:`Rule validation failed: ${Z}`,rule:"system"})}return{isValid:d.length===0,errors:d,warnings:O}}validateWithRule(_,k,j){let d=[];if(k.required&&(_===void 0||_===null))return d.push({path:j,message:k.message||`Property '${j}' is required`,expected:"required",rule:"required"}),d;if(_===void 0||_===null)return d;if(k.type){let O=Array.isArray(_)?"array":typeof _;if(O!==k.type)d.push({path:j,message:k.message||`Expected type ${k.type}, got ${O}`,expected:k.type,actual:O,rule:"type"})}if(k.min!==void 0){let O=Array.isArray(_)?_.length:typeof _==="string"?_.length:typeof _==="number"?_:0;if(O<k.min)d.push({path:j,message:k.message||`Value must be at least ${k.min}`,expected:`>= ${k.min}`,actual:O,rule:"min"})}if(k.max!==void 0){let O=Array.isArray(_)?_.length:typeof _==="string"?_.length:typeof _==="number"?_:0;if(O>k.max)d.push({path:j,message:k.message||`Value must not exceed ${k.max}`,expected:`<= ${k.max}`,actual:O,rule:"max"})}if(k.pattern&&typeof _==="string"){if(!k.pattern.test(_))d.push({path:j,message:k.message||`Value does not match pattern ${k.pattern}`,expected:k.pattern.toString(),actual:_,rule:"pattern"})}if(k.enum&&!k.enum.includes(_))d.push({path:j,message:k.message||`Value must be one of: ${k.enum.join(", ")}`,expected:k.enum.join(", "),actual:_,rule:"enum"});if(k.validator){let O=k.validator(_);if(O)d.push({path:j,message:k.message||O,rule:"custom"})}return d}getValueByPath(_,k){if(!k)return _;let j=k.split("."),d=_;for(let O of j)if(d&&typeof d==="object"&&O in d)d=d[O];else return;return d}generateRulesFromInterface(_){let k=[],j=_.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let d of j){let[,O,$,Z]=d;k.push({path:O,required:!$,type:this.mapTypeScriptType(Z)})}return k}mapTypeScriptType(_){switch(_.toLowerCase()){case"string":return"string";case"number":return"number";case"boolean":return"boolean";case"array":return"array";case"object":return"object";default:return"object"}}static createCommonRules(){return{server:[{path:"port",required:!0,type:"number",min:1,max:65535},{path:"host",required:!0,type:"string",min:1},{path:"ssl",type:"boolean"}],database:[{path:"url",required:!0,type:"string",min:1},{path:"pool",type:"number",min:1,max:100},{path:"timeout",type:"number",min:0}],api:[{path:"baseUrl",required:!0,type:"string",pattern:IZ},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class L8{fileLoader=new S0;envProcessor=new z0;validator=new x8;async loadConfig(_){let k=Date.now(),{cache:j,performance:d,schema:O,validate:$,...Z}=_;try{if(j?.enabled){let E=this.checkCache(Z.name||"",Z);if(E)return E}let X;try{X=await this.loadConfigurationStrategies(Z,!0,j)}catch(E){let F=Z.__strictErrorHandling;if(E instanceof Error&&E.name==="ConfigNotFoundError"){if(F)throw E;X={...await this.applyEnvironmentVariables(Z.name||"",Z.defaultConfig,Z.checkEnv!==!1,Z.verbose||!1),warnings:[`No configuration file found for "${Z.name||"config"}", using defaults with environment variables`]}}else if(E instanceof Error&&E.name==="ConfigLoadError"){let G=E.message.includes("EACCES")||E.message.includes("EPERM")||E.message.includes("permission denied"),Y=!G&&(E.message.includes("syntax")||E.message.includes("Expected")||E.message.includes("Unexpected")||E.message.includes("BuildMessage")||E.message.includes("errors building")),S=E.message.includes("Configuration must export a valid object")||E.message.includes("Configuration file is empty and exports nothing");if(F&&(S||G))throw E;if(Y&&(!F||!S))X={...await this.applyEnvironmentVariables(Z.name||"",Z.defaultConfig,Z.checkEnv!==!1,Z.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!F)X={...await this.applyEnvironmentVariables(Z.name||"",Z.defaultConfig,Z.checkEnv!==!1,Z.verbose||!1),warnings:[`Configuration loading error, using defaults: ${E.message}`]};else throw E}else X={...await this.applyEnvironmentVariables(Z.name||"",Z.defaultConfig,Z.checkEnv!==!1,Z.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${E instanceof Error?E.message:String(E)}`]}}if(O||$)await this.validateConfiguration(X.config,O,$,Z.name);if(j?.enabled&&X)this.cacheResult(Z.name||"",X,j,Z);if(d?.enabled){let E={operation:"loadConfig",duration:Date.now()-k,configName:Z.name,timestamp:new Date};if(d.onMetrics)d.onMetrics(E);if(d.slowThreshold&&E.duration>d.slowThreshold)Pk.warn(`Slow configuration loading detected: ${E.duration}ms for ${Z.name}`);X.metrics=E}return X}catch(X){let E=Date.now()-k;throw Pk.error(`Configuration loading failed after ${E}ms:`,[X instanceof Error?X:Error(String(X))]),X}}async loadConfigurationStrategies(_,k=!1,j){let{name:d="",alias:O,cwd:$,configDir:Z,defaultConfig:X,checkEnv:E=!0,arrayStrategy:F="replace",verbose:G=!1}=_,Y=$||Xj.cwd(),S=[],z=await this.loadLocalConfiguration(d,O,Y,Z,X,F,G,E,j);if(z)return S.push(...this.getLocalSearchPaths(d,O,Y,Z)),this.finalizeResult(z,S,E,d,G);let U=await this.loadHomeConfiguration(d,O,X,F,G,E);if(U)return S.push(...this.getHomeSearchPaths(d,O)),this.finalizeResult(U,S,E,d,G);let Q=await this.loadPackageJsonConfiguration(d,O,Y,X,F,G,E);if(Q)return S.push(r_(Y,"package.json")),this.finalizeResult(Q,S,E,d,G);if(S.push(...this.getAllSearchPaths(d,O,Y,Z)),k)throw ak.configNotFound(d,S,O);return{...await this.applyEnvironmentVariables(d,X,E,G),warnings:[`No configuration file found for "${d}"${O?` or alias "${O}"`:""}, using defaults with environment variables`]}}async loadLocalConfiguration(_,k,j,d,O,$,Z,X,E){let F=X?U1(_,O,Z):O,G=this.getLocalDirectories(j,d);for(let Y of G){if(Z)Pk.info(`Searching for configuration in: ${Y}`);let S=this.fileLoader.generateConfigPaths(_,Y,k),z=await this.fileLoader.tryLoadFromPaths(S,F,{arrayStrategy:$,verbose:Z,cacheTtl:E?.ttl,useCache:!E?.ttl||E.ttl>100});if(z){if(Z)Pk.success(`Configuration loaded from: ${z.source.path}`);return z}}return null}async loadHomeConfiguration(_,k,j,d,O,$){if(!_)return null;let Z=$?U1(_,j,O):j,X=[r_(Tj(),".config",_),r_(Tj(),".config"),Tj()];for(let E of X){if(O)Pk.info(`Checking home directory: ${E}`);let F=this.fileLoader.generateConfigPaths(_,E,k),G=await this.fileLoader.tryLoadFromPaths(F,Z,{arrayStrategy:d,verbose:O});if(G){if(O)Pk.success(`Configuration loaded from home directory: ${G.source.path}`);return G}}return null}async loadPackageJsonConfiguration(_,k,j,d,O,$,Z){let X=Z?U1(_,d,$):d;try{let E=r_(j,"package.json");if(!G8(E))return null;let F=await import(E),G=F[_],Y=_;if(!G&&k)G=F[k],Y=k;if(G&&typeof G==="object"&&!Array.isArray(G)){if($)Pk.success(`Configuration loaded from package.json: ${Y}`);return{config:N8(X,G,O),source:{type:"package.json",path:E,priority:30,timestamp:new Date}}}}catch(E){if($)Pk.warn("Failed to load package.json:",[E instanceof Error?E:Error(String(E))])}return null}async applyEnvironmentVariables(_,k,j,d){if(!j||!_||typeof k!=="object"||k===null||Array.isArray(k))return{config:k,source:{type:"default",priority:10,timestamp:new Date}};return{config:U1(_,k,d),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(_,k,j,d,O){return{config:_.config,source:_.source,path:_.source.path}}async validateConfiguration(_,k,j,d){let O=[];if(j){let $=j(_);if($)O.push(...$)}if(k){let $=await this.validator.validateConfiguration(_,k);if(!$.isValid)O.push(...$.errors.map((Z)=>Z.path?`${Z.path}: ${Z.message}`:Z.message))}if(O.length>0)throw ak.configValidation(d||"unknown",O,d)}checkCache(_,k){let j=this.generateCacheKey(_,k);return Aj.get(j)||null}cacheResult(_,k,j,d){let O=this.generateCacheKey(_,d);Aj.set(O,k,void 0,j.ttl)}generateCacheKey(_,k){let j=[_];if(k.alias)j.push(`alias:${k.alias}`);if(k.cwd)j.push(`cwd:${k.cwd}`);if(k.configDir)j.push(`configDir:${k.configDir}`);if("checkEnv"in k)j.push(`checkEnv:${k.checkEnv}`);return j.join("|")}getLocalDirectories(_,k){return Array.from(new Set([_,r_(_,"config"),r_(_,".config"),k?r_(_,k):void 0].filter(Boolean)))}getAllSearchPaths(_,k,j,d){let O=[];return O.push(...this.getLocalSearchPaths(_,k,j,d)),O.push(...this.getHomeSearchPaths(_,k)),O.push(r_(j,"package.json")),O}getLocalSearchPaths(_,k,j,d){let O=this.getLocalDirectories(j,d),$=[];for(let Z of O)$.push(...this.fileLoader.generateConfigPaths(_,Z,k));return $}getHomeSearchPaths(_,k){if(!_)return[];let j=[r_(Tj(),".config",_),r_(Tj(),".config"),Tj()],d=[];for(let O of j)d.push(...this.fileLoader.generateConfigPaths(_,O,k));return d}async loadConfigWithResult(_){return this.loadConfig(_)}}function f2(_){let j=!(_.message.includes("EACCES")||_.message.includes("EPERM")||_.message.includes("permission denied"))&&(_.message.includes("syntax")||_.message.includes("Expected")||_.message.includes("Unexpected")||_.message.includes("BuildMessage")),d=_.message.includes("Configuration must export a valid object")||_.message.includes("Configuration file is empty and exports nothing");return j||d}async function zY(_){return xk.loadConfig({..._,__strictErrorHandling:!0})}async function SZ(_){let k="defaultConfig"in _&&_.defaultConfig!==void 0?_.defaultConfig:{},j="cache"in _||"performance"in _||"schema"in _||"validate"in _;try{let d;if(j)d=await xk.loadConfig(_);else d=await xk.loadConfig({..._,defaultConfig:k,cache:{enabled:!0},performance:{enabled:!1}});return d?.config??k}catch(d){let O=d instanceof Error?d.name:"UnknownError",$=d instanceof Error?d.message:String(d);if(!(O==="ConfigNotFoundError"||O==="ConfigLoadError"||O==="ConfigValidationError"||$.includes("config"))&&_.verbose)Pk.warn("Unexpected error loading config, using defaults:",[d instanceof Error?d:Error(String(d))]);let X=j?{..._,defaultConfig:k}:{..._,defaultConfig:k,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in _?_.checkEnv!==!1:!0)return(await xk.applyEnvironmentVariables(X.name||"",k,!0,X.verbose||!1))?.config??k;return k}}async function SY(_={defaultConfig:{}}){if(typeof _==="string"){let{cwd:k}=await import("process");try{return(await xk.loadConfig({name:_,cwd:k(),generatedDir:"./generated",configDir:"./config",defaultConfig:{},checkEnv:!0,arrayStrategy:"replace"})).config}catch(j){if(j instanceof Error&&(j.name==="ConfigNotFoundError"||j.name==="ConfigLoadError"&&f2(j)))return(await xk.applyEnvironmentVariables(_,{},!0,!1)).config;throw j}}try{return(await xk.loadConfig({..._,cwd:_.cwd||Xj.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch(k){if(k instanceof Error&&(k.name==="ConfigNotFoundError"||k.name==="ConfigLoadError"&&f2(k)))return(await xk.applyEnvironmentVariables(_.name||"",_.defaultConfig||{},_.checkEnv!==!1,_.verbose||!1)).config;throw k}}async function YY(_,k,j="replace"){let d=new S0;try{let O=await d.loadFromPath(_,k,{arrayStrategy:j,useCache:!1,trackPerformance:!1});return O?O.config:null}catch{return null}}function U1(_,k,j=!1){let d=new z0,O=_.toUpperCase().replace(/[^A-Z0-9]/g,"_");function $(Z,X=[]){let E={...Z};for(let[F,G]of Object.entries(Z)){let Y=[...X,F],S=[`${O}_${Y.join("_").toUpperCase()}`,`${O}_${Y.map((Q)=>Q.toUpperCase()).join("")}`,`${O}_${Y.map((Q)=>Q.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],z,U;for(let Q of S)if(z=Xj.env[Q],z!==void 0){U=Q;break}if(z!==void 0&&U)if(typeof G==="boolean")E[F]=["true","1","yes"].includes(z.toLowerCase());else if(typeof G==="number"){let Q=Number(z);if(!Number.isNaN(Q))E[F]=Q}else if(Array.isArray(G))try{E[F]=JSON.parse(z)}catch{E[F]=z.split(",").map((Q)=>Q.trim())}else E[F]=z;else if(G&&typeof G==="object"&&!Array.isArray(G))E[F]=$(G,Y)}return E}return $(k)}function LY(_){let k=r_(Xj.cwd(),_.configDir),j=r_(Xj.cwd(),_.generatedDir),d=r_(j,"config-types.ts");if(!G8(E2(d)))$S(E2(d),{recursive:!0,mode:511});let O=G8(k)?ZS(k).map((Z)=>Z.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],$=`// Generated by bunfig v${kL}
|
|
42
|
-
export type ConfigNames = ${O.length?`'${O.join("' | '")}'`:"string"}
|
|
43
|
-
`;XS(d,$,{mode:438})}function PY(_){let k=null,j=null,d=()=>{if(!j)j=SZ(_).then(($)=>{return k=$,$},($)=>{let Z="defaultConfig"in _?_.defaultConfig:{};if(k=Z,"verbose"in _&&_.verbose)Pk.warn("Config loading failed, using defaults:",[$ instanceof Error?$:Error(String($))]);return Z});return j},O="defaultConfig"in _?_.defaultConfig:{};return k=O,d(),new Proxy({},{get($,Z){if(k)return k[Z];let X=O[Z];return d(),X},has($,Z){return Z in(k||O)},ownKeys(){return Object.keys(k||O)},getOwnPropertyDescriptor($,Z){return Object.getOwnPropertyDescriptor(k||O,Z)},set($,Z,X){if(!k)k={...O};return k[Z]=X,!0}})}function UY(_){let k=J2(fS.cwd(),_?.configDir||"./config");function j(){if(!CS(k))return[];let O=new Set([".ts",".js",".mjs",".cjs",".mts",".cts",".json"]),$=[".ts",".mts",".cts",".js",".mjs",".cjs",".json"],Z=hS(k).filter((E)=>O.has(M9(E))).map((E)=>({base:E.replace(/\.(?:ts|js|mjs|cjs|mts|cts|json)$/i,""),file:E})),X=new Map;for(let{base:E,file:F}of Z){let G=M9(F).toLowerCase(),Y=X.get(E);if(!Y){X.set(E,F);continue}let S=M9(Y).toLowerCase();if($.indexOf(G)<$.indexOf(S))X.set(E,F)}return Array.from(X.entries()).map(([E,F])=>({base:E,file:F})).sort((E,F)=>E.base.localeCompare(F.base))}function d(){let O=j(),$=O.map((F)=>F.base),Z=$.length?$.map((F)=>`'${F}'`).join(" | "):"string",X=O.length?`{
|
|
44
|
-
${O.map((F)=>{let G=J2(k,F.file).replace(/\\/g,"/");return` '${F.base}': typeof import('${G}').default`}).join(`,
|
|
45
|
-
`)}
|
|
46
|
-
}`:"Record<string, any>";return`export type ConfigNames = ${Z}
|
|
47
|
-
export type ConfigByName = ${X}
|
|
48
|
-
export type Config<N extends ConfigNames> = N extends keyof ConfigByName ? ConfigByName[N] : unknown
|
|
49
|
-
export type ConfigOf = Config
|
|
50
|
-
`}return{name:"bunfig-plugin",setup(O){O.onResolve({filter:/^virtual:bunfig-types$/},($)=>{return{path:$.path,namespace:"bunfig-virtual"}}),O.onLoad({filter:/^virtual:bunfig-types$/,namespace:"bunfig-virtual"},()=>{return{contents:d(),loader:"ts"}})}}}function QY(_,k={}){let j=NO.cwd();while(j.includes("storage"))j=I2(j,"..");let d=I2(j,_||"");if(k?.relative)return HS(NO.cwd(),d);return d}function h_(){if(qk.env.NODE_ENV==="test"||qk.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function VY(){if(qk.env.NODE_ENV==="test"||qk.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof qk<"u"){let _=qk.type;if(_==="renderer"||_==="worker")return!1;return!!(qk.versions&&(qk.versions.node||qk.versions.bun))}return!1}class YZ{async format(_){let k=await VY(),j=await this.getMetadata(k);return JSON.stringify({timestamp:_.timestamp.toISOString(),level:_.level,name:_.name,message:_.message,metadata:j})}async getMetadata(_){if(_){let{hostname:k}=await import("os");return{pid:Mj.pid,hostname:k(),environment:Mj.env.NODE_ENV||"development",platform:Mj.platform,version:Mj.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:Mj.env.NODE_ENV||Mj.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class yO{name;fileLocks=new Map;currentKeyId=null;keys=new Map;fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor(_,k={}){this.name=_,this.config={...W1},this.options=this.normalizeOptions(k),this.formatter=this.options.formatter||new YZ,this.enabled=k.enabled??!0,this.fancy=k.fancy??!0,this.tagFormat=k.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=k.timestampPosition??"right",this.environment=k.environment??Z_.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(k);let j={...k},d=k.timestamp!==void 0;if(d)delete j.timestamp;if(this.config={...this.config,...j,timestamp:d||this.config.timestamp,level:this.options.level??"info"},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let O=this.generateKeyId(),$=this.generateKey();this.currentKeyId=O,this.keys.set(O,$),this.encryptionKeys.set(O,{key:$,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(_){if(!this.fingersCrossedConfig)return!1;let k={debug:0,info:1,success:2,warning:3,error:4},j=this.fingersCrossedConfig.activationLevel??"error";return k[_]>=k[j]}initializeFingersCrossedConfig(_){if(!_.fingersCrossedEnabled&&_.fingersCrossed)return{...KO,..._.fingersCrossed};if(!_.fingersCrossedEnabled)return null;if(!_.fingersCrossed)return{...KO};return{...KO,..._.fingersCrossed}}normalizeOptions(_){let k={format:"json",level:"info",logDirectory:W1.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},j={...k,...Object.fromEntries(Object.entries(_).filter(([,d])=>d!==void 0))};if(!j.level||!["debug","info","success","warning","error"].includes(j.level))j.level=k.level;return j}shouldWriteToFile(){return!h_()&&this.config.writeToFile===!0}async writeToFile(_){let j=(async()=>{let O,$=0,Z=3,X=1000;while($<Z)try{try{try{await BS(this.config.logDirectory,M2.F_OK|M2.W_OK)}catch(F){if(F instanceof Error&&"code"in F)if(F.code==="ENOENT")await cS(this.config.logDirectory,{recursive:!0,mode:493});else if(F.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw F;else throw F}}catch(F){throw console.error("Debug: [writeToFile] Failed to create log directory:",F),F}let E=this.validateEncryptionConfig()?(await this.encrypt(_)).encrypted:Mk.from(_);try{if(!ud(this.currentLogFile))await f9(this.currentLogFile,"",{mode:420});if(O=w2(this.currentLogFile,"a",420),iS(O,E,{flag:"a"}),R2(O),O!==void 0)h9(O),O=void 0;if((await Rj(this.currentLogFile)).size===0){if(await f9(this.currentLogFile,E,{flag:"w",mode:420}),(await Rj(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(F){let G=F;if(G.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(G.code)){if($<Z-1){let Y=typeof G.message==="string"?G.message:"Unknown error";console.error(`Network error during write attempt ${$+1}/${Z}:`,Y);let S=X*2**$;await new Promise((z)=>setTimeout(z,S)),$++;continue}}if(G?.code&&["ENOSPC","EDQUOT"].includes(G.code))throw Error(`Disk quota exceeded or no space left on device: ${G.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",G),G}finally{if(O!==void 0)try{h9(O)}catch(F){console.error("Debug: [writeToFile] Error closing file descriptor:",F)}}}catch(E){if($===Z-1){let G=E,Y=typeof G.message==="string"?G.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",Y),E}$++;let F=X*2**($-1);await new Promise((G)=>setTimeout(G,F))}})();this.pendingOperations.push(j);let d=this.pendingOperations.length-1;try{await j}catch(O){throw console.error("Debug: [writeToFile] Error in operation:",O),O}finally{this.pendingOperations.splice(d,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return wj(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return wj(this.config.logDirectory,`${this.name}.log`);let _=new Date().toISOString().split("T")[0];return wj(this.config.logDirectory,`${this.name}-${_}.log`)}setupRotation(){if(h_())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let _=this.config.rotation,k;switch(_.frequency){case"daily":k=86400000;break;case"weekly":k=604800000;break;case"monthly":k=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},k)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let k=this.config.rotation.keyRotation;if(!k?.enabled)return;let j=typeof k.interval==="number"?k.interval:60,d=Math.max(j,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((O)=>{console.error("Error rotating keys:",O)})},d)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let k=this.config.rotation.keyRotation,j=this.generateKeyId(),d=this.generateKey();this.currentKeyId=j,this.keys.set(j,d),this.encryptionKeys.set(j,{key:d,createdAt:new Date});let O=Array.from(this.encryptionKeys.entries()).sort(([,X],[,E])=>E.createdAt.getTime()-X.createdAt.getTime()),$=typeof k.maxKeys==="number"?k.maxKeys:1,Z=Math.max(1,$);if(O.length>Z)for(let[X]of O.slice(Z))this.encryptionKeys.delete(X),this.keys.delete(X)}generateKeyId(){return C9(16).toString("hex")}generateKey(){return C9(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let _=this.keys.get(this.currentKeyId);if(!_)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:_,id:this.currentKeyId}}encrypt(_){let{key:k}=this.getCurrentKey(),j=C9(16),d=bS("aes-256-gcm",k,j),O=Mk.isBuffer(_)?_:Mk.from(_,"utf8"),$=d.update(O),Z=d.final(),X=$.length+Z.length,E=d.getAuthTag(),F=Mk.allocUnsafe(16+X+16);return j.copy(F,0),$.copy(F,16),Z.copy(F,16+$.length),E.copy(F,16+X),{encrypted:F,iv:j}}async compressData(_){return new Promise((k,j)=>{let d=h2(),O=[];d.on("data",($)=>O.push($)),d.on("end",()=>k(Mk.from(Mk.concat(O)))),d.on("error",j),d.write(_),d.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let _={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let k=this.config.rotation.encrypt;return{..._,...k}}return _}async rotateLog(){if(h_())return;if(!this.shouldWriteToFile())return;let _=await Rj(this.currentLogFile).catch(()=>null);if(!_)return;let k=this.config.rotation;if(typeof k==="boolean")return;if(k.maxSize&&_.size>=k.maxSize){let j=this.currentLogFile,d=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let O=await ld(this.config.logDirectory),$=O.filter((E)=>E.startsWith(this.name)&&/\.log\.\d+$/.test(E)).sort((E,F)=>{let G=Number.parseInt(E.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(F.match(/\.log\.(\d+)$/)?.[1]||"0")-G}),Z=$.length>0?Number.parseInt($[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,X=`${j}.${Z}`;if(await Rj(j).catch(()=>null))try{if(await C2(j,X),k.compress)try{let E=`${X}.gz`;await this.compressLogFile(X,E),await pd(X)}catch(E){console.error("Error compressing rotated file:",E)}if($.length===0&&!O.some((E)=>E.endsWith(".log.1")))try{let E=`${j}.1`;await f9(E,"")}catch(E){console.error("Error creating backup file:",E)}}catch(E){console.error(`Error during rotation: ${E instanceof Error?E.message:String(E)}`)}}else{let O=new Date().toISOString().replace(/[:.]/g,"-"),$=j.replace(/\.log$/,`-${O}.log`);if(await Rj(j).catch(()=>null))await C2(j,$)}if(this.currentLogFile=d,k.maxFiles){let $=(await ld(this.config.logDirectory)).filter((Z)=>Z.startsWith(this.name)).sort((Z,X)=>X.localeCompare(Z));for(let Z of $.slice(k.maxFiles))await pd(wj(this.config.logDirectory,Z))}}}async compressLogFile(_,k){let j=D2(_),d=xS(k),O=h2();await AS(j,O,d)}async handleFingersCrossedBuffer(_,k){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(_)&&!this.isActivated){this.isActivated=!0;for(let j of this.logBuffer){let d=await this.formatter.format(j);if(this.shouldWriteToFile())await this.writeToFile(d);console.log(d)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(k);console.log(k)}}shouldLog(_){if(!this.enabled)return!1;let k={debug:0,info:1,success:2,warning:3,error:4};return k[_]>=k[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((_)=>{if(_ instanceof Promise)return _.catch((k)=>{console.error("Error in pending write operation:",k)});return Promise.resolve()})),ud(this.currentLogFile))try{let _=w2(this.currentLogFile,"r+");R2(_),h9(_)}catch(_){console.error(`Error flushing file: ${_}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let _ of this.pendingOperations)if(typeof _.cancel==="function")_.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(_){console.error("Error waiting for pending operations:",_)}if(!h_()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let k=(await ld(this.config.logDirectory)).filter((j)=>(j.includes("temp")||j.includes(".tmp"))&&j.includes(this.name));for(let j of k)try{await pd(wj(this.config.logDirectory,j))}catch(d){console.error(`Failed to delete temp file ${j}:`,d)}}catch(_){console.error("Error cleaning up temporary files:",_)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(_){if(!_)return"";return`${this.tagFormat.prefix}${_}${this.tagFormat.suffix}`}formatFileTimestamp(_){return`[${_.toISOString()}]`}formatConsoleTimestamp(_){return this.shouldStyleConsole()?E_.gray(_.toLocaleTimeString()):_.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||h_())return!1;let _=typeof Z_.env.NO_COLOR<"u",k=Z_.env.FORCE_COLOR==="0";if(_||k)return!1;return!!(typeof Z_.stderr<"u"&&Z_.stderr.isTTY||typeof Z_.stdout<"u"&&Z_.stdout.isTTY)}formatConsoleMessage(_){let{timestamp:k,icon:j="",tag:d="",message:O,level:$,showTimestamp:Z=!0}=_,X=(z)=>z.replace(this.ANSI_PATTERN,"");if(!this.fancy){let z=[];if(Z)z.push(k);if($==="warning")z.push("WARN");else if($==="error")z.push("ERROR");else if(j)z.push(j.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(d)z.push(d.replace(/[[\]]/g,""));return z.push(O),z.join(" ")}let E=Z_.stdout.columns||120,F="";if($==="warning"||$==="error")F=`${j} ${O}`;else if($==="info"||$==="success")F=`${j} ${d} ${O}`;else F=`${j} ${d} ${E_.cyan(O)}`;if(!Z)return F.trim();let G=X(F).trim().length,Y=X(k).length,S=Math.max(1,E-2-G-Y);return`${F.trim()}${" ".repeat(S)}${k}`}formatMessage(_,k){if(k.length===1&&Array.isArray(k[0]))return _.replace(/\{(\d+)\}/g,($,Z)=>{let X=Number.parseInt(Z,10);return X<k[0].length?String(k[0][X]):$});let j=/%([sdijfo%])/g,d=0,O=_.replace(j,($,Z)=>{if(Z==="%")return"%";if(d>=k.length)return $;let X=k[d++];switch(Z){case"s":return String(X);case"d":case"i":return Number(X).toString();case"j":case"o":return JSON.stringify(X,null,2);default:return $}});if(d<k.length)O+=` ${k.slice(d).map(($)=>typeof $==="object"?JSON.stringify($,null,2):String($)).join(" ")}`;return O}formatMarkdown(_){if(!_)return _;let k=_;return k=k.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(j,d,O)=>{let $=E_.underline(E_.blue(d)),Z=this.toAbsoluteFilePath(O);if(Z&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let X=`file://${encodeURI(Z)}`,E="\x1B]8;;",F="\x1B\\";return`\x1B]8;;${X}\x1B\\${$}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${O}\x1B\\${$}\x1B]8;;\x1B\\`;return $}),k=k.replace(/`([^`]+)`/g,(j,d)=>E_.bgGray(d)),k=k.replace(/\*\*([^*]+)\*\*/g,(j,d)=>E_.bold(d)),k=k.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(j,d)=>E_.italic(d)),k=k.replace(/(?<!_)_([^_]+)_(?!_)/g,(j,d)=>E_.italic(d)),k=k.replace(/~([^~]+)~/g,(j,d)=>E_.strikethrough(d)),k}supportsHyperlinks(){if(h_())return!1;let _=Z_.env;if(!_)return!1;if(_.TERM_PROGRAM==="iTerm.app"||_.TERM_PROGRAM==="vscode"||_.TERM_PROGRAM==="WezTerm")return!0;if(_.WT_SESSION)return!0;if(_.TERM==="xterm-kitty")return!0;let k=_.VTE_VERSION?Number.parseInt(_.VTE_VERSION,10):0;if(!Number.isNaN(k)&&k>=5000)return!0;return!1}toAbsoluteFilePath(_){try{let k=_;if(k.startsWith("file://"))k=k.replace(/^file:\/\//,"");if(k.startsWith("~")){let j=Z_.env.HOME||"";if(j)k=k.replace(/^~(?=$|\/)/,j)}if(yS(k)||k.startsWith("./")||k.startsWith("../"))k=vS(k);else return null;return ud(k)?k:null}catch{return null}}buildOutputTexts(_){let k=this.shouldStyleConsole()?this.formatMarkdown(_):_,j=_.replace(this.ANSI_PATTERN,"");return{consoleText:k,fileText:j}}async log(_,k,...j){if(!this.shouldLog(_))return;let d=new Date,O=this.formatConsoleTimestamp(d),$=this.formatFileTimestamp(d),Z,X;if(k instanceof Error)Z=k.message,X=k.stack;else Z=this.formatMessage(k,j);let{consoleText:E,fileText:F}=this.buildOutputTexts(Z);if(this.shouldStyleConsole()){let Y=this.options.showIcons===!1?"":DZ[_],S=this.options.showTags!==!1&&this.name?E_.gray(this.formatTag(this.name)):"",z;switch(_){case"debug":z=this.formatConsoleMessage({timestamp:O,icon:Y,tag:S,message:E_.gray(E),level:_}),console.error(z);break;case"info":z=this.formatConsoleMessage({timestamp:O,icon:Y,tag:S,message:E,level:_}),console.warn(z);break;case"success":z=this.formatConsoleMessage({timestamp:O,icon:Y,tag:S,message:E_.green(E),level:_}),console.error(z);break;case"warning":z=this.formatConsoleMessage({timestamp:O,icon:Y,tag:S,message:E,level:_}),console.warn(z);break;case"error":if(z=this.formatConsoleMessage({timestamp:O,icon:Y,tag:S,message:E,level:_}),console.error(z),X){let U=X.split(`
|
|
51
|
-
`);for(let Q of U)if(Q.trim()&&!Q.includes(Z))console.error(this.formatConsoleMessage({timestamp:O,message:E_.gray(` ${Q}`),level:_,showTimestamp:!1}))}break}}else if(!h_()){if(console.error(`${$} ${this.environment}.${_.toUpperCase()}: ${Z}`),X)console.error(X)}let G=`${$} ${this.environment}.${_.toUpperCase()}: ${F}
|
|
52
|
-
`;if(X)G+=`${X}
|
|
53
|
-
`;if(G=G.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(G)}progress(_,k=""){let j={update:(X,E)=>{},finish:(X)=>{},interrupt:(X,E)=>{}};if(!this.enabled)return j;let d=30;if(this.activeProgressBar={total:Math.max(1,_||1),current:0,message:k||"",barLength:d,lastRenderedLine:""},this.shouldStyleConsole()&&!h_()&&Z_.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(X,E)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,X),this.activeProgressBar.total),E!==void 0)this.activeProgressBar.message=E;if(this.shouldStyleConsole()&&!h_()&&Z_.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(X)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,X)},interrupt:(X,E="info")=>{if(!h_()&&Z_.stdout.isTTY)Z_.stdout.write(`
|
|
54
|
-
`);if(this[E==="warning"?"warn":E](X),this.activeProgressBar&&this.shouldStyleConsole()&&!h_()&&Z_.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(_){let k=performance.now();if(this.shouldStyleConsole()){let j=this.options.showTags!==!1&&this.name?E_.gray(this.formatTag(this.name)):"",d=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:d,icon:this.options.showIcons===!1?"":E_.blue("\u25D0"),tag:j,message:`${E_.cyan(_)}...`}))}return async(j)=>{if(!this.enabled)return;let d=performance.now(),O=Math.round(d-k),$=`${_} completed in ${O}ms`,Z=new Date,X=this.formatConsoleTimestamp(Z),F=`${this.formatFileTimestamp(Z)} ${this.environment}.INFO: ${$}`;if(j)F+=` ${JSON.stringify(j)}`;if(F+=`
|
|
55
|
-
`,F=F.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let G=this.options.showTags!==!1&&this.name?E_.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:X,icon:this.options.showIcons===!1?"":E_.green("\u2713"),tag:G,message:`${$}${j?` ${JSON.stringify(j)}`:""}`}))}else if(!h_())console.error(F.trim());if(this.shouldWriteToFile())await this.writeToFile(F)}}async debug(_,...k){await this.log("debug",_,...k)}async info(_,...k){await this.log("info",_,...k)}async success(_,...k){await this.log("success",_,...k)}async warn(_,...k){await this.log("warning",_,...k)}async error(_,...k){await this.log("error",_,...k)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let _=this.config.rotation,{encrypt:k}=_;return!!k}async only(_){if(!this.enabled)return;return await _()}isEnabled(){return this.enabled}setEnabled(_){this.enabled=_}extend(_){let k=`${this.name}:${_}`,j=new yO(k,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(j),j}createReadStream(){if(h_())throw Error("createReadStream is not supported in browser environments");if(!ud(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return D2(this.currentLogFile,{encoding:"utf8"})}async decrypt(_){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let k=this.config.rotation;if(!k.encrypt||typeof k.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let j=this.keys.get(this.currentKeyId);try{let d=Mk.isBuffer(_)?_:Mk.from(_,"base64"),O=d.subarray(0,16),$=d.subarray(d.length-16),Z=d.subarray(16,d.length-16),X=NS("aes-256-gcm",j,O);X.setAuthTag($);let E=X.update(Z),F=X.final(),G=E.length+F.length,Y=Mk.allocUnsafe(G);return E.copy(Y,0),F.copy(Y,E.length),Y.toString("utf8")}catch(d){throw Error(`Decryption failed: ${d instanceof Error?d.message:String(d)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return h_()}isServerMode(){return!h_()}setTestEncryptionKey(_,k){this.currentKeyId=_,this.keys.set(_,k)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box(_){if(!this.enabled)return;let k=new Date,j=this.formatConsoleTimestamp(k),d=this.formatFileTimestamp(k),{consoleText:O,fileText:$}=this.buildOutputTexts(_);if(this.shouldStyleConsole()){let X=O.split(`
|
|
56
|
-
`),E=Math.max(...X.map((S)=>S.length))+2,F=`\u250C${"\u2500".repeat(E)}\u2510`,G=`\u2514${"\u2500".repeat(E)}\u2518`,Y=X.map((S)=>{return this.formatConsoleMessage({timestamp:j,message:E_.cyan(S),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:j,message:E_.cyan(F),showTimestamp:!1})),Y.forEach((S)=>console.error(S)),console.error(this.formatConsoleMessage({timestamp:j,message:E_.cyan(G),showTimestamp:!1}))}else if(!h_())console.error(`${d} ${this.environment}.INFO: [BOX] ${$}`);let Z=`${d} ${this.environment}.INFO: [BOX] ${$}
|
|
57
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(Z)}async prompt(_){if(h_())return Promise.resolve(!0);return new Promise((k)=>{console.error(`${E_.cyan("?")} ${_} (y/n) `);let j=(d)=>{let O=d.toString().trim().toLowerCase();Z_.stdin.removeListener("data",j);try{if(typeof Z_.stdin.setRawMode==="function")Z_.stdin.setRawMode(!1)}catch{}Z_.stdin.pause(),console.error(""),k(O==="y"||O==="yes")};try{if(typeof Z_.stdin.setRawMode==="function")Z_.stdin.setRawMode(!0)}catch{}Z_.stdin.resume(),Z_.stdin.once("data",j)})}setFancy(_){this.fancy=_}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(_,...k){if(!this.enabled)return;let j=_;if(k&&k.length>0){let E=/%([sdijfo%])/g,F=0;if(j=_.replace(E,(G,Y)=>{if(Y==="%")return"%";if(F>=k.length)return G;let S=k[F++];switch(Y){case"s":return String(S);case"d":case"i":return Number(S).toString();case"j":case"o":return JSON.stringify(S,null,2);default:return G}}),F<k.length)j+=` ${k.slice(F).map((G)=>typeof G==="object"?JSON.stringify(G,null,2):String(G)).join(" ")}`}let{consoleText:d,fileText:O}=this.buildOutputTexts(j);if(this.shouldStyleConsole()){let E=this.options.showTags!==!1&&this.name?E_.gray(this.formatTag(this.name)):"",F=this.options.showIcons===!1?"":`${E_.blue("\u25D0")} `;console.error(`${F}${E} ${E_.cyan(d)}`)}let X=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${O}
|
|
58
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(X)}renderProgressBar(_,k=!1){if(!this.enabled||!this.shouldStyleConsole()||!Z_.stdout.isTTY)return;let j=Math.min(100,Math.max(0,Math.round(_.current/_.total*100))),d=Math.round(_.barLength*j/100),O=_.barLength-d,$=E_.green("\u2501".repeat(d)),Z=E_.gray("\u2501".repeat(O)),X=`[${$}${Z}]`,E=`${j}%`.padStart(4),F=_.message?` ${_.message}`:"",G=this.options.showIcons===!1?"":k||j===100?E_.green("\u2713"):E_.blue("\u25B6"),Y=this.options.showTags!==!1&&this.name?` ${E_.gray(this.formatTag(this.name))}`:"",S=`\r${G}${Y} ${X} ${E}${F}`,z=Z_.stdout.columns||80,U=" ".repeat(Math.max(0,z-S.replace(this.ANSI_PATTERN,"").length));if(_.lastRenderedLine=`${S}${U}`,Z_.stdout.write(_.lastRenderedLine),k)Z_.stdout.write(`
|
|
59
|
-
`)}finishProgressBar(_,k){if(!this.enabled||!this.fancy||h_()||!Z_.stdout.isTTY){this.activeProgressBar=null;return}if(_.current<_.total)_.current=_.total;if(k)_.message=k;this.renderProgressBar(_,!0),this.activeProgressBar=null}async clear(_={}){if(h_()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let k=await ld(this.config.logDirectory),j=[];for(let d of k){if(!(_.name?new RegExp(_.name.replace("*",".*")).test(d):d.startsWith(this.name))||!d.endsWith(".log"))continue;let $=wj(this.config.logDirectory,d);if(_.before)try{if((await Rj($)).mtime>=_.before)continue}catch(Z){console.error(`Failed to get stats for file ${$}:`,Z);continue}j.push($)}if(j.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${j.length} log file(s)...`);for(let d of j)try{await pd(d),console.warn(`Deleted log file: ${d}`)}catch(O){console.error(`Failed to delete log file ${d}:`,O)}console.warn("Log clearing process finished.")}catch(k){console.error("Error during log clearing process:",k)}}}async function TY(_,k={}){let{maxRetries:j=3,retryDelay:d=1000,isRetryable:O=()=>!0,fallback:$}=k,Z=Error("Unknown error occurred");for(let X=0;X<=j;X++)try{return await _()}catch(E){if(Z=E instanceof Error?E:Error(String(E)),X===j||!O(Z))break;if(d>0)await new Promise((F)=>setTimeout(F,d))}if($!==void 0)return $;throw Z instanceof Error?Z:Error(`Unknown error: ${String(Z)}`)}class i8{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:(_,k)=>k==="boolean"||["true","false","1","0","yes","no"].includes(_.toLowerCase()),parse:(_)=>{let k=_.toLowerCase();return["true","1","yes"].includes(k)}},{name:"number",canParse:(_,k)=>k==="number"||!Number.isNaN(Number(_))&&!Number.isNaN(Number.parseFloat(_)),parse:(_)=>{let k=Number(_);if(Number.isNaN(k))throw TypeError(`Cannot parse "${_}" as number`);return k}},{name:"array",canParse:(_,k)=>k==="array"||_.startsWith("[")||_.includes(","),parse:(_)=>{try{let k=JSON.parse(_);if(Array.isArray(k))return k}catch{}return _.split(",").map((k)=>k.trim())}},{name:"json",canParse:(_,k)=>k==="object"||(_.startsWith("{")&&_.endsWith("}")||_.startsWith("[")&&_.endsWith("]")),parse:(_)=>{try{return JSON.parse(_)}catch(k){throw Error(`Cannot parse "${_}" as JSON: ${k}`)}}}]}async applyEnvironmentVariables(_,k,j={}){let{prefix:d,useCamelCase:O=!0,useBackwardCompatibility:$=!0,customParsers:Z={},verbose:X=!1,trackPerformance:E=!0}=j,F=async()=>{if(!_)return{config:k,source:{type:"environment",priority:50,timestamp:new Date}};let G=d||this.generateEnvPrefix(_),Y={...k};return this.processObject(Y,[],G,{useCamelCase:O,useBackwardCompatibility:$,customParsers:Z,verbose:X,configName:_}),{config:Y,source:{type:"environment",priority:50,timestamp:new Date}}};if(E)return Y0.track("applyEnvironmentVariables",F,{configName:_});return F()}generateEnvPrefix(_){return _.toUpperCase().replace(/-/g,"_")}formatEnvKey(_,k){if(!k)return _.toUpperCase();return _.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject(_,k,j,d){for(let[O,$]of Object.entries(_)){let Z=[...k,O],X=Z.map((G)=>this.formatEnvKey(G,d.useCamelCase)),E=`${j}_${X.join("_")}`,F=d.useBackwardCompatibility?`${j}_${Z.map((G)=>G.toUpperCase()).join("_")}`:null;if(d.verbose);if(typeof $==="object"&&$!==null&&!Array.isArray($))this.processObject($,Z,j,d);else{let G=sd.env[E]||(F?sd.env[F]:void 0);if(G!==void 0){if(d.verbose){let Y=sd.env[E]?E:F}try{_[O]=this.parseEnvironmentValue(G,typeof $,E,d.customParsers,d.configName)}catch(Y){if(Y instanceof V8)throw Y;throw Ej.envVar(E,G,typeof $,d.configName)}}}}}parseEnvironmentValue(_,k,j,d,O){for(let[$,Z]of Object.entries(d))try{return Z(_)}catch{continue}for(let $ of this.defaultParsers)if($.canParse(_,k))try{return $.parse(_)}catch{throw Ej.envVar(j,_,`${k} (via ${$.name} parser)`,O)}return _}getEnvironmentVariables(_){let k={},j=_.toUpperCase();for(let[d,O]of Object.entries(sd.env))if(d.startsWith(j)&&O!==void 0)k[d]=O;return k}validateEnvironmentVariable(_,k,j){let d=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(_))d.push(`Environment variable key "${_}" should only contain uppercase letters, numbers, and underscores`);if(j)try{this.parseEnvironmentValue(_,k,j,{})}catch(O){d.push(`Cannot parse value "${k}" as ${j}: ${O}`)}return{isValid:d.length===0,errors:d}}generateEnvVarDocs(_,k,j={}){let{prefix:d,format:O="text"}=j,$=d||this.generateEnvPrefix(_),Z=[];switch(this.extractEnvVarInfo(k,[],$,Z),O){case"markdown":return this.formatAsMarkdown(Z,_);case"json":return JSON.stringify(Z,null,2);default:return this.formatAsText(Z,_)}}extractEnvVarInfo(_,k,j,d){for(let[O,$]of Object.entries(_)){let Z=[...k,O],X=`${j}_${Z.map((E)=>this.formatEnvKey(E,!0)).join("_")}`;if(typeof $==="object"&&$!==null&&!Array.isArray($))this.extractEnvVarInfo($,Z,j,d);else d.push({key:X,type:Array.isArray($)?"array":typeof $,description:`Configuration for ${Z.join(".")}`,example:this.generateExample($)})}}generateExample(_){if(Array.isArray(_))return JSON.stringify(_);if(typeof _==="object"&&_!==null)return JSON.stringify(_);return String(_)}formatAsText(_,k){let j=`Environment Variables for ${k}:
|
|
60
|
-
|
|
61
|
-
`;for(let d of _)j+=`${d.key}
|
|
62
|
-
`,j+=` Type: ${d.type}
|
|
63
|
-
`,j+=` Description: ${d.description}
|
|
64
|
-
`,j+=` Example: ${d.example}
|
|
65
|
-
|
|
66
|
-
`;return j}formatAsMarkdown(_,k){let j=`# Environment Variables for ${k}
|
|
67
|
-
|
|
68
|
-
`;j+=`| Variable | Type | Description | Example |
|
|
69
|
-
`,j+=`|----------|------|-------------|----------|
|
|
70
|
-
`;for(let d of _)j+=`| \`${d.key}\` | ${d.type} | ${d.description} | \`${d.example}\` |
|
|
71
|
-
`;return j}}function WY(_,k,j={}){return LZ(_,k,j,new WeakMap)}function LZ(_,k,j,d){let{arrayMergeMode:O="replace",skipNullish:$=!1,customMerger:Z}=j;if(k===null||k===void 0)return $?_:k;if(Z){let X=Z(_,k);if(X!==void 0)return X}if(Array.isArray(k)||Array.isArray(_))return PZ(_,k,O,d);if(!Fk(k)||!Fk(_))return k;return IY(_,k,j,d)}function PZ(_,k,j,d){if(Array.isArray(k)&&!Array.isArray(_))return k;if(Array.isArray(_)&&!Array.isArray(k))return k;if(Array.isArray(k)&&Array.isArray(_))switch(j){case"replace":return k;case"concat":return KY(_,k);case"smart":return nY(_,k,d);default:return k}return k}function KY(_,k){let j=[...k];for(let d of _)if(!j.some((O)=>P8(O,d)))j.push(d);return j}function nY(_,k,j){if(k.length===0)return _;if(_.length===0)return k;if(Fk(k[0])&&Fk(_[0]))return JY(_,k,j);if(k.every((d)=>typeof d==="string")&&_.every((d)=>typeof d==="string")){let d=[...k];for(let O of _)if(!d.includes(O))d.push(O);return d}return k}function JY(_,k,j){let d=[...k];for(let O of _){if(!Fk(O)){d.push(O);continue}let $=["id","name","key","path","type"],Z=!1;for(let X of $)if(X in O){if(d.find((F)=>Fk(F)&&(X in F)&&F[X]===O[X])){Z=!0;break}}if(!Z)d.push(O)}return d}function IY(_,k,j,d){let O=k;if(Fk(O)&&d.has(O))return d.get(O);let $={..._};if(Fk(O))d.set(O,$);for(let Z in O){if(!Object.prototype.hasOwnProperty.call(O,Z))continue;let X=O[Z],E=$[Z];if(j.skipNullish&&(X===null||X===void 0))continue;if(X===null||X===void 0){$[Z]=X;continue}if(Fk(X)&&Fk(E))$[Z]=LZ(E,X,j,d);else if(Array.isArray(X)||Array.isArray(E))$[Z]=PZ(E,X,j.arrayMergeMode||"smart",d);else $[Z]=X}return $}function UZ(_,k,j="replace"){return WY(_,k,{arrayMergeMode:j==="replace"?"replace":"smart",skipNullish:!0})}function P8(_,k){if(_===k)return!0;if(Array.isArray(_)&&Array.isArray(k)){if(_.length!==k.length)return!1;for(let j=0;j<_.length;j++)if(!P8(_[j],k[j]))return!1;return!0}if(Fk(_)&&Fk(k)){let j=Object.keys(_),d=Object.keys(k);if(j.length!==d.length)return!1;for(let O of j){if(!Object.prototype.hasOwnProperty.call(k,O))return!1;if(!P8(_[O],k[O]))return!1}return!0}return!1}function Fk(_){return Boolean(_&&typeof _==="object"&&!Array.isArray(_))}class QZ{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(_,k,j={}){let{arrayStrategy:d="replace",useCache:O=!0,cacheTtl:$,trackPerformance:Z=!0,verbose:X=!1}=j;if(O){let F=v1.getWithFileCheck("file",_);if(F){if(X)console.log(`Configuration loaded from cache: ${_}`);return F}}let E=async()=>{if(!od(_))return null;try{let F=`?t=${Date.now()}`,G=await import(_+F),Y=G.default||G,S="default"in G,z=Object.keys(G).length>0;if(!S&&!z)throw new vO(_,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof Y!=="object"||Y===null||Array.isArray(Y))throw new vO(_,Error("Configuration must export a valid object"),"unknown");let I={config:UZ(k,Y,d),source:{type:"file",path:_,priority:100,timestamp:new Date}};if(O)v1.setWithFileCheck("file",I,_,$);return I}catch(F){throw F instanceof Error?Ej.configLoad(_,F):Ej.configLoad(_,Error(String(F)))}};if(Z)return Y0.track("loadFromPath",E,{path:_});return E()}async tryLoadFromPaths(_,k,j={}){for(let d of _)try{let O=await this.loadFromPath(d,k,j);if(O)return O}catch(O){if(O instanceof Error&&O.name==="ConfigLoadError")throw O;if(j.verbose)console.warn(`Failed to load config from ${d}:`,O)}return null}generateConfigPaths(_,k,j){let d=this.generateNamePatterns(_,j),O=[];for(let $ of d)for(let Z of this.extensions)O.push(q9(k,`${$}${Z}`));return O}generateNamePatterns(_,k){let j=[];if(j.push("config",".config"),_)j.push(_,`.${_}.config`,`${_}.config`,`.${_}`);let d=k===void 0?[]:Array.isArray(k)?k:[k];for(let $ of d){if(!$)continue;if(j.push($,`.${$}.config`,`${$}.config`,`.${$}`),_)j.push(`${_}.${$}.config`,`.${_}.${$}.config`)}let O=new Set;return j.filter(($)=>{if(!$||O.has($))return!1;return O.add($),!0})}checkFileAccess(_){return TY(async()=>{return od(_)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(_,k,j){let d=[];if(!od(_))return d;if(k||j){let O=this.generateNamePatterns(k||"",j);for(let $ of O)for(let Z of this.extensions){let X=q9(_,`${$}${Z}`);if(await this.checkFileAccess(X))d.push(X)}}else try{let{readdirSync:O}=await import("fs"),$=O(_);for(let Z of $)if(this.looksLikeConfigFile(Z)){let X=q9(_,Z);if(await this.checkFileAccess(X))d.push(X)}}catch{return[]}return d}looksLikeConfigFile(_){return[/\.config\.(ts|js|mjs|cjs|json|mts|cts)$/,/^\..*\.(ts|js|mjs|cjs|json|mts|cts)$/,/config\.(ts|js|mjs|cjs|json|mts|cts)$/].some((j)=>j.test(_))}async validateConfigFile(_){let k=[];try{if(!od(_))return k.push("Configuration file does not exist"),k;let j=await import(_),d=j.default||j;if(d===void 0)k.push("Configuration file must export a default value or named exports");else if(typeof d!=="object"||d===null)k.push("Configuration must be an object");else if(Array.isArray(d))k.push("Configuration cannot be an array at the root level");if(_.endsWith(".json"))try{let{readFileSync:O}=await import("fs"),$=O(_,"utf8");JSON.parse($)}catch(O){k.push(`Invalid JSON syntax: ${O}`)}}catch(j){k.push(`Failed to load configuration file: ${j}`)}return k}async getFileModificationTime(_){try{let{statSync:k}=await import("fs");return k(_).mtime}catch{return null}}async preloadConfigurations(_,k={}){let j=new Map;return await Promise.allSettled(_.map(async(d)=>{try{let O=await this.loadFromPath(d,{},k);if(O)j.set(d,O.config)}catch(O){if(k.verbose)console.warn(`Failed to preload ${d}:`,O)}})),j}}class VZ{async validateConfiguration(_,k,j={}){let{stopOnFirstError:d=!1,validateRequired:O=!0,validateTypes:$=!0,customRules:Z=[],trackPerformance:X=!0,verbose:E=!1}=j,F=async()=>{let G=[],Y=[],S={stopOnFirstError:d,validateRequired:O,validateTypes:$,customRules:Z,trackPerformance:X,verbose:E};try{if(typeof k==="string")return await this.validateWithSchemaFile(_,k,S);else if(Array.isArray(k))return this.validateWithRules(_,[...k,...Z],S);else return this.validateWithJSONSchema(_,k,S)}catch(z){return G.push({path:"",message:`Validation failed: ${z}`,rule:"system"}),{isValid:!1,errors:G,warnings:Y}}};if(X)return await Y0.track("validateConfiguration",F);return F()}async validateWithSchemaFile(_,k,j){try{if(!mS(k))throw new AO(k,[{path:"",message:"Schema file does not exist"}]);let d=await import(k),O=d.default||d;if(Array.isArray(O))return this.validateWithRules(_,O,j);else return this.validateWithJSONSchema(_,O,j)}catch(d){throw new AO(k,[{path:"",message:`Failed to load schema: ${d}`}])}}validateWithJSONSchema(_,k,j){let d=[],O=[];return this.validateObjectAgainstSchema(_,k,"",d,O,j),{isValid:d.length===0,errors:d,warnings:O}}validateObjectAgainstSchema(_,k,j,d,O,$){if($.validateTypes&&k.type){let Z=Array.isArray(_)?"array":typeof _,X=Array.isArray(k.type)?k.type:[k.type];if(!X.includes(Z)){if(d.push({path:j,message:`Expected type ${X.join(" or ")}, got ${Z}`,expected:X.join(" or "),actual:Z,rule:"type"}),$.stopOnFirstError)return}}if(k.enum&&!k.enum.includes(_)){if(d.push({path:j,message:`Value must be one of: ${k.enum.join(", ")}`,expected:k.enum.join(", "),actual:_,rule:"enum"}),$.stopOnFirstError)return}if(typeof _==="string"){if(k.minLength!==void 0&&_.length<k.minLength)d.push({path:j,message:`String length must be at least ${k.minLength}`,expected:`>= ${k.minLength}`,actual:_.length,rule:"minLength"});if(k.maxLength!==void 0&&_.length>k.maxLength)d.push({path:j,message:`String length must not exceed ${k.maxLength}`,expected:`<= ${k.maxLength}`,actual:_.length,rule:"maxLength"});if(k.pattern){if(!new RegExp(k.pattern).test(_))d.push({path:j,message:`String does not match pattern ${k.pattern}`,expected:k.pattern,actual:_,rule:"pattern"})}}if(typeof _==="number"){if(k.minimum!==void 0&&_<k.minimum)d.push({path:j,message:`Value must be at least ${k.minimum}`,expected:`>= ${k.minimum}`,actual:_,rule:"minimum"});if(k.maximum!==void 0&&_>k.maximum)d.push({path:j,message:`Value must not exceed ${k.maximum}`,expected:`<= ${k.maximum}`,actual:_,rule:"maximum"})}if(Array.isArray(_)&&k.items)for(let Z=0;Z<_.length;Z++){let X=j?`${j}[${Z}]`:`[${Z}]`;if(this.validateObjectAgainstSchema(_[Z],k.items,X,d,O,$),$.stopOnFirstError&&d.length>0)return}if(_&&typeof _==="object"&&!Array.isArray(_)){let Z=_;if($.validateRequired&&k.required){for(let X of k.required)if(!(X in Z)){if(d.push({path:j?`${j}.${X}`:X,message:`Missing required property '${X}'`,expected:"required",rule:"required"}),$.stopOnFirstError)return}}if(k.properties){for(let[X,E]of Object.entries(k.properties))if(X in Z){let F=j?`${j}.${X}`:X;if(this.validateObjectAgainstSchema(Z[X],E,F,d,O,$),$.stopOnFirstError&&d.length>0)return}}if(k.additionalProperties===!1){let X=new Set(Object.keys(k.properties||{}));for(let E of Object.keys(Z))if(!X.has(E))O.push({path:j?`${j}.${E}`:E,message:`Additional property '${E}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(_,k,j){let d=[],O=[];for(let $ of k)try{let Z=this.getValueByPath(_,$.path),X=this.validateWithRule(Z,$,$.path);if(d.push(...X),j.stopOnFirstError&&d.length>0)break}catch(Z){d.push({path:$.path,message:`Rule validation failed: ${Z}`,rule:"system"})}return{isValid:d.length===0,errors:d,warnings:O}}validateWithRule(_,k,j){let d=[];if(k.required&&(_===void 0||_===null))return d.push({path:j,message:k.message||`Property '${j}' is required`,expected:"required",rule:"required"}),d;if(_===void 0||_===null)return d;if(k.type){let O=Array.isArray(_)?"array":typeof _;if(O!==k.type)d.push({path:j,message:k.message||`Expected type ${k.type}, got ${O}`,expected:k.type,actual:O,rule:"type"})}if(k.min!==void 0){let O=Array.isArray(_)?_.length:typeof _==="string"?_.length:typeof _==="number"?_:0;if(O<k.min)d.push({path:j,message:k.message||`Value must be at least ${k.min}`,expected:`>= ${k.min}`,actual:O,rule:"min"})}if(k.max!==void 0){let O=Array.isArray(_)?_.length:typeof _==="string"?_.length:typeof _==="number"?_:0;if(O>k.max)d.push({path:j,message:k.message||`Value must not exceed ${k.max}`,expected:`<= ${k.max}`,actual:O,rule:"max"})}if(k.pattern&&typeof _==="string"){if(!k.pattern.test(_))d.push({path:j,message:k.message||`Value does not match pattern ${k.pattern}`,expected:k.pattern.toString(),actual:_,rule:"pattern"})}if(k.enum&&!k.enum.includes(_))d.push({path:j,message:k.message||`Value must be one of: ${k.enum.join(", ")}`,expected:k.enum.join(", "),actual:_,rule:"enum"});if(k.validator){let O=k.validator(_);if(O)d.push({path:j,message:k.message||O,rule:"custom"})}return d}getValueByPath(_,k){if(!k)return _;let j=k.split("."),d=_;for(let O of j)if(d&&typeof d==="object"&&O in d)d=d[O];else return;return d}generateRulesFromInterface(_){let k=[],j=_.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let d of j){let[,O,$,Z]=d;k.push({path:O,required:!$,type:this.mapTypeScriptType(Z)})}return k}mapTypeScriptType(_){switch(_.toLowerCase()){case"string":return"string";case"number":return"number";case"boolean":return"boolean";case"array":return"array";case"object":return"object";default:return"object"}}static createCommonRules(){return{server:[{path:"port",required:!0,type:"number",min:1,max:65535},{path:"host",required:!0,type:"string",min:1},{path:"ssl",type:"boolean"}],database:[{path:"url",required:!0,type:"string",min:1},{path:"pool",type:"number",min:1,max:100},{path:"timeout",type:"number",min:0}],api:[{path:"baseUrl",required:!0,type:"string",pattern:RZ},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}function DY(_){if(!_)return"";let k=Array.isArray(_)?_.filter(Boolean):[_];if(k.length===0)return"";if(k.length===1)return` or alias "${k[0]}"`;return` or aliases ${k.map((j)=>`"${j}"`).join(", ")}`}class TZ{fileLoader=new QZ;envProcessor=new i8;validator=new VZ;async loadConfig(_){let k=Date.now(),{cache:j,performance:d,schema:O,validate:$,...Z}=_;try{if(j?.enabled){let E=this.checkCache(Z.name||"",Z);if(E)return E}let X;try{X=await this.loadConfigurationStrategies(Z,!0,j)}catch(E){let F=Z.__strictErrorHandling;if(E instanceof Error&&E.name==="ConfigNotFoundError"){if(F)throw E;X={...await this.applyEnvironmentVariables(Z.name||"",Z.defaultConfig,Z.checkEnv!==!1,Z.verbose||!1),warnings:[`No configuration file found for "${Z.name||"config"}", using defaults with environment variables`]}}else if(E instanceof Error&&E.name==="ConfigLoadError"){let G=E.message.includes("EACCES")||E.message.includes("EPERM")||E.message.includes("permission denied"),Y=!G&&(E.message.includes("syntax")||E.message.includes("Expected")||E.message.includes("Unexpected")||E.message.includes("BuildMessage")||E.message.includes("errors building")),S=E.message.includes("Configuration must export a valid object")||E.message.includes("Configuration file is empty and exports nothing");if(F&&(S||G))throw E;if(Y&&(!F||!S))X={...await this.applyEnvironmentVariables(Z.name||"",Z.defaultConfig,Z.checkEnv!==!1,Z.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!F)X={...await this.applyEnvironmentVariables(Z.name||"",Z.defaultConfig,Z.checkEnv!==!1,Z.verbose||!1),warnings:[`Configuration loading error, using defaults: ${E.message}`]};else throw E}else X={...await this.applyEnvironmentVariables(Z.name||"",Z.defaultConfig,Z.checkEnv!==!1,Z.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${E instanceof Error?E.message:String(E)}`]}}if(O||$)await this.validateConfiguration(X.config,O,$,Z.name);if(j?.enabled&&X)this.cacheResult(Z.name||"",X,j,Z);if(d?.enabled){let E={operation:"loadConfig",duration:Date.now()-k,configName:Z.name,timestamp:new Date};if(d.onMetrics)d.onMetrics(E);if(d.slowThreshold&&E.duration>d.slowThreshold)Qk.warn(`Slow configuration loading detected: ${E.duration}ms for ${Z.name}`);X.metrics=E}return X}catch(X){if(X instanceof Error&&X.name==="ConfigNotFoundError")throw X;let E=Date.now()-k;throw Qk.error(`Configuration loading failed after ${E}ms:`,[X instanceof Error?X:Error(String(X))]),X}}async loadConfigurationStrategies(_,k=!1,j){let{name:d="",alias:O,cwd:$,configDir:Z,defaultConfig:X,checkEnv:E=!0,arrayStrategy:F="replace",verbose:G=!1}=_,Y=$||fO.cwd(),S=[],z=await this.loadLocalConfiguration(d,O,Y,Z,X,F,G,E,j);if(z)return S.push(...this.getLocalSearchPaths(d,O,Y,Z)),this.finalizeResult(z,S,E,d,G);let U=await this.loadHomeConfiguration(d,O,X,F,G,E);if(U)return S.push(...this.getHomeSearchPaths(d,O)),this.finalizeResult(U,S,E,d,G);let Q=await this.loadPackageJsonConfiguration(d,O,Y,X,F,G,E);if(Q)return S.push(Zk(Y,"package.json")),this.finalizeResult(Q,S,E,d,G);if(S.push(...this.getAllSearchPaths(d,O,Y,Z)),k)throw Ej.configNotFound(d,S,O);return{...await this.applyEnvironmentVariables(d,X,E,G),warnings:[`No configuration file found for "${d}"${DY(O)}, using defaults with environment variables`]}}async loadLocalConfiguration(_,k,j,d,O,$,Z,X,E){let F=X?td(_,O,Z):O,G=this.getLocalDirectories(j,d);for(let Y of G){if(Z)Qk.info(`Searching for configuration in: ${Y}`);let S=this.fileLoader.generateConfigPaths(_,Y,k),z=await this.fileLoader.tryLoadFromPaths(S,F,{arrayStrategy:$,verbose:Z,cacheTtl:E?.ttl,useCache:!E?.ttl||E.ttl>100});if(z){if(Z)Qk.success(`Configuration loaded from: ${z.source.path}`);return z}}return null}async loadHomeConfiguration(_,k,j,d,O,$){if(!_)return null;let Z=$?td(_,j,O):j,X=[Zk(Vj(),".config",_),Zk(Vj(),".config"),Vj()];for(let E of X){if(O)Qk.info(`Checking home directory: ${E}`);let F=this.fileLoader.generateConfigPaths(_,E,k),G=await this.fileLoader.tryLoadFromPaths(F,Z,{arrayStrategy:d,verbose:O});if(G){if(O)Qk.success(`Configuration loaded from home directory: ${G.source.path}`);return G}}return null}async loadPackageJsonConfiguration(_,k,j,d,O,$,Z){let X=Z?td(_,d,$):d;try{let E=Zk(j,"package.json");if(!dS(E))return null;let F={};try{F=JSON.parse(OS(E,"utf8"))}catch(S){if($)Qk.warn("Failed to parse package.json:",[S instanceof Error?S:Error(String(S))]);return null}let G=F[_],Y=_;if(!G&&k){let S=Array.isArray(k)?k:[k];for(let z of S){if(!z)continue;if(F[z]){G=F[z],Y=z;break}}}if(G&&typeof G==="object"&&!Array.isArray(G)){if($)Qk.success(`Configuration loaded from package.json: ${Y}`);return{config:UZ(X,G,O),source:{type:"package.json",path:E,priority:30,timestamp:new Date}}}}catch(E){if($)Qk.warn("Failed to load package.json:",[E instanceof Error?E:Error(String(E))])}return null}async applyEnvironmentVariables(_,k,j,d){if(!j||!_||typeof k!=="object"||k===null||Array.isArray(k))return{config:k,source:{type:"default",priority:10,timestamp:new Date}};return{config:td(_,k,d),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(_,k,j,d,O){return{config:_.config,source:_.source,path:_.source.path}}async validateConfiguration(_,k,j,d){let O=[];if(j){let $=j(_);if($)O.push(...$)}if(k){let $=await this.validator.validateConfiguration(_,k);if(!$.isValid)O.push(...$.errors.map((Z)=>Z.path?`${Z.path}: ${Z.message}`:Z.message))}if(O.length>0)throw Ej.configValidation(d||"unknown",O,d)}checkCache(_,k){let j=this.generateCacheKey(_,k);return v1.get(j)||null}cacheResult(_,k,j,d){let O=this.generateCacheKey(_,d);v1.set(O,k,void 0,j.ttl)}generateCacheKey(_,k){let j=[_];if(k.alias){let d=Array.isArray(k.alias)?k.alias.join(","):k.alias;j.push(`alias:${d}`)}if(k.cwd)j.push(`cwd:${k.cwd}`);if(k.configDir)j.push(`configDir:${k.configDir}`);if("checkEnv"in k)j.push(`checkEnv:${k.checkEnv}`);return j.join("|")}getLocalDirectories(_,k){return Array.from(new Set([_,Zk(_,"config"),Zk(_,".config"),k?Zk(_,k):void 0].filter(Boolean)))}getAllSearchPaths(_,k,j,d){let O=[];return O.push(...this.getLocalSearchPaths(_,k,j,d)),O.push(...this.getHomeSearchPaths(_,k)),O.push(Zk(j,"package.json")),O}getLocalSearchPaths(_,k,j,d){let O=this.getLocalDirectories(j,d),$=[];for(let Z of O)$.push(...this.fileLoader.generateConfigPaths(_,Z,k));return $}getHomeSearchPaths(_,k){if(!_)return[];let j=[Zk(Vj(),".config",_),Zk(Vj(),".config"),Vj()],d=[];for(let O of j)d.push(...this.fileLoader.generateConfigPaths(_,O,k));return d}async loadConfigWithResult(_){return this.loadConfig(_)}}function td(_,k,j=!1){let d=new i8,O=_.toUpperCase().replace(/[^A-Z0-9]/g,"_");function $(Z,X=[]){let E={...Z};for(let[F,G]of Object.entries(Z)){let Y=[...X,F],S=[`${O}_${Y.join("_").toUpperCase()}`,`${O}_${Y.map((Q)=>Q.toUpperCase()).join("")}`,`${O}_${Y.map((Q)=>Q.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],z,U;for(let Q of S)if(z=fO.env[Q],z!==void 0){U=Q;break}if(z!==void 0&&U)if(typeof G==="boolean")E[F]=["true","1","yes"].includes(z.toLowerCase());else if(typeof G==="number"){let Q=Number(z);if(!Number.isNaN(Q))E[F]=Q}else if(Array.isArray(G))try{E[F]=JSON.parse(z)}catch{E[F]=z.split(",").map((Q)=>Q.trim())}else E[F]=z;else if(G&&typeof G==="object"&&!Array.isArray(G))E[F]=$(G,Y)}return E}return $(k)}var v1,Y0,WZ,RY=(_)=>_,wY=(_,k)=>{for(var j in k)WZ(_,j,{get:k[j],enumerable:!0,configurable:!0,set:gS.bind(k,j)})},MY=(_,k)=>()=>(_&&(k=_(_=0)),k),H9,KZ,Aj,A1,q2,CY,hY,H2,PO,U8,y_,Q_,fY,b2,qY,N2,HY,bY,b9,NY,x2,i2,N9,xY,iY,BY,cY,UO,nZ,yY,m_,vY,AY,B2,QO,Q8,f_,X_,mY,c2,gY,y2,uY,lY,x9,pY,v2,A2,sY,i9,oY,rY,tY,aY,eY,VO,JZ,_L,kL="0.15.6",e_,TO,V1,B9,c9,WO,y9,v9,T1,A9,m9,ak,m2,IZ,Pk,xk,g2,u2,l2,p2,g9,W1,jL,q_,E_,dL,s2,OL,o2,$L,ZL,u9,XL,r2,t2,EL,l9,GL,FL,zL,SL,YL,KO,DZ,LL,Yk,a2,vO,e2,_5,V8,k5,j5,AO,d5,O5,Ej,RZ,Qk,PL,UL,QL,VL=r(()=>{v1=new dZ,Y0=new OZ,WZ=Object.defineProperty,H9={},wY(H9,{withErrorRecovery:()=>XZ,tryLoadConfig:()=>YY,loadConfigWithResult:()=>zY,loadConfig:()=>SZ,isRetryableError:()=>$Y,isConfigNotFoundError:()=>OY,isBunfigError:()=>EZ,globalPerformanceMonitor:()=>A1,globalCache:()=>Aj,getEnvOrDefault:()=>ZY,generateConfigTypes:()=>LY,defaultGeneratedDir:()=>u2,defaultConfigDir:()=>g2,deepMergeWithArrayStrategy:()=>N8,deepMerge:()=>GZ,createLibraryConfig:()=>PY,config:()=>SY,bunfigPlugin:()=>UY,applyEnvVarsToConfig:()=>U1,TypeGenerationError:()=>v9,SchemaValidationError:()=>T1,PluginError:()=>m9,PerformanceMonitor:()=>S8,FileSystemError:()=>y9,ErrorFactory:()=>ak,EnvVarError:()=>WO,EnvProcessor:()=>z0,ConfigValidator:()=>x8,ConfigValidationError:()=>B9,ConfigNotFoundError:()=>TO,ConfigMergeError:()=>c9,ConfigLoader:()=>L8,ConfigLoadError:()=>V1,ConfigFileLoader:()=>S0,ConfigCache:()=>z8,CacheUtils:()=>q2,BunfigError:()=>e_,BrowserConfigError:()=>A9,ArrayMergeStrategies:()=>m2}),l2=MY(async()=>{KZ=import.meta.require,Aj=new z8,A1=new S8,q2={createKey:uS,isEquivalent:lS,estimateMemoryUsage:pS},CY=bO(F8.cwd(),"config"),hY=bO(F8.cwd(),"src/generated"),H2=HO.env.CLARITY_LOG_DIR||FS(rS(),"logs"),PO={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:H2,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},U8=await tS(),y_={red:(_)=>`\x1B[31m${_}\x1B[0m`,green:(_)=>`\x1B[32m${_}\x1B[0m`,yellow:(_)=>`\x1B[33m${_}\x1B[0m`,blue:(_)=>`\x1B[34m${_}\x1B[0m`,magenta:(_)=>`\x1B[35m${_}\x1B[0m`,cyan:(_)=>`\x1B[36m${_}\x1B[0m`,white:(_)=>`\x1B[37m${_}\x1B[0m`,gray:(_)=>`\x1B[90m${_}\x1B[0m`,bgRed:(_)=>`\x1B[41m${_}\x1B[0m`,bgYellow:(_)=>`\x1B[43m${_}\x1B[0m`,bold:(_)=>`\x1B[1m${_}\x1B[0m`,dim:(_)=>`\x1B[2m${_}\x1B[0m`,italic:(_)=>`\x1B[3m${_}\x1B[0m`,underline:(_)=>`\x1B[4m${_}\x1B[0m`,reset:"\x1B[0m"},Q_=y_,fY=y_.red,b2=y_.green,qY=y_.yellow,N2=y_.blue,HY=y_.magenta,bY=y_.cyan,b9=y_.white,NY=y_.gray,x2=y_.bgRed,i2=y_.bgYellow,N9=y_.bold,xY=y_.dim,iY=y_.italic,BY=y_.underline,cY=y_.reset,UO={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},nZ={debug:"\uD83D\uDD0D",info:N2("\u2139"),success:b2("\u2713"),warning:i2(b9(N9(" WARN "))),error:x2(b9(N9(" ERROR ")))},yY=new iO("stacks"),m_=new iO("bunfig",{showTags:!0}),vY=s_(y1.cwd(),"config"),AY=s_(y1.cwd(),"src/generated"),B2=qO.env.CLARITY_LOG_DIR||ES(kY(),"logs"),QO={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:B2,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},Q8=await jY(),f_={red:(_)=>`\x1B[31m${_}\x1B[0m`,green:(_)=>`\x1B[32m${_}\x1B[0m`,yellow:(_)=>`\x1B[33m${_}\x1B[0m`,blue:(_)=>`\x1B[34m${_}\x1B[0m`,magenta:(_)=>`\x1B[35m${_}\x1B[0m`,cyan:(_)=>`\x1B[36m${_}\x1B[0m`,white:(_)=>`\x1B[37m${_}\x1B[0m`,gray:(_)=>`\x1B[90m${_}\x1B[0m`,bgRed:(_)=>`\x1B[41m${_}\x1B[0m`,bgYellow:(_)=>`\x1B[43m${_}\x1B[0m`,bgGray:(_)=>`\x1B[100m${_}\x1B[0m`,bold:(_)=>`\x1B[1m${_}\x1B[0m`,dim:(_)=>`\x1B[2m${_}\x1B[0m`,italic:(_)=>`\x1B[3m${_}\x1B[0m`,underline:(_)=>`\x1B[4m${_}\x1B[0m`,strikethrough:(_)=>`\x1B[9m${_}\x1B[0m`,reset:"\x1B[0m"},X_=f_,mY=f_.red,c2=f_.green,gY=f_.yellow,y2=f_.blue,uY=f_.magenta,lY=f_.cyan,x9=f_.white,pY=f_.gray,v2=f_.bgRed,A2=f_.bgYellow,sY=f_.bgGray,i9=f_.bold,oY=f_.dim,rY=f_.italic,tY=f_.underline,aY=f_.strikethrough,eY=f_.reset,VO={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},JZ={debug:"\uD83D\uDD0D",info:y2("\u2139"),success:c2("\u2713"),warning:A2(x9(i9(" WARN "))),error:v2(x9(i9(" ERROR ")))},_L=new cO("stacks"),e_=class extends Error{timestamp;context;constructor(k,j={}){super(k);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=j,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,timestamp:this.timestamp.toISOString(),context:this.context,stack:this.stack}}toString(){let k=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([j,d])=>`${j}: ${d}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${k}`}},TO=class extends e_{code="CONFIG_NOT_FOUND";constructor(k,j,d){let O=d?` or alias "${d}"`:"";super(`Configuration "${k}"${O} not found`,{configName:k,alias:d,searchPaths:j,searchPathCount:j.length})}},V1=class extends e_{code="CONFIG_LOAD_ERROR";constructor(k,j,d){super(`Failed to load configuration from "${k}": ${j.message}`,{configPath:k,configName:d,originalError:j.name,originalMessage:j.message});this.cause=j}},B9=class extends e_{code="CONFIG_VALIDATION_ERROR";constructor(k,j,d){super(`Configuration validation failed for "${k}"`,{configPath:k,configName:d,validationErrors:j,errorCount:j.length})}},c9=class extends e_{code="CONFIG_MERGE_ERROR";constructor(k,j,d,O){super(`Failed to merge configuration from "${k}" with "${j}": ${d.message}`,{sourcePath:k,targetPath:j,configName:O,originalError:d.name,originalMessage:d.message});this.cause=d}},WO=class extends e_{code="ENV_VAR_ERROR";constructor(k,j,d,O){super(`Failed to parse environment variable "${k}" with value "${j}" as ${d}`,{envKey:k,envValue:j,expectedType:d,configName:O})}},y9=class extends e_{code="FILE_SYSTEM_ERROR";constructor(k,j,d){super(`File system ${k} failed for "${j}": ${d.message}`,{operation:k,path:j,originalError:d.name,originalMessage:d.message});this.cause=d}},v9=class extends e_{code="TYPE_GENERATION_ERROR";constructor(k,j,d){super(`Failed to generate types from "${k}" to "${j}": ${d.message}`,{configDir:k,outputPath:j,originalError:d.name,originalMessage:d.message});this.cause=d}},T1=class extends e_{code="SCHEMA_VALIDATION_ERROR";constructor(k,j,d){super(`Schema validation failed${d?` for config "${d}"`:""}`,{schemaPath:k,configName:d,validationErrors:j,errorCount:j.length})}},A9=class extends e_{code="BROWSER_CONFIG_ERROR";constructor(k,j,d,O){super(`Failed to fetch configuration from "${k}": ${j} ${d}`,{endpoint:k,status:j,statusText:d,configName:O})}},m9=class extends e_{code="PLUGIN_ERROR";constructor(k,j,d){super(`Plugin "${k}" failed during ${j}: ${d.message}`,{pluginName:k,operation:j,originalError:d.name,originalMessage:d.message});this.cause=d}},ak={configNotFound(_,k,j){return new TO(_,k,j)},configLoad(_,k,j){return new V1(_,k,j)},configValidation(_,k,j){return new B9(_,k,j)},configMerge(_,k,j,d){return new c9(_,k,j,d)},envVar(_,k,j,d){return new WO(_,k,j,d)},fileSystem(_,k,j){return new y9(_,k,j)},typeGeneration(_,k,j){return new v9(_,k,j)},schemaValidation(_,k,j){return new T1(_,k,j)},browserConfig(_,k,j,d){return new A9(_,k,j,d)},plugin(_,k,j){return new m9(_,k,j)}},m2={replace:"replace",concat:"concat",smart:"smart"},IZ=/^https?:\/\//,Pk=new cO("bunfig",{showTags:!0}),xk=new L8,g2=r_(Xj.cwd(),"config"),u2=r_(Xj.cwd(),"src/generated")}),p2=NO.env.CLARITY_LOG_DIR||qS(QY(),"logs"),g9={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:p2,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},W1={...g9},jL=(async()=>{try{let{loadConfig:_}=await l2().then(()=>H9),k=await _({name:"clarity",alias:"logging",defaultConfig:g9,cwd:NO.cwd()});if(k)Object.assign(W1,k)}catch{}return W1})(),q_={red:(_)=>`\x1B[31m${_}\x1B[0m`,green:(_)=>`\x1B[32m${_}\x1B[0m`,yellow:(_)=>`\x1B[33m${_}\x1B[0m`,blue:(_)=>`\x1B[34m${_}\x1B[0m`,magenta:(_)=>`\x1B[35m${_}\x1B[0m`,cyan:(_)=>`\x1B[36m${_}\x1B[0m`,white:(_)=>`\x1B[37m${_}\x1B[0m`,gray:(_)=>`\x1B[90m${_}\x1B[0m`,bgRed:(_)=>`\x1B[41m${_}\x1B[0m`,bgYellow:(_)=>`\x1B[43m${_}\x1B[0m`,bgGray:(_)=>`\x1B[100m${_}\x1B[0m`,bold:(_)=>`\x1B[1m${_}\x1B[0m`,dim:(_)=>`\x1B[2m${_}\x1B[0m`,italic:(_)=>`\x1B[3m${_}\x1B[0m`,underline:(_)=>`\x1B[4m${_}\x1B[0m`,strikethrough:(_)=>`\x1B[9m${_}\x1B[0m`,reset:"\x1B[0m"},E_=q_,dL=q_.red,s2=q_.green,OL=q_.yellow,o2=q_.blue,$L=q_.magenta,ZL=q_.cyan,u9=q_.white,XL=q_.gray,r2=q_.bgRed,t2=q_.bgYellow,EL=q_.bgGray,l9=q_.bold,GL=q_.dim,FL=q_.italic,zL=q_.underline,SL=q_.strikethrough,YL=q_.reset,KO={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},DZ={debug:"\uD83D\uDD0D",info:o2("\u2139"),success:s2("\u2713"),warning:t2(u9(l9(" WARN "))),error:r2(u9(l9(" ERROR ")))},LL=new yO("stacks"),Yk=class extends Error{timestamp;context;constructor(k,j={}){super(k);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=j,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,timestamp:this.timestamp.toISOString(),context:this.context,stack:this.stack}}toString(){let k=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([j,d])=>`${j}: ${d}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${k}`}},a2=class extends Yk{code="CONFIG_NOT_FOUND";constructor(k,j,d){let O=d===void 0?[]:Array.isArray(d)?d.filter(Boolean):[d],$="";if(O.length===1)$=` or alias "${O[0]}"`;else if(O.length>1)$=` or aliases ${O.map((Z)=>`"${Z}"`).join(", ")}`;super(`Configuration "${k}"${$} not found`,{configName:k,alias:d,searchPaths:j,searchPathCount:j.length})}},vO=class extends Yk{code="CONFIG_LOAD_ERROR";constructor(k,j,d){super(`Failed to load configuration from "${k}": ${j.message}`,{configPath:k,configName:d,originalError:j.name,originalMessage:j.message});this.cause=j}},e2=class extends Yk{code="CONFIG_VALIDATION_ERROR";constructor(k,j,d){super(`Configuration validation failed for "${k}"`,{configPath:k,configName:d,validationErrors:j,errorCount:j.length})}},_5=class extends Yk{code="CONFIG_MERGE_ERROR";constructor(k,j,d,O){super(`Failed to merge configuration from "${k}" with "${j}": ${d.message}`,{sourcePath:k,targetPath:j,configName:O,originalError:d.name,originalMessage:d.message});this.cause=d}},V8=class extends Yk{code="ENV_VAR_ERROR";constructor(k,j,d,O){super(`Failed to parse environment variable "${k}" with value "${j}" as ${d}`,{envKey:k,envValue:j,expectedType:d,configName:O})}},k5=class extends Yk{code="FILE_SYSTEM_ERROR";constructor(k,j,d){super(`File system ${k} failed for "${j}": ${d.message}`,{operation:k,path:j,originalError:d.name,originalMessage:d.message});this.cause=d}},j5=class extends Yk{code="TYPE_GENERATION_ERROR";constructor(k,j,d){super(`Failed to generate types from "${k}" to "${j}": ${d.message}`,{configDir:k,outputPath:j,originalError:d.name,originalMessage:d.message});this.cause=d}},AO=class extends Yk{code="SCHEMA_VALIDATION_ERROR";constructor(k,j,d){super(`Schema validation failed${d?` for config "${d}"`:""}`,{schemaPath:k,configName:d,validationErrors:j,errorCount:j.length})}},d5=class extends Yk{code="BROWSER_CONFIG_ERROR";constructor(k,j,d,O){super(`Failed to fetch configuration from "${k}": ${j} ${d}`,{endpoint:k,status:j,statusText:d,configName:O})}},O5=class extends Yk{code="PLUGIN_ERROR";constructor(k,j,d){super(`Plugin "${k}" failed during ${j}: ${d.message}`,{pluginName:k,operation:j,originalError:d.name,originalMessage:d.message});this.cause=d}},Ej={configNotFound(_,k,j){return new a2(_,k,j)},configLoad(_,k,j){return new vO(_,k,j)},configValidation(_,k,j){return new e2(_,k,j)},configMerge(_,k,j,d){return new _5(_,k,j,d)},envVar(_,k,j,d){return new V8(_,k,j,d)},fileSystem(_,k,j){return new k5(_,k,j)},typeGeneration(_,k,j){return new j5(_,k,j)},schemaValidation(_,k,j){return new AO(_,k,j)},browserConfig(_,k,j,d){return new d5(_,k,j,d)},plugin(_,k,j){return new O5(_,k,j)}},RZ=/^https?:\/\//,Qk=new yO("bunfig",{showTags:!0}),PL=new TZ,UL=Zk(fO.cwd(),"config"),QL=Zk(fO.cwd(),"src/generated")});function p(_){if(c.dialect==="postgres")return`$${_}`;return"?"}function p_(_,k=1){if(c.dialect==="postgres")return Array.from({length:_},(j,d)=>`$${k+d}`).join(", ");return Array.from({length:_},()=>"?").join(", ")}var $5,c;var Wk=r(()=>{VL(),$5={verbose:!0,dialect:"postgres",database:{database:"test_db",username:"postgres",password:"postgres",host:"localhost",port:5432},timestamps:{createdAt:"created_at",updatedAt:"updated_at",defaultOrderColumn:"created_at"},pagination:{defaultPerPage:25,cursorColumn:"id"},aliasing:{relationColumnAliasFormat:"table_column"},relations:{foreignKeyFormat:"singularParent_id",maxDepth:10,maxEagerLoad:50,detectCycles:!0},transactionDefaults:{retries:2,isolation:"read committed",sqlStates:["40001","40P01"],backoff:{baseMs:50,factor:2,maxMs:2000,jitter:!0}},sql:{randomFunction:"RANDOM()",sharedLockSyntax:"FOR SHARE",jsonContainsMode:"operator"},features:{distinctOn:!0},debug:{captureText:!0},hooks:{},softDeletes:{enabled:!1,column:"deleted_at",defaultFilter:!0}},c={...$5}}),{SQL:TL}=globalThis.Bun;class wZ{db;constructor(_){this.db=new WL(_),this.db.run("PRAGMA journal_mode = WAL")}query(_,k=[]){return this.db.prepare(_).all(...k)}run(_,k=[]){return this.db.prepare(_).run(...k)}close(){this.db.close()}get database(){return this.db}}function Z5(_){return{__raw:!0,value:_,toString:()=>_}}function KL(_){let k=[],j="",d=!1,O=!1,$=!1,Z=!1;for(let E=0;E<_.length;E++){let F=_[E],G=_[E+1];if(!d&&!O&&!Z&&F==="-"&&G==="-"){$=!0,j+=F;continue}if($&&(F===`
|
|
72
|
-
`||F==="\r")){$=!1,j+=F;continue}if(!d&&!O&&!$&&F==="/"&&G==="*"){Z=!0,j+=F;continue}if(Z&&F==="*"&&G==="/"){Z=!1,j+=F+G,E++;continue}if($||Z){j+=F;continue}if(F==="'"&&!O){if(d&&G==="'"){j+=F+G,E++;continue}d=!d,j+=F;continue}if(F==='"'&&!d){O=!O,j+=F;continue}if(F===";"&&!d&&!O){let Y=j.trim();if(Y&&!Y.startsWith("--"))k.push(Y);j="";continue}j+=F}let X=j.trim();if(X&&!X.startsWith("--"))k.push(X);return k}function X5(_){let k=new wZ(_);function j(O,...$){let Z=O[0],X=[];for(let E=0;E<$.length;E++){let F=$[E];if(F&&typeof F==="object"&&(F.__raw||F.raw)){let G=F.__raw?F.value:typeof F.raw==="string"?F.raw:F.raw();Z+=G+(O[E+1]||"")}else if(F&&typeof F==="object"&&"sql"in F&&"values"in F)Z+=F.sql+(O[E+1]||""),X.push(...F.values);else if(Array.isArray(F)){let G=F.map(()=>"?").join(", ");Z+=G+(O[E+1]||""),X.push(...F)}else Z+=`?${O[E+1]||""}`,X.push(F)}return{sql:Z,values:X,execute:()=>{try{let E=Z.trim().toUpperCase();if(E.startsWith("SELECT")||E.startsWith("PRAGMA")){let F=k.query(Z,X);return Promise.resolve(F)}else{let F=k.run(Z,X);return Promise.resolve(F)}}catch(E){return Promise.reject(E)}},raw:()=>Z,toString:()=>Z,cancel:()=>{}}}function d(O,...$){if(Array.isArray(O)&&"raw"in O)return j(O,...$);if(typeof O==="string")return Z5(O);return j([""])}return d.raw=(O)=>Z5(O),d.unsafe=(O,$=[])=>{return{sql:O,values:$,execute:()=>{try{let Z=O.trim().toUpperCase();if(Z.startsWith("SELECT")||Z.startsWith("PRAGMA")){let X=k.query(O,$);return Promise.resolve(X)}else{let X=k.run(O,$);return Promise.resolve(X)}}catch(Z){return Promise.reject(Z)}},raw:()=>O,toString:()=>O,cancel:()=>{}}},d.close=()=>{return k.close(),Promise.resolve()},d.query=(O,$)=>{try{let Z=k.query(O,$||[]);return Promise.resolve(Z)}catch(Z){return Promise.reject(Z)}},d.file=async(O,$)=>{try{let{readFileSync:Z}=await import("fs"),X=Z(O,"utf-8"),E=KL(X);for(let F of E){let G=F.trim();if(!G||G.startsWith("--"))continue;let Y=G.toUpperCase();if(Y.startsWith("SELECT")||Y.startsWith("PRAGMA"))k.query(F);else k.run(F)}return Promise.resolve([])}catch(Z){return Promise.reject(Z)}},d._wrapper=k,d}function nL(_,k){if(k.url)return k.url;let{database:j,username:d,password:O,host:$="localhost",port:Z}=k;switch(_){case"postgres":return`postgres://${d}:${O}@${$}${Z?`:${Z}`:""}/${j}`;case"mysql":return`mysql://${d}:${O}@${$}${Z?`:${Z}`:""}/${j}`;case"sqlite":if(j===":memory:")return":memory:";return j||":memory:";default:throw Error(`Unsupported dialect: ${_}`)}}function JL(){let _=c.dialect,k=nL(_,c.database);try{if(_==="sqlite")return X5(k);let j=new TL(k);if(j&&typeof j.catch==="function")j.catch((d)=>{if(c.verbose&&!d.message.includes("database")&&!d.message.includes("does not exist"))console.warn(`[query-builder] Database connection error: ${d.message}`)});return j}catch(j){if(c.verbose)console.warn(`[query-builder] Failed to create connection: ${j.message}`);try{return X5(":memory:")}catch{return{query:()=>Promise.resolve([]),execute:()=>Promise.resolve([]),close:()=>Promise.resolve()}}}}function m1(_=!1){let k=ed!==null&&(E5!==c.dialect||G5!==c.database.database);if(_||k||!ed)ed=JL(),E5=c.dialect,G5=c.database.database;return ed}async function p9(_){try{return await _(m1())}catch(k){if(k?.code==="ERR_POSTGRES_CONNECTION_CLOSED"||k?.message?.includes("Connection closed")){console.log("-- Connection closed, creating fresh connection...");let j=m1(!0);return await _(j)}throw k}}function IL(){return new Proxy({},{get(_,k){let j=m1(),d=j[k];if(typeof d==="function")return d.bind(j);return d},apply(_,k,j){return m1()(...j)}})}var ed=null,E5=null,G5=null,v,mj=r(()=>{if(Wk(),v=IL(),typeof ad<"u"&&ad.on){if(!ad.listeners("unhandledRejection").find((k)=>k.name==="sqlConnectionErrorHandler")){let k=function(j){if(j&&(j.message?.includes("database")||j.message?.includes("does not exist")||j.code==="ERR_POSTGRES_SERVER_ERROR"||j.code==="3D000"));};Object.defineProperty(k,"name",{value:"sqlConnectionErrorHandler"}),ad.on("unhandledRejection",k)}}});var DL=r(()=>{mj(),i_()});function RL(_){return _.endsWith("s")?_.slice(0,-1):_}function _O(_,k,j,d={}){let O=d.singularize??RL,Z=_.relations?.[k]?.belongsToMany?.[j];if(Z==null)return null;let X=typeof Z==="object",E=X?Z:null,F=X?E.model:Z,G=_.modelToTable[F]||F,Y,S;if(E?.table)Y=E.table;else if(E?.through){if(S=E.through,Y=_.modelToTable[E.through],!Y)throw Error(`[query-builder] belongsToMany relation '${j}' on '${k}' references unknown through model '${E.through}'. Make sure '${E.through}' is registered via defineModels({...}).`)}else{let W=O(k),J=O(G);Y=[W,J].sort().join("_")}let z=E?.foreignKey??`${O(k)}_id`,U=E?.relatedKey??`${O(G)}_id`,Q={};if(E?.pivot?.columns)Object.assign(Q,E.pivot.columns);if(S&&d.models){let W=d.models[S],J=W?.definition??W?.getDefinition?.()??W,C=J?.attributes??{};for(let[f,N]of Object.entries(C)){if(f===z||f===U||f===(J?.primaryKey??"id"))continue;Q[f]={default:N?.default,nullable:N?.nullable,validation:N?.validation}}}let I=Boolean(E?.pivot?.timestamps),T=Object.keys(Q);return{pivotTable:Y,fkParent:z,fkRelated:U,pivotColumns:T,pivotColumnDefs:Q,pivotModelName:S,timestamps:I,relatedModelName:F,relatedTable:G,hasConfig:X}}function F5(_){return typeof _==="object"&&_!==null&&"raw"in _&&typeof _.raw==="string"}class MZ{cache=new Map;maxSize=100;get(_){let k=this.cache.get(_);if(!k)return null;if(Date.now()>k.expiresAt)return this.cache.delete(_),null;return k.data}set(_,k,j){if(this.cache.size>=this.maxSize){let d=this.cache.keys().next().value;if(d)this.cache.delete(d)}this.cache.set(_,{data:k,expiresAt:Date.now()+j})}clear(){this.cache.clear()}setMaxSize(_){this.maxSize=_}}function wL(_){let k=String(_?.message||"").toLowerCase();return k.includes("deadlock")||k.includes("serialization failure")||k.includes("could not serialize access")||k.includes("deadlock found when trying to get lock")||k.includes("lock wait timeout exceeded")||k.includes("database is locked")||k.includes("busy")}function ML(_,k){if(!k||k.length===0)return!1;let j=_&&(_.code||_.sqlState||_.sqlstate);if(!j)return!1;return k.includes(j)}function CL(_){return new Promise((k)=>setTimeout(k,_))}function hL(_,k){let j=Math.max(1,k?.baseMs??50),d=Math.max(1,k?.factor??2),O=Math.max(j,k?.maxMs??2000),$=Math.min(O,j*d**Math.max(0,_-1));if(k?.jitter){let Z=Math.random()*$*0.2;$=$-Z/2}return Math.floor($)}function Q1(_){let k=_?.sql??m1(),j=_?.meta,d=_?.schema;function O(G){if(Array.isArray(G)){let[Q,I,T]=G,W=String(Q);switch(I){case"in":if(Array.isArray(T)){let J=p_(T.length);return k.unsafe(`${W} IN (${J})`,T)}return k.unsafe(`${W} IN (${p(1)})`,[T]);case"not in":if(Array.isArray(T)){let J=p_(T.length);return k.unsafe(`${W} NOT IN (${J})`,T)}return k.unsafe(`${W} NOT IN (${p(1)})`,[T]);case"like":return k.unsafe(`${W} LIKE ${p(1)}`,[T]);case"is":return k.unsafe(`${W} IS ${T}`);case"is not":return k.unsafe(`${W} IS NOT ${T}`);case"!=":return k.unsafe(`${W} <> ${p(1)}`,[T]);case"<":case">":case"<=":case">=":case"=":default:return k.unsafe(`${W} ${I} ${p(1)}`,[T])}}if("raw"in G)return G.raw;let Y=Object.keys(G);if(Y.length===0)return k.unsafe("");let S=[],z=[],U=1;for(let Q of Y){let I=G[Q];if(Array.isArray(I)){let T=p_(I.length,U);S.push(`${Q} IN (${T})`),z.push(...I),U+=I.length}else S.push(`${Q} = ${p(U++)}`),z.push(I)}return k.unsafe(S.join(" AND "),z)}function $(G,Y,S){if(!S)return Y;let z=O(S);return k`${Y} WHERE ${z}`}function Z(G){let Y=c.debug?.captureText;if(c.debug)c.debug.captureText=!0;let S=String(G);if(c.debug)c.debug.captureText=Y;return S}function X(G,Y,S){let z=c.hooks,U=z&&(z.onQueryStart||z.onQueryEnd||z.onQueryError||z.startSpan),Q=S?.timeoutMs&&S.timeoutMs>0||S?.signal;if(!U&&!Q)return G.execute();let I=Z(G),T=Date.now(),W;try{if(z?.onQueryStart?.({sql:I,kind:Y}),z?.startSpan)W=z.startSpan({sql:I,kind:Y})}catch{}let J=!1,C=(B,A)=>{if(J)return;J=!0;let g=Date.now()-T;try{if(B)z?.onQueryError?.({sql:I,error:B,durationMs:g,kind:Y});else z?.onQueryEnd?.({sql:I,durationMs:g,rowCount:A,kind:Y})}catch{}try{W?.end(B)}catch{}},f=G.execute(),N=[f],y;if(S?.timeoutMs&&S.timeoutMs>0){let B=new Promise((A,g)=>{y=setTimeout(()=>{try{G.cancel?.()}catch{}let j_=Error(`Query timed out after ${S.timeoutMs}ms`);j_.code="EBQBTIMEOUT",g(j_)},S.timeoutMs)});N.push(B)}if(S?.signal){if(S.signal.aborted){try{G.cancel?.()}catch{}let A=Error("Query aborted");return A.code="EBQBABORT",C(A),Promise.reject(A)}let B=()=>{try{G.cancel?.()}catch{}};S.signal.addEventListener("abort",B,{once:!0}),f.finally(()=>{S.signal?.removeEventListener("abort",B)})}return Promise.race(N).then((B)=>{clearTimeout(y);let A=Array.isArray(B)?B.length:typeof B==="number"?B:void 0;return C(void 0,A),B}).catch((B)=>{throw clearTimeout(y),C(B),B})}function E(G,Y){let S=Y??Z(G);return{sql:S,toString:()=>S,execute:()=>G.execute(),values:()=>G.values(),raw:()=>G.raw()}}function F(G,Y){let S=k,z=Y&&Y.length>0?`SELECT ${Y.join(", ")} FROM ${String(G)}`:`SELECT * FROM ${String(G)}`,U=null,Q=()=>{if(U===null)U=x.length>0?k.unsafe(z,x):k.unsafe(z);return U},I=(L,V)=>{let n=l.WHERE.test(z)?L:"WHERE";z=`${z} ${n} ${V}`},T=new Set,W,J,C=!1,f=!1,N=!1,y=new Map,B=new Set,A=60000,g=(L)=>{if(c.relations.singularizeStrategy==="none")return L;return L.endsWith("s")?L.slice(0,-1):L},j_=(L)=>{if(!j)return null;return _O(j,String(G),L,{singularize:g,models:j.models})},a_=(L)=>{if(!L||typeof L!=="object"||B.size===0)return L;let V;for(let K of Object.keys(L))if(K.startsWith("pivot_")){if(!V)V={};V[K.slice(6)]=L[K],delete L[K]}if(V)L.pivot=V;return L},Ik=(L)=>{if(B.size===0||!L)return L;if(Array.isArray(L))for(let V=0;V<L.length;V++)a_(L[V]);else a_(L);return L},gk=(L)=>{if(!j)return;if(T.has(L.pivotTable))return;let V=String(G),K=j.primaryKeys[V]??"id";o(L.pivotTable,"wherePivot auto-join (pivot table)"),o(L.fkParent,"wherePivot auto-join (parent FK)"),o(V,"wherePivot auto-join (parent table)"),o(K,"wherePivot auto-join (parent PK)"),U=S`${Q()} LEFT JOIN ${S(L.pivotTable)} ON ${S(`${L.pivotTable}.${L.fkParent}`)} = ${S(`${V}.${K}`)}`,z=`${z} LEFT JOIN ${L.pivotTable} ON ${L.pivotTable}.${L.fkParent} = ${V}.${K}`,T.add(L.pivotTable)},T_=[],x=[],o=(L,V)=>{if(!l.IDENTIFIER.test(L)){let K=V?` in ${V}`:"";throw Error(`[query-builder] Invalid identifier${K}: '${L}'. Identifiers must start with a letter or underscore and contain only alphanumeric characters, underscores, and dots.`)}},$9=(L)=>{if(l.SELECT_STAR.test(z))z=z.replace(l.SELECT_STAR,`SELECT *, ${L}`);else if(l.SELECT.test(z))z=z.replace(l.SELECT_FROM,`SELECT $1, ${L} FROM`);let V=String(Q());if(l.SELECT_STAR.test(V)){let K=V.replace(l.SELECT_STAR,`SELECT *, ${L}`);U=k.unsafe(K)}else if(l.SELECT.test(V)){if(l.SELECT_FROM.exec(V)){let n=V.replace(l.SELECT_FROM,`SELECT $1, ${L} FROM`);U=k.unsafe(n)}}},Md=(L,V,K,n)=>{o(L,"relationship subquery (parent table)"),o(V,"relationship subquery (target table)"),o(K,"relationship subquery (primary key)");let D=`${L.endsWith("s")?L.slice(0,-1):L}_id`;o(D,"relationship subquery (foreign key)");let w=`SELECT 1 FROM ${V} WHERE ${V}.${D} = ${L}.${K}`;if(n){let q=n({where:(i,h,b)=>{return o(i,"relationship subquery condition"),`${V}.${i} ${h} ${typeof b==="string"?`'${b}'`:b}`}});if(q)w+=` AND ${q}`}return w},Cd=(L,V,K,n)=>{o(L,"relationship subquery (parent table)"),o(V,"relationship subquery (target table)"),o(K,"relationship subquery (primary key)");let D=`${V.endsWith("s")?V.slice(0,-1):V}_id`;o(D,"relationship subquery (foreign key)");let w=`SELECT 1 FROM ${V} WHERE ${V}.${K} = ${L}.${D}`;if(n){let q=n({where:(i,h,b)=>{return o(i,"relationship subquery condition"),`${V}.${i} ${h} ${typeof b==="string"?`'${b}'`:b}`}});if(q)w+=` AND ${q}`}return w},hd=(L,V,K,n,D,w)=>{o(L,"relationship subquery (parent table)"),o(V,"relationship subquery (target table)"),o(K,"relationship subquery (primary key)"),o(n,"relationship subquery (target primary key)");let H=w&&j?_O(j,L,w,{singularize:g,models:j.models}):null,q=g(L),i=g(V),h=H?.pivotTable??[q,i].sort().join("_"),b=H?.fkParent??`${q}_id`,u=H?.fkRelated??`${i}_id`;o(h,"relationship subquery (pivot table)"),o(b,"relationship subquery (foreign key A)"),o(u,"relationship subquery (foreign key B)");let a=`SELECT 1 FROM ${h} JOIN ${V} ON ${V}.${n} = ${h}.${u} WHERE ${h}.${b} = ${L}.${K}`;if(D){let e=D({where:(uk,E1,Zj)=>{return o(uk,"relationship subquery condition"),`${V}.${uk} ${E1} ${typeof Zj==="string"?`'${Zj}'`:Zj}`}});if(e)a+=` AND ${e}`}return a},Lz=(L,V,K)=>{o(L,"withCount (parent table)"),o(V,"withCount (target table)"),o(K,"withCount (primary key)");let n=`${L.endsWith("s")?L.slice(0,-1):L}_id`;return o(n,"withCount (foreign key)"),`(SELECT COUNT(*) FROM ${V} WHERE ${V}.${n} = ${L}.${K})`},Pz=(L,V,K,n)=>{o(L,"withCount (parent table)"),o(V,"withCount (target table)"),o(K,"withCount (primary key)");let D=n&&j?_O(j,L,n,{singularize:g,models:j.models}):null,w=g(L),H=g(V),q=D?.pivotTable??[w,H].sort().join("_"),i=D?.fkParent??`${w}_id`;return o(q,"withCount (pivot table)"),o(i,"withCount (foreign key)"),`(SELECT COUNT(*) FROM ${q} WHERE ${q}.${i} = ${L}.${K})`},c$=()=>{if(y.size===0)return;let L=[];for(let[V,K]of y.entries()){let n=j_(V);if(!n)continue;for(let w of K)o(w,"withPivot");let D=K.map((w)=>`${n.pivotTable}.${w} AS pivot_${w}`);L.push(...D)}if(L.length>0){let V=L.join(", ");$9(V)}};return new Proxy({distinct(){return z=z.replace(/^SELECT\s+/i,"SELECT DISTINCT "),U=null,this},distinctOn(...L){let V=L.map(String).join(", ");return z=z.replace(/^SELECT\s+/i,`SELECT DISTINCT ON (${V}) `),U=null,this},selectRaw(L){let V=z.indexOf(" FROM ");if(V!==-1)z=`${z.substring(0,V)}, ${String(L)}${z.substring(V)}`;else z+=`, ${String(L)}`;return U=null,this},rowNumber(L="row_number",V,K){let n=[];if(V){let q=Array.isArray(V)?V:[V];n.push(`PARTITION BY ${q.join(", ")}`)}if(K&&K.length)n.push(`ORDER BY ${K.map(([q,i])=>`${q} ${i==="desc"?"DESC":"ASC"}`).join(", ")}`);let w=`ROW_NUMBER() ${n.length?`OVER (${n.join(" ")})`:"OVER ()"} AS ${L}`,H=z.indexOf(" FROM ");if(H!==-1)z=`${z.substring(0,H)}, ${w}${z.substring(H)}`;else z+=`, ${w}`;return U=null,this},denseRank(L="dense_rank",V,K){let n=Array.isArray(V)?V:V?[V]:[],D=[];if(n.length)D.push(`PARTITION BY ${n.join(", ")}`);if(K&&K.length)D.push(`ORDER BY ${K.map(([i,h])=>`${i} ${h==="desc"?"DESC":"ASC"}`).join(", ")}`);let H=`DENSE_RANK() ${D.length?`OVER (${D.join(" ")})`:"OVER ()"} AS ${L}`,q=z.indexOf(" FROM ");if(q!==-1)z=`${z.substring(0,q)}, ${H}${z.substring(q)}`;else z+=`, ${H}`;return U=null,this},rank(L="rank",V,K){let n=Array.isArray(V)?V:V?[V]:[],D=[];if(n.length)D.push(`PARTITION BY ${n.join(", ")}`);if(K&&K.length)D.push(`ORDER BY ${K.map(([i,h])=>`${i} ${h==="desc"?"DESC":"ASC"}`).join(", ")}`);let H=`RANK() ${D.length?`OVER (${D.join(" ")})`:"OVER ()"} AS ${L}`,q=z.indexOf(" FROM ");if(q!==-1)z=`${z.substring(0,q)}, ${H}${z.substring(q)}`;else z+=`, ${H}`;return U=null,this},selectAll(){return this},select(L){if(!L||L.length===0)return this;let V=z.indexOf(" FROM ");if(V!==-1)z=`SELECT ${L.join(", ")}${z.substring(V)}`;else z=`SELECT ${L.join(", ")} FROM ${G}`;return this},addSelect(...L){if(!L.length)return this;let V=z.indexOf(" FROM ");if(V!==-1)z=`${z.substring(0,V)}, ${L.join(", ")}${z.substring(V)}`;else z+=`, ${L.join(", ")}`;return U=null,this},with(...L){if(!j||!L||L.length===0)return this;let V=[];for(let h of L){if(!h)continue;if(typeof h==="string")V.push({name:h});else if(typeof h==="object"&&!Array.isArray(h))for(let[b,u]of Object.entries(h))if(typeof u==="function")V.push({name:b,callback:u});else V.push({name:b})}if(V.length===0)return this;let K=c.relations.maxEagerLoad??50;if(V.length>K)throw Error(`[query-builder] Too many relationships to eager load (${V.length}). Maximum allowed: ${K}`);let n=String(G),D=new Set,w=new Set,H=new Map,q=(h)=>{let b=j.relations?.[h];if(!b)return[];return[...Object.keys(b.hasOne||{}),...Object.keys(b.hasMany||{}),...Object.keys(b.belongsTo||{}),...Object.keys(b.belongsToMany||{}),...Object.keys(b.hasOneThrough||{}),...Object.keys(b.hasManyThrough||{}),...Object.keys(b.morphOne||{}),...Object.keys(b.morphMany||{}),...Object.keys(b.morphToMany||{}),...Object.keys(b.morphedByMany||{})]},i=(h,b,u=0,a)=>{let I_=c.relations.maxDepth??10;if(u>=I_)throw Error(`[query-builder] Maximum relationship depth (${I_}) exceeded at '${b}'. Consider using separate queries or increasing maxDepth.`);let e=j.relations?.[h];if(!e)return h;let uk=(t,__)=>{let P_=t;if(c.softDeletes?.enabled&&c.softDeletes?.defaultFilter){let U_=c.softDeletes.column||"deleted_at";P_=`${P_} AND ${__}.${U_} IS NULL`}if(!a)return P_;let D_={where:(U_,dk,Dk)=>{let G1=typeof Dk==="string"?`'${Dk}'`:String(Dk);return`${__}.${U_} ${dk} ${G1}`}};try{let U_=a(D_);if(U_&&typeof U_==="string")return`${P_} AND ${U_}`}catch{}return P_},E1=(t)=>{if(c.softDeletes?.enabled&&c.softDeletes?.defaultFilter){let __=c.softDeletes.column||"deleted_at";return` AND ${t}.${__} IS NULL`}return""},Zj=()=>{let t=(D_)=>{let U_=D_?.[b];return U_?j.modelToTable[U_]:void 0},__=(D_)=>{let U_=D_?.[b],dk=typeof U_==="string"?U_:U_?.model;return dk?j.modelToTable[dk]:void 0},P_=(D_)=>{let U_=D_?.[b];return U_?.target?j.modelToTable[U_.target]:void 0};return t(e?.hasOne)||t(e?.hasMany)||t(e?.belongsTo)||__(e?.belongsToMany)||P_(e?.hasOneThrough)||P_(e?.hasManyThrough)||t(e?.morphOne)||t(e?.morphMany)||t(e?.morphToMany)||t(e?.morphedByMany)},y$=Zj()??(j.modelToTable[b]||j.tableToModel[b]?j.modelToTable[b]??b:b),d_=String(y$);if(!y$||!Zj()&&!j.modelToTable[b]&&!j.tableToModel[b]){let t=q(h);if(t.length>0&&!t.includes(b)){let __=` Available relationships: ${t.join(", ")}`;throw Error(`[query-builder] Relationship '${b}' not found on table '${h}'.${__}`)}}if(c.relations.detectCycles!==!1){let t=`${h}->${d_}`;if(D.has(t))throw Error(`[query-builder] Circular relationship detected: ${t}. This would cause an infinite loop.`);D.add(t)}if(!d_||d_===h)return h;let Z9=e?.hasOneThrough?.[b]||e?.hasManyThrough?.[b];if(Z9){let{through:t,target:__}=Z9,P_=j.modelToTable[t]||t,D_=j.modelToTable[__]||__,U_=j.primaryKeys[h]??"id",dk=j.primaryKeys[P_]??"id",Dk=`${g(h)}_id`,G1=`${g(P_)}_id`;return U=S`${Q()} LEFT JOIN ${S(P_)} ON ${S(`${P_}.${Dk}`)} = ${S(`${h}.${U_}`)} LEFT JOIN ${S(D_)} ON ${S(`${D_}.${G1}`)} = ${S(`${P_}.${dk}`)}`,T.add(P_),T.add(D_),D_}if(Boolean(e?.belongsToMany?.[b])){let t=_O(j,h,b,{singularize:g,models:j.models}),__=t?.pivotTable??[g(h),g(d_)].sort().join("_"),P_=j.primaryKeys[h]??"id",D_=j.primaryKeys[d_]??"id",U_=t?.fkParent??`${g(h)}_id`,dk=t?.fkRelated??`${g(d_)}_id`;return U=S`${Q()} LEFT JOIN ${S(__)} ON ${S(`${__}.${U_}`)} = ${S(`${h}.${P_}`)} LEFT JOIN ${S(d_)} ON ${S(`${d_}.${D_}`)} = ${S(`${__}.${dk}`)}`,T.add(__),T.add(d_),d_}if(Boolean(e?.morphToMany?.[b])){let t=b,__=`${g(d_)}_${t}`,P_=j.primaryKeys[h]??"id",D_=j.primaryKeys[d_]??"id",U_=`${t}_type`,dk=`${t}_id`,Dk=`${g(d_)}_id`;return U=S`${Q()} LEFT JOIN ${S(__)} ON ${S(`${__}.${dk}`)} = ${S(`${h}.${P_}`)} AND ${S(`${__}.${U_}`)} = ${S(j.tableToModel[h]||h)} LEFT JOIN ${S(d_)} ON ${S(`${d_}.${D_}`)} = ${S(`${__}.${Dk}`)}`,T.add(__),T.add(d_),d_}if(Boolean(e?.morphedByMany?.[b])){let t=e.morphedByMany?.[b]||b,__=j.modelToTable[t]||t,P_=g(h),D_=`${g(__)}_${P_}`,U_=j.primaryKeys[h]??"id",dk=j.primaryKeys[__]??"id",Dk=`${P_}_type`,G1=`${P_}_id`,Vz=`${g(__)}_id`;return U=S`${Q()} LEFT JOIN ${S(D_)} ON ${S(`${D_}.${Vz}`)} = ${S(`${h}.${U_}`)} LEFT JOIN ${S(__)} ON ${S(`${__}.${dk}`)} = ${S(`${D_}.${G1}`)} AND ${S(`${D_}.${Dk}`)} = ${S(j.tableToModel[__]||__)}`,T.add(D_),T.add(__),__}if(Boolean(e?.belongsTo?.[b])){let t=`${g(d_)}_id`,__=j.primaryKeys[d_]??"id";return U=S`${Q()} LEFT JOIN ${S(d_)} ON ${S(`${h}.${t}`)} = ${S(`${d_}.${__}`)}`,T.add(d_),d_}let Uz=Boolean(e?.morphOne?.[b]),Qz=Boolean(e?.morphMany?.[b]);if(Uz||Qz){let t=`${b}_type`,__=`${b}_id`,P_=j.primaryKeys[h]??"id";return U=S`${Q()} LEFT JOIN ${S(d_)} ON ${S(`${d_}.${__}`)} = ${S(`${h}.${P_}`)} AND ${S(`${d_}.${t}`)} = ${S(j.tableToModel[h]||h)}`,T.add(d_),d_}let v$=`${g(h)}_id`,A$=j.primaryKeys[h]??"id",m$=E1(d_);if(m$){let t=String(Q()),__=`${d_}.${v$} = ${h}.${A$}${m$}`;U=S`${S(t)} LEFT JOIN ${S(d_)} ON ${S(__)}`}else U=S`${Q()} LEFT JOIN ${S(d_)} ON ${S(`${d_}.${v$}`)} = ${S(`${h}.${A$}`)}`;return T.add(d_),d_};for(let h of V){let b=h.name.trim();if(h.callback)H.set(b,h.callback);let u=b.split("."),a=n,I_=0;for(let e of u){if(!e||e.trim().length===0)continue;let uk=e.trim(),E1=H.get(uk);a=i(a,uk,I_,E1)||a,I_++}w.add(b)}if(y.size>0){let h=[];for(let[b,u]of y.entries()){let a=j_(b);if(!a)continue;let I_=u.map((e)=>`${a.pivotTable}.${e} AS pivot_${e}`);h.push(...I_)}if(h.length>0){let b=h.join(", ");$9(b)}}return z=Z(Q()),this},whereHas(L,V){if(!j)return this;let K=String(G),n=j.relations?.[K];if(!n)throw Error(`[query-builder] No relationships defined for table '${K}'`);let D=Object.entries(n).find(([u,a])=>a&&typeof a==="object"&&(L in a));if(!D)throw Error(`[query-builder] Relationship '${L}' not found on table '${K}'`);let[w,H]=D,q=H[L],i=typeof q==="string"?q:q?.model||q?.target||q,h=j.modelToTable[i]||i,b;if(w==="hasMany"||w==="hasOne"){let u=j.primaryKeys[K]??"id";b=Md(K,h,u,V)}else if(w==="belongsTo"){let u=j.primaryKeys[h]??"id";b=Cd(K,h,u,V)}else if(w==="belongsToMany"){let u=j.primaryKeys[K]??"id",a=j.primaryKeys[h]??"id";b=hd(K,h,u,a,V,L)}else throw Error(`[query-builder] Unsupported relationship type '${w}' for whereHas`);U=S`${Q()} WHERE EXISTS (${S([b])})`;try{I("WHERE",`EXISTS (${b})`)}catch{}return this},whereDoesntHave(L,V){if(!j)return this;let K=String(G),n=j.relations?.[K];if(!n)throw Error(`[query-builder] No relationships defined for table '${K}'`);let D=Object.entries(n).find(([u,a])=>a&&typeof a==="object"&&(L in a));if(!D)throw Error(`[query-builder] Relationship '${L}' not found on table '${K}'`);let[w,H]=D,q=H[L],i=typeof q==="string"?q:q?.model||q?.target||q,h=j.modelToTable[i]||i,b;if(w==="hasMany"||w==="hasOne"){let u=j.primaryKeys[K]??"id";b=Md(K,h,u,V)}else if(w==="belongsTo"){let u=j.primaryKeys[h]??"id";b=Cd(K,h,u,V)}else if(w==="belongsToMany"){let u=j.primaryKeys[K]??"id",a=j.primaryKeys[h]??"id";b=hd(K,h,u,a,V,L)}else throw Error(`[query-builder] Unsupported relationship type '${w}' for whereDoesntHave`);U=S`${Q()} WHERE NOT EXISTS (${S([b])})`;try{I("WHERE",`NOT EXISTS (${b})`)}catch{}return this},has(L){if(!j)return this;let V=String(G),K=j.relations?.[V];if(!K)throw Error(`[query-builder] No relationships defined for table '${V}'`);let n=Object.entries(K).find(([b,u])=>u&&typeof u==="object"&&(L in u));if(!n)throw Error(`[query-builder] Relationship '${L}' not found on table '${V}'`);let[D,w]=n,H=w[L],q=typeof H==="string"?H:H?.model||H?.target||H,i=j.modelToTable[q]||q,h;if(D==="hasMany"||D==="hasOne"){let b=j.primaryKeys[V]??"id";h=Md(V,i,b)}else if(D==="belongsTo"){let b=j.primaryKeys[i]??"id";h=Cd(V,i,b)}else if(D==="belongsToMany"){let b=j.primaryKeys[V]??"id",u=j.primaryKeys[i]??"id";h=hd(V,i,b,u,void 0,L)}else throw Error(`[query-builder] Unsupported relationship type '${D}' for has`);U=S`${Q()} WHERE EXISTS (${S([h])})`;try{I("WHERE",`EXISTS (${h})`)}catch{}return this},doesntHave(L){if(!j)return this;let V=String(G),K=j.relations?.[V];if(!K)throw Error(`[query-builder] No relationships defined for table '${V}'`);let n=Object.entries(K).find(([b,u])=>u&&typeof u==="object"&&(L in u));if(!n)throw Error(`[query-builder] Relationship '${L}' not found on table '${V}'`);let[D,w]=n,H=w[L],q=typeof H==="string"?H:H?.model||H?.target||H,i=j.modelToTable[q]||q,h;if(D==="hasMany"||D==="hasOne"){let b=j.primaryKeys[V]??"id";h=Md(V,i,b)}else if(D==="belongsTo"){let b=j.primaryKeys[i]??"id";h=Cd(V,i,b)}else if(D==="belongsToMany"){let b=j.primaryKeys[V]??"id",u=j.primaryKeys[i]??"id";h=hd(V,i,b,u,void 0,L)}else throw Error(`[query-builder] Unsupported relationship type '${D}' for doesntHave`);U=S`${Q()} WHERE NOT EXISTS (${S([h])})`;try{I("WHERE",`NOT EXISTS (${h})`)}catch{}return this},withCount(...L){if(!j||!L||L.length===0)return this;let V=String(G);for(let K of L){let n=j.relations?.[V];if(!n)continue;let D=Object.entries(n).find(([I_,e])=>e&&typeof e==="object"&&(K in e));if(!D)continue;let[w,H]=D,q=H[K],i=typeof q==="string"?q:q?.model||q?.target||q,h=j.modelToTable[i]||i,b=j.primaryKeys[V]??"id",u;if(w==="hasMany"||w==="hasOne")u=Lz(V,h,b);else if(w==="belongsToMany")u=Pz(V,h,b,K);else continue;let a=`${K}_count`;$9(`${u} AS ${a}`)}return this},applyPivotColumns(){return c$(),this},withPivot(L,...V){if(!j)return this;let K=String(G),n=j_(L);if(!n)throw Error(`[query-builder] Relationship '${L}' is not a belongsToMany relationship on table '${K}'`);let D=V&&V.length>0?V:n.hasConfig?n.pivotColumns:[];if(D.length===0)return this;if(y.set(L,D),n.hasConfig)B.add(L);return c$(),this},wherePivot(L,V,K,n){if(!j)return this;let D=j_(L);if(!D)throw Error(`[query-builder] Relationship '${L}' is not a belongsToMany relationship on table '${String(G)}'`);o(D.pivotTable,"wherePivot (pivot table)"),o(V,"wherePivot (column)"),gk(D);let w=n===void 0?"=":String(K),H=n===void 0?K:n,q=x.length+1,i=`${D.pivotTable}.${V} ${w} ${p(q)}`;T_.push(i),x.push(H);let h=l.WHERE.test(z)?"AND":"WHERE";if(z=`${z} ${h} ${i}`,U=null,D.hasConfig)B.add(L);return this},wherePivotIn(L,V,K){if(!j||!Array.isArray(K)||K.length===0)return this;let n=j_(L);if(!n)throw Error(`[query-builder] Relationship '${L}' is not a belongsToMany relationship on table '${String(G)}'`);o(n.pivotTable,"wherePivotIn (pivot table)"),o(V,"wherePivotIn (column)"),gk(n);let D=p_(K.length,x.length+1),w=`${n.pivotTable}.${V} IN (${D})`;T_.push(w),x.push(...K);let H=l.WHERE.test(z)?"AND":"WHERE";if(z=`${z} ${H} ${w}`,U=null,n.hasConfig)B.add(L);return this},wherePivotNotIn(L,V,K){if(!j||!Array.isArray(K)||K.length===0)return this;let n=j_(L);if(!n)throw Error(`[query-builder] Relationship '${L}' is not a belongsToMany relationship on table '${String(G)}'`);o(n.pivotTable,"wherePivotNotIn (pivot table)"),o(V,"wherePivotNotIn (column)"),gk(n);let D=p_(K.length,x.length+1),w=`${n.pivotTable}.${V} NOT IN (${D})`;T_.push(w),x.push(...K);let H=l.WHERE.test(z)?"AND":"WHERE";if(z=`${z} ${H} ${w}`,U=null,n.hasConfig)B.add(L);return this},wherePivotNull(L,V){if(!j)return this;let K=j_(L);if(!K)throw Error(`[query-builder] Relationship '${L}' is not a belongsToMany relationship on table '${String(G)}'`);o(K.pivotTable,"wherePivotNull (pivot table)"),o(V,"wherePivotNull (column)"),gk(K);let n=`${K.pivotTable}.${V} IS NULL`;T_.push(n);let D=l.WHERE.test(z)?"AND":"WHERE";if(z=`${z} ${D} ${n}`,U=null,K.hasConfig)B.add(L);return this},wherePivotNotNull(L,V){if(!j)return this;let K=j_(L);if(!K)throw Error(`[query-builder] Relationship '${L}' is not a belongsToMany relationship on table '${String(G)}'`);o(K.pivotTable,"wherePivotNotNull (pivot table)"),o(V,"wherePivotNotNull (column)"),gk(K);let n=`${K.pivotTable}.${V} IS NOT NULL`;T_.push(n);let D=l.WHERE.test(z)?"AND":"WHERE";if(z=`${z} ${D} ${n}`,U=null,K.hasConfig)B.add(L);return this},where(L,V,K){let n=()=>z.toUpperCase().includes(" WHERE ")?"AND":"WHERE";if(typeof L==="string"&&V!==void 0){let D=x.length+1;return T_.push(`${String(L)} ${String(V)} ${p(D)}`),x.push(K),z=`${z} ${n()} ${String(L)} ${String(V)} ${p(D)}`,U=null,this}if(Array.isArray(L)){let[D,w,H]=L,q=String(D),i=String(w);if(i==="in"||i==="not in"){let h=Array.isArray(H)?H:[H],b=p_(h.length,x.length+1);T_.push(`${q} ${i.toUpperCase()} (${b})`),x.push(...h),z=`${z} ${n()} ${q} ${i.toUpperCase()} (${b})`,U=null}else{let h=x.length+1;T_.push(`${q} ${i} ${p(h)}`),x.push(H),z=`${z} ${n()} ${q} ${i} ${p(h)}`,U=null}return this}if(L&&typeof L==="object"&&!F5(L)){let D=L,w=Object.keys(D),H=[];for(let q of w){let i=D[q];if(Array.isArray(i)){let h=p_(i.length,x.length+1);H.push(`${q} IN (${h})`),T_.push(`${q} IN (${h})`),x.push(...i)}else{let h=x.length+1;H.push(`${q} = ${p(h)}`),T_.push(`${q} = ${p(h)}`),x.push(i)}}if(H.length>0)z=`${z} ${n()} ${H.join(" AND ")}`,U=null;return this}if(F5(L))return T_.push(L.raw),z=`${z} ${n()} ${L.raw}`,U=null,this;return this},whereNull(L){let V=z.toUpperCase().includes(" WHERE ")?"AND":"WHERE";return z=`${z} ${V} ${String(L)} IS NULL`,U=null,this},whereNotNull(L){let V=z.toUpperCase().includes(" WHERE ")?"AND":"WHERE";return z=`${z} ${V} ${String(L)} IS NOT NULL`,U=null,this},whereBetween(L,V,K){let n=z.toUpperCase().includes(" WHERE ")?"AND":"WHERE";return x.push(V,K),z=`${z} ${n} ${String(L)} BETWEEN ? AND ?`,U=null,this},whereExists(L){let V=z.toUpperCase().includes(" WHERE ")?"AND":"WHERE";return z=`${z} ${V} EXISTS (${L.toSQL()})`,U=null,this},whereJsonContains(L,V){let K=l.WHERE.test(z)?"AND":"WHERE",n=x.length+1;return z+=` ${K} ${L} @> ${p(n)}`,x.push(JSON.stringify(V)),U=null,this},whereJsonPath(L,V,K){let n=c.dialect,D=l.WHERE.test(z)?"AND":"WHERE",w=x.length+1;if(n==="postgres")z+=` ${D} ${L} ${V} ${p(w)}`;else if(n==="mysql")z+=` ${D} JSON_EXTRACT(${L}) ${V} ${p(w)}`;else z+=` ${D} json_extract(${L}) ${V} ${p(w)}`;return x.push(K),U=null,this},whereLike(L,V,K=!1){let n=K?S`${S(String(L))} LIKE ${V}`:S`LOWER(${S(String(L))}) LIKE LOWER(${V})`;return U=S`${Q()} WHERE ${n}`,I("WHERE",`${K?String(L):`LOWER(${String(L)})`} LIKE ${K?"?":"LOWER(?)"}`),this},whereILike(L,V){if(c.dialect==="postgres")U=S`${Q()} WHERE ${S(String(L))} ILIKE ${V}`,I("WHERE",`${String(L)} ILIKE ?`);else{let K=S`LOWER(${S(String(L))}) LIKE LOWER(${V})`;U=S`${Q()} WHERE ${K}`,I("WHERE",`LOWER(${String(L)}) LIKE LOWER(?)`)}return this},orWhereLike(L,V,K=!1){let n=K?S`${S(String(L))} LIKE ${V}`:S`LOWER(${S(String(L))}) LIKE LOWER(${V})`;return U=S`${Q()} OR ${n}`,I("OR",`${K?String(L):`LOWER(${String(L)})`} LIKE ${K?"?":"LOWER(?)"}`),this},orWhereILike(L,V){if(c.dialect==="postgres")U=S`${Q()} OR ${S(String(L))} ILIKE ${V}`,I("OR",`${String(L)} ILIKE ?`);else{let K=S`LOWER(${S(String(L))}) LIKE LOWER(${V})`;U=S`${Q()} OR ${K}`,I("OR",`LOWER(${String(L)}) LIKE LOWER(?)`)}return this},whereNotLike(L,V,K=!1){let n=K?S`${S(String(L))} NOT LIKE ${V}`:S`LOWER(${S(String(L))}) NOT LIKE LOWER(${V})`;return U=S`${Q()} WHERE ${n}`,I("WHERE",`${K?String(L):`LOWER(${String(L)})`} NOT LIKE ${K?"?":"LOWER(?)"}`),this},whereNotILike(L,V){if(c.dialect==="postgres")U=S`${Q()} WHERE ${S(String(L))} NOT ILIKE ${V}`,I("WHERE",`${String(L)} NOT ILIKE ?`);else{let K=S`LOWER(${S(String(L))}) NOT LIKE LOWER(${V})`;U=S`${Q()} WHERE ${K}`,I("WHERE",`LOWER(${String(L)}) NOT LIKE LOWER(?)`)}return this},orWhereNotLike(L,V,K=!1){let n=K?S`${S(String(L))} NOT LIKE ${V}`:S`LOWER(${S(String(L))}) NOT LIKE LOWER(${V})`;return U=S`${Q()} OR ${n}`,I("OR",`${K?String(L):`LOWER(${String(L)})`} NOT LIKE ${K?"?":"LOWER(?)"}`),this},orWhereNotILike(L,V){if(c.dialect==="postgres")U=S`${Q()} OR ${S(String(L))} NOT ILIKE ${V}`,I("OR",`${String(L)} NOT ILIKE ?`);else{let K=S`LOWER(${S(String(L))}) NOT LIKE LOWER(${V})`;U=S`${Q()} OR ${K}`,I("OR",`LOWER(${String(L)}) NOT LIKE LOWER(?)`)}return this},whereAny(L,V,K){if(L.length===0)return this;let n=l.WHERE.test(z)?"AND":"WHERE",D=x.length+1,w=L.map((H,q)=>`${H} ${V} ${p(D+q)}`);z+=` ${n} (${w.join(" OR ")})`;for(let H=0;H<L.length;H++)x.push(K);return U=null,this},whereAll(L,V,K){if(L.length===0)return this;let n=l.WHERE.test(z)?"AND":"WHERE",D=x.length+1,w=L.map((H,q)=>`${H} ${V} ${p(D+q)}`);z+=` ${n} (${w.join(" AND ")})`;for(let H=0;H<L.length;H++)x.push(K);return U=null,this},whereNone(L,V,K){if(L.length===0)return this;let n=l.WHERE.test(z)?"AND":"WHERE",D=x.length+1,w=L.map((H,q)=>`${H} ${V} ${p(D+q)}`);z+=` ${n} NOT (${w.join(" OR ")})`;for(let H=0;H<L.length;H++)x.push(K);return U=null,this},whereNotBetween(L,V,K){let n=l.WHERE.test(z)?"AND":"WHERE";return z+=` ${n} ${L} NOT BETWEEN ? AND ?`,x.push(V,K),U=null,this},whereDate(L,V,K){let n=l.WHERE.test(z)?"AND":"WHERE",D=x.length+1;return z+=` ${n} ${L} ${V} ${p(D)}`,x.push(String(K)),U=null,this},whereRaw(L){let V=l.WHERE.test(z)?"AND":"WHERE";return z+=` ${V} ${String(L)}`,U=null,this},whereColumn(L,V,K){let n=l.WHERE.test(z)?"AND":"WHERE";return z+=` ${n} ${L} ${V} ${K}`,U=null,this},orWhereColumn(L,V,K){return z+=` OR ${L} ${V} ${K}`,U=null,this},whereIn(L,V){let K=l.WHERE.test(z)?"AND":"WHERE";if(Array.isArray(V)){let n=p_(V.length,x.length+1);z+=` ${K} ${L} IN (${n})`,x.push(...V)}else z+=` ${K} ${L} IN (${String(V.toSQL())})`;return U=null,this},orWhereIn(L,V){if(Array.isArray(V)){let K=p_(V.length,x.length+1);z+=` OR ${L} IN (${K})`,x.push(...V)}else z+=` OR ${L} IN (${String(V.toSQL())})`;return U=null,this},whereNotIn(L,V){let K=l.WHERE.test(z)?"AND":"WHERE";if(Array.isArray(V)){let n=p_(V.length,x.length+1);z+=` ${K} ${L} NOT IN (${n})`,x.push(...V)}else z+=` ${K} ${L} NOT IN (${String(V.toSQL())})`;return U=null,this},orWhereNotIn(L,V){if(Array.isArray(V)){let K=p_(V.length,x.length+1);z+=` OR ${L} NOT IN (${K})`,x.push(...V)}else z+=` OR ${L} NOT IN (${String(V.toSQL())})`;return U=null,this},whereNested(L){let V=l.WHERE.test(z)?"AND":"WHERE",K=L.toSQL?String(L.toSQL()):String(L);return z+=` ${V} (${K})`,U=null,this},orWhereNested(L){let V=L.toSQL?String(L.toSQL()):String(L);return z+=` OR (${V})`,U=null,this},andWhere(L,V,K){if(typeof L==="string"&&V!==void 0){let n=x.length+1;return T_.push(`${String(L)} ${String(V)} ${p(n)}`),x.push(K),z=`${z} AND ${String(L)} ${String(V)} ${p(n)}`,U=null,this}if(Array.isArray(L)){let[n,D,w]=L,H=String(n),q=String(D);if(q==="in"||q==="not in"){let i=Array.isArray(w)?w:[w],h=p_(i.length,x.length+1);T_.push(`${H} ${q.toUpperCase()} (${h})`),x.push(...i),z=`${z} AND ${H} ${q.toUpperCase()} (${h})`,U=null}else{let i=x.length+1;T_.push(`${H} ${q} ${p(i)}`),x.push(w),z=`${z} AND ${H} ${q} ${p(i)}`,U=null}return this}if(L&&typeof L==="object"&&!("raw"in L)){let n=Object.keys(L),D=[];for(let w of n){let H=L[w];if(Array.isArray(H)){let q=p_(H.length,x.length+1);D.push(`${w} IN (${q})`),T_.push(`${w} IN (${q})`),x.push(...H)}else{let q=x.length+1;D.push(`${w} = ${p(q)}`),T_.push(`${w} = ${p(q)}`),x.push(H)}}if(D.length>0)z=`${z} AND ${D.join(" AND ")}`,U=null;return this}if(L&&typeof L.raw<"u")return T_.push(L.raw),z=`${z} AND ${L.raw}`,U=null,this;return this},orWhere(L,V,K){if(typeof L==="string"&&V!==void 0){let n=x.length+1;return T_.push(`OR ${String(L)} ${String(V)} ${p(n)}`),x.push(K),z=`${z} OR ${String(L)} ${String(V)} ${p(n)}`,U=null,this}if(Array.isArray(L)){let[n,D,w]=L,H=String(n),q=String(D);if(q==="in"||q==="not in"){let i=Array.isArray(w)?w:[w],h=p_(i.length,x.length+1);T_.push(`OR ${H} ${q.toUpperCase()} (${h})`),x.push(...i),z=`${z} OR ${H} ${q.toUpperCase()} (${h})`,U=null}else{let i=x.length+1;T_.push(`OR ${H} ${q} ${p(i)}`),x.push(w),z=`${z} OR ${H} ${q} ${p(i)}`,U=null}return this}if(L&&typeof L==="object"&&!("raw"in L)){let n=Object.keys(L),D=[];for(let w of n){let H=L[w];if(Array.isArray(H)){let q=p_(H.length,x.length+1);D.push(`${w} IN (${q})`),T_.push(`OR ${w} IN (${q})`),x.push(...H)}else{let q=x.length+1;D.push(`${w} = ${p(q)}`),T_.push(`OR ${w} = ${p(q)}`),x.push(H)}}if(D.length>0)z=`${z} OR ${D.join(" AND ")}`,U=null;return this}if(L&&typeof L.raw<"u")return T_.push(`OR ${L.raw}`),z=`${z} OR ${L.raw}`,U=null,this;return this},orderBy(L,V="asc"){let K=V==="asc"?"ASC":"DESC";return z=l.ORDER_BY.test(z)?`${z}, ${L} ${K}`:`${z} ORDER BY ${L} ${K}`,U=null,this},orderByDesc(L){return z=l.ORDER_BY.test(z)?`${z}, ${L} DESC`:`${z} ORDER BY ${L} DESC`,U=null,this},inRandomOrder(){let L=c.sql.randomFunction==="RAND()"?"RAND()":"RANDOM()";return z=l.ORDER_BY.test(z)?`${z}, ${L}`:`${z} ORDER BY ${L}`,U=null,this},reorder(L,V="asc"){return z=z.replace(/ORDER BY[\s\S]*$/i,""),z+=` ORDER BY ${L} ${V==="asc"?"ASC":"DESC"}`,U=null,this},latest(L){let V=L??c.timestamps.defaultOrderColumn;return z=l.ORDER_BY.test(z)?`${z}, ${V} DESC`:`${z} ORDER BY ${V} DESC`,U=null,this},oldest(L){let V=L??c.timestamps.defaultOrderColumn;return z=l.ORDER_BY.test(z)?`${z}, ${V} ASC`:`${z} ORDER BY ${V} ASC`,U=null,this},limit(L){return z=l.LIMIT.test(z)?z.replace(l.LIMIT,` LIMIT ${L}`):`${z} LIMIT ${L}`,U=null,this},offset(L){return z=l.OFFSET.test(z)?z.replace(l.OFFSET,` OFFSET ${L}`):`${z} OFFSET ${L}`,U=null,this},join(L,V,K,n){return z=`${z} JOIN ${L} ON ${V} ${K} ${n}`,T.add(L),this},joinSub(L,V,K,n,D){return z+=` JOIN (${String(L.toSQL())}) AS ${V} ON ${K} ${n} ${D}`,U=null,T.add(V),this},innerJoin(L,V,K,n){return z=`${z} INNER JOIN ${L} ON ${V} ${K} ${n}`,U=null,T.add(L),this},leftJoin(L,V,K,n){return z=`${z} LEFT JOIN ${L} ON ${V} ${K} ${n}`,U=null,T.add(L),this},leftJoinSub(L,V,K,n,D){return z+=` LEFT JOIN (${String(L.toSQL())}) AS ${V} ON ${K} ${n} ${D}`,U=null,T.add(V),this},rightJoin(L,V,K,n){return z=`${z} RIGHT JOIN ${L} ON ${V} ${K} ${n}`,U=null,T.add(L),this},crossJoin(L){return z=`${z} CROSS JOIN ${L}`,U=null,T.add(L),this},crossJoinSub(L,V){return z+=` CROSS JOIN (${String(L.toSQL())}) AS ${V}`,U=null,T.add(V),this},selectAllRelations(){if(!d)return this;let L=String(G),V=Object.keys(d[L]?.columns??{}),K=[];if(V.length>0)K.push(S`${S(L)}.*`);for(let n of T){let D=Object.keys(d[n]?.columns??{});for(let w of D){let H=c.aliasing.relationColumnAliasFormat==="camelCase"?`${n}_${w}`.replace(/_([a-z])/g,(q,i)=>i.toUpperCase()):c.aliasing.relationColumnAliasFormat==="table.dot.column"?`${n}.${w}`:`${n}_${w}`;K.push(S`${S(`${n}.${w}`)} AS ${S(H)}`)}}if(K.length>0){let n=V.length>0?`${L}.*`:"",D=[];for(let q of T){let i=Object.keys(d[q]?.columns??{});for(let h of i){let b=c.aliasing.relationColumnAliasFormat==="camelCase"?`${q}_${h}`.replace(/_([a-z])/g,(u,a)=>a.toUpperCase()):c.aliasing.relationColumnAliasFormat==="table.dot.column"?`${q}.${h}`:`${q}_${h}`;D.push(`${q}.${h} AS ${b}`)}}let w=[n,...D].filter(Boolean).join(", "),H=z.indexOf(" FROM ");if(H!==-1)z=`SELECT ${w}${z.substring(H)}`;else z=`SELECT ${w} FROM ${L}`;U=null}return this},groupBy(...L){if(L.length)z=l.GROUP_BY.test(z)?`${z}, ${L.join(", ")}`:`${z} GROUP BY ${L.join(", ")}`,U=null;return this},groupByRaw(L){return z=l.GROUP_BY.test(z)?`${z}, ${String(L)}`:`${z} GROUP BY ${String(L)}`,U=null,this},having(L){if(Array.isArray(L)){let V=x.length+1;z=`${z} HAVING ${L[0]} ${L[1]} ${p(V)}`,x.push(L[2]),U=null}else if(L&&typeof L==="object"&&!("raw"in L)){let V=Object.keys(L),K=V.length;if(K){let n=x.length,D=Array.from({length:K});for(let w=0;w<K;w++){let H=V[w];D[w]=`${H} = ${p(n+w+1)}`,x.push(L[H])}z=`${z} HAVING ${D.join(" AND ")}`,U=null}}else if(L&&typeof L.raw<"u")z+=` HAVING ${L.raw}`,U=null;return this},havingRaw(L){return z+=` HAVING ${String(L)}`,U=null,this},orderByRaw(L){return z=l.ORDER_BY.test(z)?`${z}, ${String(L)}`:`${z} ORDER BY ${String(L)}`,U=null,this},union(L){return z+=` UNION ${String(L.toSQL())}`,U=null,this},unionAll(L){return z+=` UNION ALL ${String(L.toSQL())}`,U=null,this},forPage(L,V){let K=Math.max(1,Math.floor(L)),n=Math.max(1,Math.floor(V));return z+=` LIMIT ${n} OFFSET ${(K-1)*n}`,U=null,this},toSQL(){return E(Q(),z)},async value(L){let V=S`${Q()} LIMIT 1`,K=await X(V,"select",{signal:J,timeoutMs:W}),[n]=K;return n?.[L]},async pluck(L,V){let K=await X(Q(),"select",{signal:J,timeoutMs:W});if(V){let n={};for(let D of K)n[String(D?.[V])]=D?.[L];return n}return K.map((n)=>n?.[L])},async exists(){let L=S`SELECT EXISTS (${Q()}) as e`,V=await X(L,"select",{signal:J,timeoutMs:W}),[K]=V;return Boolean(K?.e)},async doesntExist(){return!await this.exists()},async paginate(L,V=1){let K=S`SELECT COUNT(*) as c FROM (${Q()}) as sub`,n=await X(K,"select",{signal:J,timeoutMs:W}),[D]=n,w=Number(D?.c??0),H=Math.max(1,Math.ceil(w/L)),q=Math.max(1,Math.min(V,H)),i=(q-1)*L;return{data:await X(S`${Q()} LIMIT ${L} OFFSET ${i}`,"select",{signal:J,timeoutMs:W}),meta:{perPage:L,page:q,total:w,lastPage:H}}},async simplePaginate(L,V=1){let K=Math.max(1,V),n=(K-1)*L,D=await X(S`${Q()} LIMIT ${L+1} OFFSET ${n}`,"select",{signal:J,timeoutMs:W}),w=D.length>L;return{data:w?D.slice(0,L):D,meta:{perPage:L,page:K,hasMore:w}}},async cursorPaginate(L,V,K="id",n="asc"){let D=Q();if(V!==void 0&&V!==null)if(Array.isArray(K)){let h=K.map((I_)=>S(String(I_))),b=n==="asc"?S`>`:S`<`,u=S`(${S(h)})`,a=S`(${S(V)})`;D=S`${D} WHERE ${u} ${b} ${a}`}else D=n==="asc"?S`${D} WHERE ${S(String(K))} > ${V}`:S`${D} WHERE ${S(String(K))} < ${V}`;if(Array.isArray(K)){let b=K.map((u)=>S`${S(String(u))} ${n==="asc"?S`ASC`:S`DESC`}`).reduce((u,a,I_)=>I_===0?a:S`${u}, ${a}`);D=S`${D} ORDER BY ${b} LIMIT ${L+1}`}else D=S`${D} ORDER BY ${S(String(K))} ${n==="asc"?S`ASC`:S`DESC`} LIMIT ${L+1}`;let w=await X(D,"select",{signal:J,timeoutMs:W}),H=w.length>L?Array.isArray(K)?K.map((h)=>w[L]?.[h]):w[L]?.[K]:null,q=w.slice(0,L),i=q.length?Array.isArray(K)?K.map((h)=>q[0]?.[h]):q[0]?.[K]:null;return{data:q,meta:{perPage:L,nextCursor:H??null,prevCursor:i}}},async chunk(L,V){let K=1;while(!0){let{data:n}=await this.paginate(L,K);if(n.length===0)break;if(await V(n),n.length<L)break;K+=1}},async chunkById(L,V="id",K){let n;while(!0){let{data:D,meta:w}=await this.cursorPaginate(L,n,V,"asc");if(D.length===0)break;if(K)await K(D);if(n=w.nextCursor,!n)break}},async eachById(L,V="id",K){await this.chunkById(L,V,async(n)=>{for(let D of n)await K?.(D)})},withTimeout(L){return W=Math.max(1,Math.floor(L)),this},abort(L){return J=L,this},withTrashed(){return C=!0,f=!1,this},onlyTrashed(){C=!0,f=!0;let L=c.softDeletes?.column||"deleted_at";if(z.includes("WHERE"))z=z.replace(/WHERE/,`WHERE ${G}.${L} IS NOT NULL AND`);else z=`${z} WHERE ${G}.${L} IS NOT NULL`;let V=String(Q());if(V.includes("WHERE")){let K=V.replace(/WHERE/,`WHERE ${G}.${L} IS NOT NULL AND`);U=S([K])}else{let K=`${V} WHERE ${G}.${L} IS NOT NULL`;U=S([K])}return this},scope(L,V){let K=String(G),D=j?.scopes?.[K]?.[L];if(D)return D(this,V);return this},when(L,V,K){if(L)return V(this);if(K)return K(this);return this},tap(L){return L(this),this},dump(){return console.log(String(Q())),this},dd(){throw console.log(String(Q())),Error("Dump and Die")},cache(L=60000){return A=L,N=!0,this},async explain(){let L=S`EXPLAIN ${Q()}`;return await X(L,"select",{signal:J,timeoutMs:W})},simple(){return Q().simple()},toText(){return z},async get(){let L=c.hooks,V=L&&(L.onQueryStart||L.onQueryEnd||L.onQueryError||L.startSpan);if(!c.softDeletes?.enabled&&!N&&!W&&!J&&!V){let D=k._prepareStatement;if(D){let w=D(z);return Ik(x.length>0?w.all(...x):w.all())}}if(U=x.length>0?k.unsafe(z,x):k.unsafe(z),!c.softDeletes?.enabled&&!N&&!W&&!J&&!V){let D=Q()._stmt,w=Q()._params;if(D)return Ik(w&&w.length>0?D.all(...w):D.all());return Ik(await Q().execute())}if(!c.softDeletes?.enabled&&!N&&!W&&!J)return Ik(await X(Q(),"select"));let K=Q();if(c.softDeletes?.enabled&&c.softDeletes.defaultFilter&&!C){let D=c.softDeletes.column,w=String(G);if((d?Boolean(d[w]?.columns?.[D]):!0)&&!l.DELETED_AT.test(z))K=S`${Q()} WHERE ${S(String(D))} IS ${f?S`NOT NULL`:S`NULL`}`,I("WHERE",`${String(D)} IS ${f?"NOT ":""}NULL`)}if(N){let D=String(K),w=T8.get(D);if(w)return w}let n=await X(K,"select",{signal:J,timeoutMs:W});if(N){let D=String(K);T8.set(D,n,A)}return Ik(n)},async executeTakeFirst(){let L=await X(Q(),"select",{signal:J,timeoutMs:W});return a_(Array.isArray(L)?L[0]:L)},async executeTakeFirstOrThrow(){let L=await this.executeTakeFirst();if(!L)throw Error("Record not found");return L},async first(){let L=c.hooks,V=L&&(L.onQueryStart||L.onQueryEnd||L.onQueryError||L.startSpan);if(!c.softDeletes?.enabled&&!N&&!W&&!J&&!V){let D=k._prepareStatement;if(D){let w=z.includes(" LIMIT ")?z:`${z} LIMIT 1`,H=D(w),q=x.length>0?H.all(...x):H.all();return a_(q[0])}}let K=await X(S`${Q()} LIMIT 1`,"select",{signal:J,timeoutMs:W}),[n]=K;return a_(n)},async firstOrFail(){let L=await this.first();if(!L)throw Error("Record not found");return L},async find(L){let V=j?.primaryKeys[String(G)]??"id",K=await X(S`${Q()} WHERE ${S(V)} = ${L} LIMIT 1`,"select",{signal:J,timeoutMs:W}),[n]=K;return n},async findOrFail(L){let V=await this.find(L);if(!V)throw Error("Record not found");return V},async findMany(L){let V=j?.primaryKeys[String(G)]??"id";return await X(S`${Q()} WHERE ${S(String(V))} IN ${S(L)}`,"select",{signal:J,timeoutMs:W})},async*lazy(){let L,V=j?.primaryKeys[String(G)]??"id";while(!0){let n=await(L==null?S`${Q()} ORDER BY ${S(String(V))} ASC LIMIT 100`:S`${Q()} WHERE ${S(String(V))} > ${L} ORDER BY ${S(String(V))} ASC LIMIT 100`).execute();if(n.length===0)break;for(let D of n)yield D;if(L=n[n.length-1]?.[V],L==null)break}},async*lazyById(){let L=j?.primaryKeys[String(G)]??"id",V;while(!0){let n=await(V==null?S`${Q()} ORDER BY ${S(String(L))} ASC LIMIT 100`:S`${Q()} WHERE ${S(String(L))} > ${V} ORDER BY ${S(String(L))} ASC LIMIT 100`).execute();if(n.length===0)break;for(let D of n)yield D;if(V=n[n.length-1]?.[L],V==null)break}},pipe(L){return L(this)},async count(){let L=z.indexOf(" FROM "),V=L!==-1?`SELECT COUNT(*) as c${z.substring(L)}`:`SELECT COUNT(*) as c FROM ${G}`,K=c.hooks,n=K&&(K.onQueryStart||K.onQueryEnd||K.onQueryError||K.startSpan);if(!c.softDeletes?.enabled&&!N&&!W&&!J&&!n){let q=k._prepareStatement;if(q){let i=q(V),h=x.length>0?i.all(...x):i.all();return Number(h[0]?.c??0)}}let D=x.length>0?k.unsafe(V,x):k.unsafe(V),w=await X(D,"select",{signal:J,timeoutMs:W}),[H]=w;return Number(H?.c??0)},async avg(L){let V=z.indexOf(" FROM "),K=V!==-1?`SELECT AVG(${L}) as a${z.substring(V)}`:`SELECT AVG(${L}) as a FROM ${G}`,n=c.hooks,D=n&&(n.onQueryStart||n.onQueryEnd||n.onQueryError||n.startSpan);if(!c.softDeletes?.enabled&&!N&&!W&&!J&&!D){let i=k._prepareStatement;if(i){let h=i(K),b=x.length>0?h.all(...x):h.all();return Number(b[0]?.a??0)}}let w=x.length>0?k.unsafe(K,x):k.unsafe(K),H=await X(w,"select",{signal:J,timeoutMs:W}),[q]=H;return Number(q?.a??0)},async sum(L){let V=z.indexOf(" FROM "),K=V!==-1?`SELECT SUM(${L}) as s${z.substring(V)}`:`SELECT SUM(${L}) as s FROM ${G}`,n=x.length>0?k.unsafe(K,x):k.unsafe(K),D=await X(n,"select",{signal:J,timeoutMs:W}),[w]=D;return Number(w?.s??0)},async max(L){let V=z.indexOf(" FROM "),K=V!==-1?`SELECT MAX(${L}) as m${z.substring(V)}`:`SELECT MAX(${L}) as m FROM ${G}`,n=x.length>0?k.unsafe(K,x):k.unsafe(K),D=await X(n,"select",{signal:J,timeoutMs:W}),[w]=D;return w?.m},async min(L){let V=z.indexOf(" FROM "),K=V!==-1?`SELECT MIN(${L}) as m${z.substring(V)}`:`SELECT MIN(${L}) as m FROM ${G}`,n=x.length>0?k.unsafe(K,x):k.unsafe(K),D=await X(n,"select",{signal:J,timeoutMs:W}),[w]=D;return w?.m},lockForUpdate(){return z+=" FOR UPDATE",U=null,this},sharedLock(){let L=c.sql.sharedLockSyntax==="LOCK IN SHARE MODE"?"LOCK IN SHARE MODE":"FOR SHARE";return z+=` ${L}`,U=null,this},withCTE(L,V){return z=`WITH ${L} AS (${String(V.toSQL())}) ${z}`,U=null,this},withRecursive(L,V){return z=`WITH RECURSIVE ${L} AS (${String(V.toSQL())}) ${z}`,U=null,this},execute(){return X(Q(),"select",{signal:J,timeoutMs:W})},values(){return Q().values()},toParams(){return Q().values?.()??[]},raw(){return Q().raw()},get rows(){return},get row(){return},cancel(){try{Q().cancel()}catch{}}},{get(L,V,K){let n=Reflect.get(L,V,K);if(n!==void 0)return n;if(typeof V==="string"&&(V.startsWith("where")||V.startsWith("orWhere")||V.startsWith("andWhere"))){let D=V.startsWith("orWhere"),w=V.startsWith("andWhere"),H=V.replace(/^or?where/i,"").replace(/^andwhere/i,"");if(!H)return()=>K;let q=H.charAt(0).toLowerCase()+H.slice(1),h=((I_)=>I_.replace(/([A-Z])/g,"_$1").toLowerCase().replace(/^_/,""))(H),b=String(G),u=d?Object.keys(d[b]?.columns??{}):[],a=[h,q,q.toLowerCase()].find((I_)=>u.includes(I_))??h;return(I_)=>{let e=Array.isArray(I_)?S`${S(String(a))} IN ${S(I_)}`:S`${S(String(a))} = ${I_}`;U=D?S`${Q()} OR ${e}`:w?S`${Q()} AND ${e}`:S`${Q()} WHERE ${e}`;let uk=Array.isArray(I_)?`${String(a)} IN (?)`:`${String(a)} = ?`;return I(D?"OR":w?"AND":"WHERE",uk),K}}return Reflect.get(L,V,K)}})}return{configure(G){return Object.assign(c,G),this},id(G){if(!l.IDENTIFIER.test(G))throw Error(`[query-builder] Invalid identifier: '${G}'. Identifiers must start with a letter or underscore and contain only alphanumeric characters, underscores, and dots.`);return k(String(G))},ids(...G){for(let Y of G)if(!l.IDENTIFIER.test(Y))throw Error(`[query-builder] Invalid identifier: '${Y}'. Identifiers must start with a letter or underscore and contain only alphanumeric characters, underscores, and dots.`);return k(G)},select(G,...Y){return F(G,Y)},selectFrom(G){return F(G)},selectFromSub(G,Y){let S=k,z=k`SELECT * FROM (${G.toSQL()}) AS ${k(Y)}`,U={distinct(){let T=String(z).replace(/^SELECT\s+/i,""),W=S`SELECT DISTINCT ${S``}${S(T)}`;return Q(W)},distinctOn(...T){let W=/^SELECT\s+(\S+)\s+FROM/i.exec(String(z)),J=W?`${W[1]} FROM`:String(z),C=S`SELECT DISTINCT ON (${S(T)}) ${S``}${S(J)}`;return Q(C)},selectRaw(T){let W=S`${z} , ${T}`;return Q(W)},where(T,W,J){let C=I(z,T,W,J,"WHERE");return Q(C)},andWhere(T,W,J){let C=I(z,T,W,J,"AND");return Q(C)},orWhere(T,W,J){let C=I(z,T,W,J,"OR");return Q(C)},orderBy(T,W="asc"){let J=W==="asc"?"ASC":"DESC",C=String(z),f=l.ORDER_BY.test(C)?S.unsafe(`${C}, ${T} ${J}`):S`${z} ORDER BY ${S(T)} ${W==="asc"?S`ASC`:S`DESC`}`;return Q(f)},limit(T){let W=String(z),J=l.LIMIT.test(W)?S.unsafe(W.replace(l.LIMIT,` LIMIT ${T}`)):S`${z} LIMIT ${T}`;return Q(J)},offset(T){let W=String(z),J=l.OFFSET.test(W)?S.unsafe(W.replace(l.OFFSET,` OFFSET ${T}`)):S`${z} OFFSET ${T}`;return Q(J)},toSQL(){return E(z)},async execute(){return X(z,"select")},async executeTakeFirst(){let T=await X(z,"select");return Array.isArray(T)?T[0]:T},async executeTakeFirstOrThrow(){let T=await X(z,"select"),W=Array.isArray(T)?T[0]:T;if(!W)throw Error("Record not found");return W},async get(){return X(z,"select")},async first(){let T=await X(z,"select");return Array.isArray(T)?T[0]:T},async firstOrFail(){let T=await X(z,"select"),W=Array.isArray(T)?T[0]:T;if(!W)throw Error("No rows found");return W},async exists(){let T=S`SELECT EXISTS(${z}) as exists`;return(await X(T,"select"))?.[0]?.exists===!0},async doesntExist(){return!await this.exists()},values(){return z.values()},raw(){return z.raw()},cancel(){try{z.cancel()}catch{}},whereRaw:()=>this,whereColumn:()=>this,orWhereColumn:()=>this,whereIn:()=>this,orWhereIn:()=>this,whereNotIn:()=>this,orWhereNotIn:()=>this,whereLike:()=>this,whereILike:()=>this,orWhereLike:()=>this,orWhereILike:()=>this,whereNotLike:()=>this,whereNotILike:()=>this,orWhereNotLike:()=>this,orWhereNotILike:()=>this,whereAny:()=>this,whereAll:()=>this,whereNone:()=>this,whereNested:()=>this,orWhereNested:()=>this,whereDate:()=>this,whereBetween:()=>this,whereNotBetween:()=>this,whereJsonContains:()=>this,whereJsonPath:()=>this,whereNull:()=>this,whereNotNull:()=>this,whereExists:()=>this,whereJsonDoesntContain:()=>this,whereJsonContainsKey:()=>this,whereJsonDoesntContainKey:()=>this,whereJsonLength:()=>this,join:()=>this,joinSub:()=>this,innerJoin:()=>this,leftJoin:()=>this,leftJoinSub:()=>this,rightJoin:()=>this,crossJoin:()=>this,crossJoinSub:()=>this,groupBy:()=>this,groupByRaw:()=>this,having:()=>this,havingRaw:()=>this,addSelect:()=>this,select:()=>this,selectAll:()=>this,orderByDesc:()=>this,inRandomOrder:()=>this,reorder:()=>this,orderByRaw:()=>this,union:()=>this,unionAll:()=>this,forPage:()=>this,selectAllRelations:()=>this,with:()=>this,value:()=>Promise.resolve(void 0),pluck:()=>Promise.resolve([]),cursorPaginate:()=>Promise.resolve({data:[],meta:{perPage:0,nextCursor:null}}),paginate:()=>Promise.resolve({data:[],meta:{perPage:0,page:1,total:0,lastPage:1}}),simplePaginate:()=>Promise.resolve({data:[],meta:{perPage:0,page:1,hasMore:!1}}),chunk:()=>Promise.resolve(),chunkById:()=>Promise.resolve(),eachById:()=>Promise.resolve(),count:()=>Promise.resolve(0),avg:()=>Promise.resolve(0),sum:()=>Promise.resolve(0),max:()=>Promise.resolve(null),min:()=>Promise.resolve(null),find:()=>Promise.resolve(void 0),findOrFail:()=>Promise.reject(Error("Not found")),findMany:()=>Promise.resolve([]),latest:()=>this,oldest:()=>this,lazy:()=>async function*(){}(),lazyById:()=>async function*(){}(),pipe:(T)=>T(this),when:()=>this,tap:()=>this,dump:()=>this,dd:()=>{throw Error("Dump and Die")},explain:()=>Promise.resolve([]),simple:()=>z.simple(),toText:()=>String(z),toParams:()=>z.values?.()??[],withTimeout:()=>this,abort:()=>this,lockForUpdate:()=>this,sharedLock:()=>this,withCTE:()=>this,withRecursive:()=>this,cache:()=>this,clone:()=>this,withTrashed:()=>this,onlyTrashed:()=>this,scope:()=>this,get rows(){return[]},get row(){return}};function Q(T){return{...U,toSQL:()=>E(T),execute:()=>X(T,"select"),get:()=>X(T,"select"),first:async()=>{let W=await X(T,"select");return Array.isArray(W)?W[0]:W},firstOrFail:async()=>{let W=await X(T,"select"),J=Array.isArray(W)?W[0]:W;if(!J)throw Error("No rows found");return J},exists:async()=>{let W=S`SELECT EXISTS(${T}) as exists`;return(await X(W,"select"))?.[0]?.exists===!0},doesntExist:async()=>{return!await U.exists()},values:()=>T.values(),raw:()=>T.raw(),cancel:()=>{try{T.cancel()}catch{}},simple:()=>T.simple(),toText:()=>String(T),toParams:()=>T.values?.()??[]}}function I(T,W,J,C,f="WHERE"){if(typeof W==="string"&&J!==void 0){let N=Array.isArray(C)?`${W} IN (?)`:`${W} ${J} ?`;return S`${T} ${S(f)} ${S(N)}`}else if(Array.isArray(W)&&W.length===3){let[N,y,B]=W,A=Array.isArray(B)?`${N} IN (?)`:`${N} ${y} ?`;return S`${T} ${S(f)} ${S(A)}`}else if(typeof W==="object"&&W!==null){let y=Object.entries(W).map(([B,A])=>{let g=Array.isArray(A)?`${B} IN (?)`:`${B} = ?`;return S`${S(g)}`}).reduce((B,A,g)=>g===0?A:S`${B} AND ${A}`);return S`${T} ${S(f)} ${y}`}return T}return U},insertInto(G){let Y,S="",z=[],U=c.dialect==="postgres",Q=U?(T)=>`"${T}"`:c.dialect==="mysql"?(T)=>`\`${T}\``:(T)=>T,I=U?(T)=>`$${T+1}`:(T)=>"?";return{values(T){let W=Array.isArray(T)?T:[T],J=W.length;if(J===0)return Y=k.unsafe("SELECT 1"),this;let C=W[0],f=Object.keys(C),N=f.length,y=J*N;if(z.length=y,J===1)if(!U){let B=f[0],A="?";z[0]=C[f[0]];for(let g=1;g<N;g++)B+=`,${f[g]}`,A+=",?",z[g]=C[f[g]];S=`INSERT INTO ${G}(${B})VALUES(${A})`}else{let B=f.map((A)=>Q(A)).join(",");S=`INSERT INTO ${Q(G)}(${B})VALUES(`;for(let A=0;A<N;A++){if(A>0)S+=",";S+=I(A),z[A]=C[f[A]]}S+=")"}else{let B=f.map((g)=>Q(g)).join(",");S=`INSERT INTO ${Q(G)}(${B})VALUES`;let A=0;for(let g=0;g<J;g++){let j_=W[g];if(g===0)S+="(";else S+="),(";for(let a_=0;a_<N;a_++){if(a_>0)S+=",";S+=I(A),z[A++]=j_[f[a_]]}}S+=")"}if(!k._prepareStatement)Y=k.unsafe(S,z);return this},returning(...T){let W=`${S} RETURNING ${T.join(", ")}`,J=k.unsafe(W,z);return{where:()=>this,andWhere:()=>this,orWhere:()=>this,orderBy:()=>this,limit:()=>this,offset:()=>this,toSQL:()=>E(J,W),execute:()=>X(J,"insert")}},toSQL(){if(!Y)Y=k.unsafe(S,z);return E(Y,S)},execute(){let T=c.hooks;if(!(T&&(T.onQueryStart||T.onQueryEnd||T.onQueryError||T.startSpan||T.beforeCreate||T.afterCreate))){let J=k._prepareStatement;if(J){let C=J(S);return z.length>0?C.run(...z):C.run()}}if(!Y)Y=k.unsafe(S,z);return X(Y,"insert")},async executeTakeFirst(){if(!Y)Y=k.unsafe(S,z);return await X(Y,"insert")},async executeTakeFirstOrThrow(){if(!Y)Y=k.unsafe(S,z);let T=await X(Y,"insert");if(!T)throw Error("Insert failed");return T},returningAll(){let T=`${S} RETURNING *`,W=k.unsafe(T,z);return{toSQL:()=>E(W,T),execute:()=>X(W,"insert"),async executeTakeFirst(){let J=await X(W,"insert");return Array.isArray(J)?J[0]:J},async executeTakeFirstOrThrow(){let J=await X(W,"insert"),C=Array.isArray(J)?J[0]:J;if(!C)throw Error("Insert with RETURNING failed");return C}}}}},updateTable(G){let Y,S=[],z=(Q)=>{if(c.dialect==="mysql")return`\`${Q}\``;return`"${Q}"`},U=`UPDATE ${z(String(G))}`;return{set(Q){let I=Object.keys(Q),T=I.length,W=Array.from({length:T});for(let J=0;J<T;J++){let C=I[J];W[J]=`${z(C)} = ${p(J+1)}`,S.push(Q[C])}return U=`${U} SET ${W.join(", ")}`,Y=k.unsafe(U,S),this},where(Q,I,T){let W=()=>U.toUpperCase().includes(" WHERE ")?"AND":"WHERE";if(typeof Q==="string"&&I!==void 0){let J=S.length+1;return U=`${U} ${W()} ${z(Q)} ${I} ${p(J)}`,S.push(T),Y=k.unsafe(U,S),this}if(Array.isArray(Q)){let[J,C,f]=Q,N=S.length+1;return U=`${U} ${W()} ${z(String(J))} ${String(C)} ${p(N)}`,S.push(f),Y=k.unsafe(U,S),this}if(Q&&typeof Q==="object"&&!("raw"in Q)){let J=Object.keys(Q),C=J.length,f=S.length,N=Array.from({length:C});for(let y=0;y<C;y++)N[y]=`${z(J[y])} = ${p(f+y+1)}`,S.push(Q[J[y]]);U=`${U} ${W()} ${N.join(" AND ")}`,Y=k.unsafe(U,S)}return this},returning(...Q){let I=`${U} RETURNING ${Q.join(", ")}`,T=S.length>0?k.unsafe(I,S):k.unsafe(I),W={where:()=>W,andWhere:()=>W,orWhere:()=>W,orderBy:()=>W,limit:()=>W,offset:()=>W,toSQL:()=>E(T,I),execute:()=>X(T,"update")};return W},toSQL(){if(!Y)Y=S.length>0?k.unsafe(U,S):k.unsafe(U);return E(Y,U)},execute(){return X(Y,"update")},async executeTakeFirst(){return{numUpdatedRows:await X(Y,"update")}},async executeTakeFirstOrThrow(){let Q=await X(Y,"update");if(Q===0)throw Error("No rows updated");return{numUpdatedRows:Q}},returningAll(){let Q=`${U} RETURNING *`,I=S.length>0?k.unsafe(Q,S):k.unsafe(Q);return{toSQL:()=>E(I,Q),execute:()=>X(I,"update"),async executeTakeFirst(){let T=await X(I,"update");return Array.isArray(T)?T[0]:T},async executeTakeFirstOrThrow(){let T=await X(I,"update"),W=Array.isArray(T)?T[0]:T;if(!W)throw Error("Update with RETURNING failed");return W}}}}},deleteFrom(G){let Y=(W)=>{if(c.dialect==="mysql")return`\`${W}\``;return`"${W}"`},z=`DELETE FROM ${Y(String(G))}`,U=null,Q=[],I=null,T=()=>{if(U===null)U=Q.length>0?k.unsafe(z,Q):k.unsafe(z);return U};return{where(W,J,C){if(I=W,typeof W==="string"&&J!==void 0){let f=Q.length+1;return z+=` WHERE ${Y(W)} ${J} ${p(f)}`,Q.push(C),U=null,this}if(Array.isArray(W)){let[f,N,y]=W,B=Q.length+1;return z+=` WHERE ${Y(String(f))} ${N} ${p(B)}`,Q.push(y),U=null,this}if(W&&typeof W==="object"&&!("raw"in W)){let f=Object.keys(W),N=[];for(let y of f){let B=Q.length+1;N.push(`${Y(y)} = ${p(B)}`),Q.push(W[y])}return z+=` WHERE ${N.join(" AND ")}`,U=null,this}return U=$({},T(),W),this},returning(...W){let J=`${z} RETURNING ${W.join(", ")}`,C=Q.length>0?k.unsafe(J,Q):k.unsafe(J),f={where:()=>f,andWhere:()=>f,orWhere:()=>f,orderBy:()=>f,limit:()=>f,offset:()=>f,toSQL:()=>E(C,J),execute:()=>X(C,"delete")};return f},toSQL(){return E(T(),z)},async execute(){try{await c.hooks?.beforeDelete?.({table:String(G),where:I})}catch(J){throw J}let W=await X(T(),"delete");try{await c.hooks?.afterDelete?.({table:String(G),where:I,result:W})}catch{}return W},async executeTakeFirst(){return{numDeletedRows:await X(T(),"delete")}},async executeTakeFirstOrThrow(){let W=await X(T(),"delete");if(W===0)throw Error("No rows deleted");return{numDeletedRows:W}},returningAll(){let W=`${z} RETURNING *`,J=Q.length>0?k.unsafe(W,Q):k.unsafe(W);return{toSQL:()=>E(J,W),execute:()=>X(J,"delete"),async executeTakeFirst(){let C=await X(J,"delete");return Array.isArray(C)?C[0]:C},async executeTakeFirstOrThrow(){let C=await X(J,"delete"),f=Array.isArray(C)?C[0]:C;if(!f)throw Error("Delete with RETURNING failed");return f}}}}},table(G){let Y=this;return{insert(S){return Y.insertInto(G).values(S)},update(S){return Y.updateTable(G).set(S)},delete(){return Y.deleteFrom(G)},select(...S){if(S.length===0)return Y.selectFrom(G);return Y.select(G,...S)}}},sql:k,raw(G,...Y){return k(G,...Y)},simple(G,...Y){return k(G,...Y).simple()},async advisoryLock(G){if(c.dialect!=="postgres")return;let Y=String(G),S=7;for(let Q=0;Q<Y.length;Q++)S=S*31+Y.charCodeAt(Q)|0;let z=typeof G==="number"?G:Math.abs(S),U=v`SELECT pg_advisory_lock(${z})`;await X(U,"raw")},async tryAdvisoryLock(G){if(c.dialect!=="postgres")return!1;let Y=String(G),S=7;for(let I=0;I<Y.length;I++)S=S*31+Y.charCodeAt(I)|0;let z=typeof G==="number"?G:Math.abs(S),U=v`SELECT pg_try_advisory_lock(${z}) as ok`,Q=await X(U,"raw");return Boolean(Q?.[0]?.ok)},unsafe(G,Y){return v.unsafe(G,Y)},file(G,Y){return v.file(G,Y)},async reserve(){let G=await v.reserve(),Y=Q1({sql:G,meta:j,schema:d});return Y.release=()=>G.release(),Y},async close(G){await v.close(G)},async listen(G,Y){},async unlisten(G){},async notify(G,Y){},async copyTo(G,Y){throw Error("COPY TO is not yet supported by Bun.sql; placeholder")},async copyFrom(G,Y,S){throw Error("COPY FROM is not yet supported by Bun.sql; placeholder")},async ping(){try{let G=v`SELECT 1`;return await X(G,"select"),!0}catch{return!1}},async waitForReady(G){let Y=Math.max(1,G?.attempts??10),S=Math.max(10,G?.delayMs??100);for(let z=0;z<Y;z++){if(await this.ping())return;await new Promise((U)=>setTimeout(U,S))}throw Error("Database not ready after waiting")},async transaction(G,Y){let z={..._?.txDefaults,...Y},U=async(T)=>{z.logger?.({type:"start",attempt:T});let W=Date.now();return await v.begin(async(J)=>{let C=Q1({sql:J,meta:j,schema:d});if(z?.isolation){let y=z.isolation,B=y==="read committed"?v`READ COMMITTED`:y==="repeatable read"?v`REPEATABLE READ`:v`SERIALIZABLE`;await J`${v`SET TRANSACTION ISOLATION LEVEL`} ${B}`.execute()}if(z?.readOnly)try{await J`${v`SET TRANSACTION READ ONLY`}`.execute()}catch{}let f=await G(C),N=Date.now()-W;return z.logger?.({type:"commit",attempt:T,durationMs:N}),f})},Q=Math.max(0,z?.retries??0),I=0;for(;;)try{let T=await U(I+1);return z?.afterCommit?.(),T}catch(T){let W=wL(T)||ML(T,z.sqlStates);if(I<Q&&W){I++,z?.onRetry?.(I,T);let J=hL(I,z.backoff);if(J>0)await CL(J);continue}try{z.onRollback?.(T)}catch{}try{z.afterRollback?.()}catch{}throw T}},async savepoint(G){let Y=k;if(!Y||typeof Y.savepoint!=="function")throw Error("savepoint() must be called inside a transaction");return await Y.savepoint(async(S)=>{let z=Q1({sql:S,meta:j,schema:d});return await G(z)})},async beginDistributed(G,Y){return await v.beginDistributed(G,async(z)=>{let U=Q1({sql:z,meta:j,schema:d});return await Y(U)})},async commitDistributed(G){await v.commitDistributed(G)},async rollbackDistributed(G){await v.rollbackDistributed(G)},setTransactionDefaults(G){_={..._,txDefaults:{..._?.txDefaults,...G}}},transactional(G,Y){return(...S)=>{return this.transaction((z)=>G(z,...S),Y)}},async insertOrIgnore(G,Y){return v`INSERT INTO ${v(String(G))} ${v(Y)} ON CONFLICT DO NOTHING`.execute()},async insertGetId(G,Y,S="id"){if(c.dialect==="mysql"){let U=await v`INSERT INTO ${v(String(G))} ${v(Y)}`.execute();if(U&&typeof U==="object"&&"insertId"in U)return U.insertId;let[Q]=await v`SELECT LAST_INSERT_ID() as id`.execute();return Q?.id}else{let z=v`INSERT INTO ${v(String(G))} ${v(Y)} RETURNING ${v(String(S))} as id`,[U]=await z.execute();return U?.id}},async updateOrInsert(G,Y,S){let z=Object.keys(Y).map((I)=>v`${v(String(I))} = ${v(Y[I])}`);if((await v`SELECT 1 FROM ${v(String(G))} WHERE ${v(z)} LIMIT 1`.execute()).length)return await v`UPDATE ${v(String(G))} SET ${v(S)} WHERE ${v(z)}`.execute(),!0;else return await v`INSERT INTO ${v(String(G))} ${v({...Y,...S})}`.execute(),!0},async upsert(G,Y,S,z){let U=S.map((T)=>String(T)),Q=(z??[]).map((T)=>String(T));return v`INSERT INTO ${v(String(G))} ${v(Y)} ON CONFLICT (${v(U)}) DO UPDATE SET ${v(Q.reduce((T,W)=>({...T,[W]:v(`EXCLUDED.${W}`)}),{}))}`.execute()},async save(G,Y){let S=j?.primaryKeys[String(G)]??"id",z=Y[S];if(z!=null)if(await this.selectFrom(G).find(z)){await this.updateTable(G).set(Y).where({[S]:z}).execute();let Q=await this.selectFrom(G).find(z);if(!Q)throw Error("save() failed to retrieve updated row");return Q}else return await this.create(G,Y);return await this.create(G,Y)},async remove(G,Y){return await this.deleteFrom(G).where({id:Y}).execute()},async find(G,Y){return await this.selectFrom(G).find(Y)},async findOrFail(G,Y){return await this.selectFrom(G).findOrFail(Y)},async findMany(G,Y){return await this.selectFrom(G).findMany(Y)},async latest(G,Y){return await this.selectFrom(G).latest(Y).first()},async oldest(G,Y){return await this.selectFrom(G).oldest(Y).first()},skip(G,Y){return this.selectFrom(G).offset(Y)},async rawQuery(G){let Y=Date.now();try{c.hooks?.onQueryStart?.({sql:G,kind:"raw"});let S=await v.unsafe(G);return c.hooks?.onQueryEnd?.({sql:G,durationMs:Date.now()-Y,kind:"raw"}),S}catch(S){throw c.hooks?.onQueryError?.({sql:G,error:S,durationMs:Date.now()-Y,kind:"raw"}),S}},async create(G,Y){let S=j?.primaryKeys[String(G)]??"id";try{await c.hooks?.beforeCreate?.({table:String(G),data:Y})}catch(z){throw z}if(c.dialect==="postgres"){let z=v`INSERT INTO ${v(String(G))} ${v(Y)} RETURNING ${v(String(S))} as id`,[U]=await z.execute();if(console.log("resultId",U),!U?.id)throw console.error(`create() failed to get insert ID for table ${String(G)}`),console.error("Inserted values:",Y),Error(`create() failed to get insert ID for table ${String(G)}`);let Q=await this.selectFrom(G).find(U.id);if(!Q)throw console.error(`create() failed to retrieve inserted row for table ${String(G)} with id ${U.id}`),console.error("Inserted values:",Y),Error(`create() failed to retrieve inserted row for table ${String(G)} with id ${U.id}`);try{await c.hooks?.afterCreate?.({table:String(G),data:Y,result:Q})}catch{}return Q}else{let z=await this.insertGetId(G,Y,S);if(z==null)throw Error(`create() failed to get insert ID for table ${String(G)}`);let U=await this.selectFrom(G).find(z);if(!U)throw console.error(`create() failed to retrieve inserted row for table ${String(G)} with id ${z}`),console.error("Inserted values:",Y),Error(`create() failed to retrieve inserted row for table ${String(G)} with id ${z}`);try{await c.hooks?.afterCreate?.({table:String(G),data:Y,result:U})}catch{}return U}},async createMany(G,Y){if(!Y?.length)return;let S=Y[0],z=Object.keys(S),U=z.length,Q=Y.length,I=Array.from({length:Q*U}),T=`INSERT INTO ${G}(${z.join(",")})VALUES`,W=0;for(let J=0;J<Q;J++){if(J>0)T+=",";T+="(";let C=Y[J];for(let f=0;f<U;f++){if(f>0)T+=",";T+=p(W+1),I[W++]=C[z[f]]}T+=")"}return k.unsafe(T,I).execute()},async insertMany(G,Y){if(!Y?.length)return;let S=Y[0],z=Object.keys(S),U=z.length,Q=Y.length,I=Q*U,T=Array(I),W=c.dialect==="postgres",J;if(!W){let N=Array(U);for(let y=0;y<U;y++)N[y]="?";J=`(${N.join(",")})`}else J="";let C=Array(Q+2);C[0]=`INSERT INTO ${G}(${z.join(",")})VALUES`;let f=0;if(!W){for(let N=0;N<Q;N++){let y=Y[N];C[N+1]=J;for(let B=0;B<U;B++)T[f++]=y[z[B]]}return k.unsafe(C[0]+C.slice(1,Q+1).join(","),T).execute()}for(let N=0;N<Q;N++){let y=Y[N],B=Array(U);for(let A=0;A<U;A++)B[A]=`$${f+1}`,T[f++]=y[z[A]];C[N+1]=`(${B.join(",")})`}return k.unsafe(C[0]+C.slice(1,Q+1).join(","),T).execute()},async updateMany(G,Y,S){let z=Object.keys(S),U=z.length;if(U===0)return 0;let Q=[],I=Array.from({length:U});for(let W=0;W<U;W++)I[W]=`${z[W]}=${p(W+1)}`,Q.push(S[z[W]]);let T=`UPDATE ${G} SET ${I.join(",")}`;if(Array.isArray(Y))T+=` WHERE ${Y[0]}${Y[1]}${p(Q.length+1)}`,Q.push(Y[2]);else if(Y&&typeof Y==="object"&&!("raw"in Y)){let W=Object.keys(Y),J=W.length;if(J>0){let C=Q.length,f=Array.from({length:J});for(let N=0;N<J;N++)f[N]=`${W[N]}=${p(C+N+1)}`,Q.push(Y[W[N]]);T+=` WHERE ${f.join(" AND ")}`}}return k.unsafe(T,Q).execute()},async deleteMany(G,Y){if(!Array.isArray(Y)||Y.length===0)return 0;let S=j?.primaryKeys[String(G)]??"id",z=Y.length;if(c.dialect==="postgres"){let Q=Array(z);for(let I=0;I<z;I++)Q[I]=`$${I+1}`;return k.unsafe(`DELETE FROM ${G} WHERE ${S} IN (${Q.join(",")})`,Y).execute()}let U=Array(z);for(let Q=0;Q<z;Q++)U[Q]="?";return k.unsafe(`DELETE FROM ${G} WHERE ${S} IN (${U.join(",")})`,Y).execute()},async firstOrCreate(G,Y,S){let z=await this.selectFrom(G).where(Y).first();if(z)return z;return await this.create(G,{...Y,...S})},async updateOrCreate(G,Y,S){let z=await this.selectFrom(G).where(Y).first();if(z){await this.updateTable(G).set(S).where(Y).execute();let U=j?.primaryKeys[String(G)]??"id",Q=z[U],I=Q!=null?await this.selectFrom(G).find(Q):await this.selectFrom(G).where(Y).first();if(!I)throw Error("updateOrCreate() failed to retrieve updated row");return I}return await this.create(G,{...Y,...S})},async count(G,Y){let S=Y?v(String(Y)):v`*`,z=v`SELECT COUNT(${S}) as c FROM ${v(String(G))}`,[U]=await z.execute();return Number(U?.c??0)},async sum(G,Y){let S=v`SELECT SUM(${v(String(Y))}) as s FROM ${v(String(G))}`,[z]=await S.execute();return Number(z?.s??0)},async avg(G,Y){let S=v`SELECT AVG(${v(String(Y))}) as a FROM ${v(String(G))}`,[z]=await S.execute();return Number(z?.a??0)},async min(G,Y){let S=v`SELECT MIN(${v(String(Y))}) as m FROM ${v(String(G))}`,[z]=await S.execute();return z?.m},async max(G,Y){let S=v`SELECT MAX(${v(String(Y))}) as m FROM ${v(String(G))}`,[z]=await S.execute();return z?.m},getRelationships(G){if(!j?.relations)return{};let Y=j.relations[G];if(!Y)return{};let S={};for(let[z,U]of Object.entries(Y))if(U&&typeof U==="object"&&Object.keys(U).length>0)S[z]=U;return S},hasRelationship(G,Y){if(!j?.relations)return!1;let S=j.relations[G];if(!S)return!1;return Object.values(S).some((z)=>z&&typeof z==="object"&&(Y in z))},getRelationshipType(G,Y){if(!j?.relations)return null;let S=j.relations[G];if(!S)return null;for(let[z,U]of Object.entries(S))if(U&&typeof U==="object"&&Y in U)return z;return null},getRelationshipTarget(G,Y){if(!j?.relations)return null;let S=j.relations[G];if(!S)return null;for(let[z,U]of Object.entries(S))if(U&&typeof U==="object"&&Y in U){let Q=U[Y];if(typeof Q==="string")return j.modelToTable[Q]||Q;else if(Q&&typeof Q==="object"){if("model"in Q)return j.modelToTable[Q.model]||Q.model;if("target"in Q)return j.modelToTable[Q.target]||Q.target}}return null}}}var l,T8,L0=r(()=>{Wk(),mj(),l={SELECT_STAR:/^SELECT\s+\*/i,SELECT:/^SELECT\s+/i,SELECT_FROM:/^SELECT\s+(.+?)\s+FROM/i,WHERE:/\bWHERE\b/i,ORDER_BY:/\bORDER\s+BY\b/i,GROUP_BY:/\bGROUP\s+BY\b/i,LIMIT:/\sLIMIT\s+\d+/i,OFFSET:/\sOFFSET\s+\d+/i,IDENTIFIER:/^[A-Z_][\w.]*$/i,DELETED_AT:/\bdeleted_at\b/i},T8=new MZ});var fL=r(()=>{L0()});var qL=r(()=>{i_()});var HL=r(()=>{Wk(),L0()});var bL=r(()=>{Wk(),i_()});var NL=r(()=>{mj()});var xL=r(()=>{mj()});var iL=r(()=>{i_()});var BL=r(()=>{i_()});var cL=r(()=>{Wk(),i_()});var yL=r(()=>{i_()});var vL=()=>{};class CZ{quoteIdentifier(_){return`\`${_.replace(/`/g,"``")}\``}getColumnType(_){switch(_.type){case"string":return"varchar(255)";case"text":return"text";case"boolean":return"tinyint(1)";case"integer":return"integer";case"bigint":return"bigint";case"float":return"real";case"double":return"double precision";case"decimal":return"decimal(10,2)";case"date":return"date";case"datetime":return"datetime";case"json":return"json";case"enum":if(_.enumValues&&_.enumValues.length>0)return`ENUM(${_.enumValues.map((j)=>`'${j.replace(/'/g,"''")}'`).join(", ")})`;return"text";default:return"text"}}getPrimaryKeyType(_){return this.getColumnType(_)}getAutoIncrementClause(_){if(_.isPrimaryKey&&(_.type==="integer"||_.type==="bigint"))return"auto_increment";return""}getDefaultValue(_){if(!_.hasDefault||_.defaultValue===void 0)return"";let k=_.defaultValue;if(typeof k==="string"){let j=["CURRENT_TIMESTAMP","NOW()","NULL","CURRENT_DATE","CURRENT_TIME"],d=k.toUpperCase();if(j.includes(d))return`default ${d}`;return`default '${k.replace(/'/g,"''")}'`}else if(typeof k==="number"||typeof k==="bigint")return`default ${k}`;else if(typeof k==="boolean")return`default ${k?1:0}`;else if(k instanceof Date)return`default '${k.toISOString()}'`;return""}createEnumType(_,k){return""}createTable(_){let k=_.columns.map((j)=>this.renderColumn(j)).join(`,
|
|
73
|
-
`);return`CREATE TABLE IF NOT EXISTS ${this.quoteIdentifier(_.table)} (
|
|
74
|
-
${k}
|
|
75
|
-
);`}createIndex(_,k){if(k.where)throw Error(`[migrations] Partial indexes (CompositeIndex.where) are not supported on MySQL. Index '${k.name}' on table '${_}' uses WHERE clause: ${k.where}`);let j=k.type==="unique"?"UNIQUE ":"",d=`${_}_${k.name}`,O=k.columns.map(($)=>this.quoteIdentifier($)).join(", ");return`CREATE ${j}INDEX ${this.quoteIdentifier(d)} ON ${this.quoteIdentifier(_)} (${O});`}addForeignKey(_,k,j,d,O,$){let Z=`${_}_${k}_fk`,X=`ALTER TABLE ${this.quoteIdentifier(_)} ADD CONSTRAINT ${this.quoteIdentifier(Z)} FOREIGN KEY (${this.quoteIdentifier(k)}) REFERENCES ${this.quoteIdentifier(j)}(${this.quoteIdentifier(d)})`;if(O)X+=` ON DELETE ${O.toUpperCase()}`;if($)X+=` ON UPDATE ${$.toUpperCase()}`;return`${X};`}addColumn(_,k){let j=this.getColumnType(k),d=[this.quoteIdentifier(k.name),j];if(!k.isNullable&&!k.isPrimaryKey)d.push("not null");let O=this.getDefaultValue(k);if(O)d.push(O);return`ALTER TABLE ${this.quoteIdentifier(_)} ADD COLUMN ${d.join(" ")};`}modifyColumn(_,k){let j=this.getColumnType(k),d=[this.quoteIdentifier(k.name),j];if(!k.isNullable&&!k.isPrimaryKey)d.push("not null");let O=this.getDefaultValue(k);if(O)d.push(O);return`ALTER TABLE ${this.quoteIdentifier(_)} MODIFY COLUMN ${d.join(" ")};`}dropTable(_){return`DROP TABLE IF EXISTS ${this.quoteIdentifier(_)}`}dropColumn(_,k){return`ALTER TABLE ${this.quoteIdentifier(_)} DROP COLUMN ${this.quoteIdentifier(k)};`}dropIndex(_,k){let j=`${_}_${k}`;return`DROP INDEX ${this.quoteIdentifier(j)} ON ${this.quoteIdentifier(_)};`}dropEnumType(_){return""}createMigrationsTable(){return`CREATE TABLE IF NOT EXISTS migrations (
|
|
76
|
-
id INT AUTO_INCREMENT PRIMARY KEY,
|
|
77
|
-
migration VARCHAR(255) NOT NULL UNIQUE,
|
|
78
|
-
executed_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
|
79
|
-
)`}getExecutedMigrationsQuery(){return"SELECT migration FROM migrations ORDER BY executed_at"}recordMigrationQuery(){return"INSERT INTO migrations (migration) VALUES (?)"}renderColumn(_){let k=this.getColumnType(_),j=[this.quoteIdentifier(_.name),k];if(_.isPrimaryKey){j.push("PRIMARY KEY");let O=this.getAutoIncrementClause(_);if(O)j.push(O)}if(!_.isNullable&&!_.isPrimaryKey)j.push("not null");let d=this.getDefaultValue(_);if(d)j.push(d);return j.join(" ")}}class hZ{quoteIdentifier(_){return`"${_.replace(/"/g,'""')}"`}getColumnType(_){switch(_.type){case"string":return"varchar(255)";case"text":return"text";case"boolean":return"boolean";case"integer":return"integer";case"bigint":return"bigint";case"float":return"real";case"double":return"double precision";case"decimal":return"decimal(10,2)";case"date":return"date";case"datetime":return"timestamp";case"json":return"jsonb";case"enum":if(_.enumValues&&_.enumValues.length>0)return`${_.name}_type`;return"text";default:return"text"}}getPrimaryKeyType(_){switch(_.type){case"integer":return"SERIAL";case"bigint":return"BIGSERIAL";default:return this.getColumnType(_)}}getAutoIncrementClause(_){return""}getDefaultValue(_){if(!_.hasDefault||_.defaultValue===void 0)return"";let k=_.defaultValue;if(typeof k==="string"){let j=["CURRENT_TIMESTAMP","NOW()","NULL","CURRENT_DATE","CURRENT_TIME"],d=k.toUpperCase();if(j.includes(d))return`default ${d}`;return`default '${k.replace(/'/g,"''")}'`}else if(typeof k==="number"||typeof k==="bigint")return`default ${k}`;else if(typeof k==="boolean")return`default ${k?"true":"false"}`;else if(k instanceof Date)return`default '${k.toISOString()}'`;return""}createEnumType(_,k){let j=k.map((d)=>`'${d.replace(/'/g,"''")}'`).join(", ");return`CREATE TYPE ${this.quoteIdentifier(_)} AS ENUM (${j});`}createTable(_){let k=_.columns.map((j)=>this.renderColumn(j)).join(`,
|
|
80
|
-
`);return`CREATE TABLE IF NOT EXISTS ${this.quoteIdentifier(_.table)} (
|
|
81
|
-
${k}
|
|
82
|
-
);`}createIndex(_,k){let j=k.type==="unique"?"UNIQUE ":"",d=`${_}_${k.name}`,O=k.columns.map((Z)=>this.quoteIdentifier(Z)).join(", "),$=k.where?` WHERE ${k.where}`:"";return`CREATE ${j}INDEX IF NOT EXISTS ${this.quoteIdentifier(d)} ON ${this.quoteIdentifier(_)} (${O})${$};`}addForeignKey(_,k,j,d,O,$){let Z=`${_}_${k}_fk`,X=`ALTER TABLE ${this.quoteIdentifier(_)} ADD CONSTRAINT ${this.quoteIdentifier(Z)} FOREIGN KEY (${this.quoteIdentifier(k)}) REFERENCES ${this.quoteIdentifier(j)}(${this.quoteIdentifier(d)})`;if(O)X+=` ON DELETE ${O.toUpperCase()}`;if($)X+=` ON UPDATE ${$.toUpperCase()}`;return`${X};`}addColumn(_,k){let j=this.getColumnType(k),d=[this.quoteIdentifier(k.name),j];if(!k.isNullable&&!k.isPrimaryKey)d.push("not null");let O=this.getDefaultValue(k);if(O)d.push(O);return`ALTER TABLE ${this.quoteIdentifier(_)} ADD COLUMN ${d.join(" ")};`}modifyColumn(_,k){let j=this.getColumnType(k);return`ALTER TABLE ${this.quoteIdentifier(_)} ALTER COLUMN ${this.quoteIdentifier(k.name)} TYPE ${j} USING ${this.quoteIdentifier(k.name)}::${j};`}dropTable(_){return`DROP TABLE IF EXISTS ${this.quoteIdentifier(_)} CASCADE`}dropColumn(_,k){return`ALTER TABLE ${this.quoteIdentifier(_)} DROP COLUMN ${this.quoteIdentifier(k)};`}dropIndex(_,k){let j=`${_}_${k}`;return`DROP INDEX IF EXISTS ${this.quoteIdentifier(j)};`}dropEnumType(_){return`DROP TYPE IF EXISTS ${this.quoteIdentifier(_)} CASCADE`}createMigrationsTable(){return`CREATE TABLE IF NOT EXISTS migrations (
|
|
83
|
-
id SERIAL PRIMARY KEY,
|
|
84
|
-
migration VARCHAR(255) NOT NULL UNIQUE,
|
|
85
|
-
executed_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
|
86
|
-
)`}getExecutedMigrationsQuery(){return"SELECT migration FROM migrations ORDER BY executed_at"}recordMigrationQuery(){return"INSERT INTO migrations (migration) VALUES ($1)"}renderColumn(_){let k=_.isPrimaryKey?this.getPrimaryKeyType(_):this.getColumnType(_),j=[this.quoteIdentifier(_.name),k];if(_.isPrimaryKey)j.push("PRIMARY KEY");if(!_.isNullable&&!_.isPrimaryKey)j.push("not null");let d=this.getDefaultValue(_);if(d)j.push(d);return j.join(" ")}}class fZ{quoteIdentifier(_){return`"${_.replace(/"/g,'""')}"`}getColumnType(_){if(_.name.endsWith("_id"))return"INTEGER";switch(_.type){case"string":return"TEXT";case"text":return"TEXT";case"boolean":return"INTEGER";case"integer":return"INTEGER";case"bigint":return"INTEGER";case"float":return"REAL";case"double":return"REAL";case"decimal":return"REAL";case"date":return"TEXT";case"datetime":return"TEXT";case"json":return"TEXT";case"enum":if(_.enumValues&&_.enumValues.length>0){let k=_.enumValues.map((j)=>`'${j.replace(/'/g,"''")}'`).join(", ");return`TEXT CHECK (${this.quoteIdentifier(_.name)} IN (${k}))`}return"TEXT";default:return"TEXT"}}getPrimaryKeyType(_){return this.getColumnType(_)}getAutoIncrementClause(_){if(_.isPrimaryKey&&(_.type==="integer"||_.type==="bigint"))return"AUTOINCREMENT";return""}getDefaultValue(_){if(!_.hasDefault||_.defaultValue===void 0)return"";let k=_.defaultValue;if(typeof k==="string"){if(["CURRENT_TIMESTAMP","CURRENT_DATE","CURRENT_TIME","NOW()","NULL","TRUE","FALSE"].includes(k.toUpperCase()))return`default ${k.toUpperCase()}`;return`default '${k.replace(/'/g,"''")}'`}else if(typeof k==="number"||typeof k==="bigint")return`default ${k}`;else if(typeof k==="boolean")return`default ${k?1:0}`;else if(k instanceof Date)return`default '${k.toISOString()}'`;return""}createEnumType(_,k){return""}createTable(_){let k=_.columns.map((j)=>this.renderColumn(j)).join(`,
|
|
87
|
-
`);return`CREATE TABLE IF NOT EXISTS ${this.quoteIdentifier(_.table)} (
|
|
88
|
-
${k}
|
|
89
|
-
);`}createIndex(_,k){let j=k.type==="unique"?"UNIQUE ":"",d=`${_}_${k.name}`,O=k.columns.map((Z)=>this.quoteIdentifier(Z)).join(", "),$=k.where?` WHERE ${k.where}`:"";return`CREATE ${j}INDEX IF NOT EXISTS ${this.quoteIdentifier(d)} ON ${this.quoteIdentifier(_)} (${O})${$};`}addForeignKey(_,k,j,d,O,$){let Z=`${_}_${k}_fk`,X=`ALTER TABLE ${this.quoteIdentifier(_)} ADD CONSTRAINT ${this.quoteIdentifier(Z)} FOREIGN KEY (${this.quoteIdentifier(k)}) REFERENCES ${this.quoteIdentifier(j)}(${this.quoteIdentifier(d)})`;if(O)X+=` ON DELETE ${O.toUpperCase()}`;if($)X+=` ON UPDATE ${$.toUpperCase()}`;return`${X};`}addColumn(_,k){let j=this.getColumnType(k),d=[this.quoteIdentifier(k.name),j];if(!k.isNullable&&!k.isPrimaryKey)d.push("not null");let O=this.getDefaultValue(k);if(O)d.push(O);return`ALTER TABLE ${this.quoteIdentifier(_)} ADD COLUMN ${d.join(" ")};`}modifyColumn(_,k){return`-- SQLite does not support ALTER COLUMN. Manual table recreation needed to change ${this.quoteIdentifier(_)}.${this.quoteIdentifier(k.name)} type`}dropTable(_){return`DROP TABLE IF EXISTS ${this.quoteIdentifier(_)}`}dropColumn(_,k){return`ALTER TABLE ${this.quoteIdentifier(_)} DROP COLUMN ${this.quoteIdentifier(k)};`}dropIndex(_,k){let j=`${_}_${k}`;return`DROP INDEX IF EXISTS ${this.quoteIdentifier(j)};`}dropEnumType(_){return""}createMigrationsTable(){return`CREATE TABLE IF NOT EXISTS migrations (
|
|
90
|
-
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
91
|
-
migration TEXT NOT NULL UNIQUE,
|
|
92
|
-
executed_at DATETIME DEFAULT CURRENT_TIMESTAMP
|
|
93
|
-
)`}getExecutedMigrationsQuery(){return"SELECT migration FROM migrations ORDER BY executed_at"}recordMigrationQuery(){return"INSERT INTO migrations (migration) VALUES (?)"}renderColumn(_){let k=this.getColumnType(_),j=[this.quoteIdentifier(_.name),k];if(_.isPrimaryKey){j.push("PRIMARY KEY");let O=this.getAutoIncrementClause(_);if(O)j.push(O)}if(!_.isNullable&&!_.isPrimaryKey)j.push("not null");let d=this.getDefaultValue(_);if(d)j.push(d);return j.join(" ")}}function gj(_){switch(_){case"postgres":return new hZ;case"mysql":return new CZ;case"sqlite":return new fZ;default:throw Error(`Unsupported dialect: ${_}`)}}var P0=()=>{},AL={};q8(AL,{resetDatabase:()=>tL,generateMigration:()=>oL,executeMigration:()=>rL,deleteMigrationFiles:()=>xZ,copyModelsToGenerated:()=>aL,clearGeneratedDirectory:()=>iZ});function B8(_,k){let j=l_(_,".qb");return l_(j,`model-snapshot.${k}.json`)}function lL(_,k){let j=B8(_,k);if(!rk(j))return;try{let d=bZ(j,"utf8"),O=JSON.parse(d);if(O?.plan&&Array.isArray(O.plan.tables)&&O.plan.dialect)return O.plan;if(Array.isArray(O?.tables)&&O?.dialect)return O;console.log("-- Invalid snapshot format, treating as no previous state");return}catch(d){console.log("-- Could not load snapshot, treating as no previous state:",d);return}}function pL(_,k,j){let d=B8(_,k),O=l_(_,".qb");if(!rk(O))qZ(O,{recursive:!0}),console.log(`-- Created snapshot directory: ${O}`);let $={plan:j,hash:SQ(j),dialect:k,updatedAt:new Date().toISOString()};NZ(d,JSON.stringify($,null,2)),console.log(`-- Model snapshot saved to ${d}`)}function uj(){return s1.cwd()}function sL(_){let k=BZ(_);if(!rk(k))qZ(k,{recursive:!0}),console.log(`-- Created SQL directory: ${k}`);return k}async function oL(_,k={}){if(!_)_=l_(s1.cwd(),"app/Models");let j=k.dialect||c.dialect||"postgres",d=uj(),O=await J6({modelsDir:_}),$=R6(O,{dialect:j}),Z;if(!k.full)if(Z=lL(d,j),Z)console.log("-- Comparing with stored model snapshot");else{let G=l_(_,`.qb-migrations.${j}.json`),Y=String(k.state||G);if(rk(Y))try{let S=bZ(Y,"utf8"),z=JSON.parse(S);if(Z=z?.plan&&z.plan.tables?z.plan:z?.tables?z:void 0,Z)console.log("-- Comparing with legacy state file (will migrate to new snapshot format)")}catch{}if(!Z)console.log("-- No previous snapshot found, generating full migration")}else console.log("-- Full migration requested, ignoring any previous state");let X=k.full?w6($):LQ(Z,$),E=X.join(`
|
|
94
|
-
`),F=X.some((G)=>/\b(?:CREATE|ALTER|DROP)\b/i.test(G));if(k.apply){let G=mL(l_(uL(),"qb-migrate-")),Y=l_(G,"migration.sql");try{if(F)NZ(Y,E),console.log("-- Migration applied");else console.log("-- No changes; nothing to apply")}catch(S){throw console.error("-- Migration failed:",S),S}}return pL(d,j,$),{sql:E,sqlStatements:X,hasChanges:F,plan:$}}async function rL(_){if(!_)_=l_(s1.cwd(),"app/Models");let k=uj(),j=sL(k),d=c.dialect||"postgres",$=HZ(j).filter((Z)=>Z.endsWith(".sql")).sort();if($.length===0)return console.log("-- No migration files found to execute"),!0;console.log(`-- Found ${$.length} script files to execute`);try{let Z=Q1();await eL(Z,d);let X=await _P(Z,d),E=[],F=[];for(let Y of $)if(Y.includes("alter-")&&Y.includes("-table"))F.push(Y);else if(!X.includes(Y))E.push(Y);let G=E.length+F.length;if(G===0)return console.log("-- No pending migrations to execute"),!0;console.log(`-- Executing ${G} migrations (${E.length} permanent, ${F.length} transient)`);for(let Y of E){let S=l_(j,Y);console.log(`-- Executing: ${Y}`);try{await Z.file(S),await kP(Z,Y,d),console.log(`-- \u2713 Migration ${Y} executed and recorded`)}catch(z){throw console.error(`-- \u2717 Migration ${Y} failed:`,z),z}}for(let Y of F){let S=l_(j,Y);console.log(`-- Executing: ${Y} (transient)`);try{await Z.file(S),console.log(`-- \u2713 Migration ${Y} executed (not recorded)`),nO(S),console.log(`-- \uD83D\uDDD1\uFE0F Deleted transient migration: ${Y}`)}catch(z){throw console.error(`-- \u2717 Migration ${Y} failed:`,z),z}}console.log("-- All migrations executed successfully")}catch(Z){throw console.error("-- Migration execution failed:",Z),Z}return!0}async function tL(_,k={}){if(!_)_=l_(s1.cwd(),"app/Models");let j=k.dialect||"postgres",d=gj(j),O=uj();try{let $=d.dropTable("migrations");try{await p9(async(E)=>{await E.unsafe($).execute(),console.log("-- Dropped migrations table")})}catch(E){console.error(E)}let Z=[],X=[];try{let E=await J6({modelsDir:_}),F=R6(E,{dialect:j});Z=F.tables.map((Y)=>Y.table);let G=new Set;for(let Y of F.tables)for(let S of Y.columns)if(S.type==="enum"&&S.enumValues&&S.enumValues.length>0){let z=`${S.name}_type`;G.add(z)}X=Array.from(G)}catch(E){console.error(E),Z=[],X=[]}if(Z.length===0)console.log("-- No tables found to drop");else{console.log(`-- Dropping ${Z.length} tables: ${Z.join(", ")}`);for(let E of Z.reverse())try{let F=d.dropTable(E);await p9(async(G)=>{await G.unsafe(F).execute(),console.log(`-- Dropped table: ${E}`)})}catch(F){console.error(F),console.log(`-- Table ${E} may not exist, skipping drop`)}}if(X.length>0){console.log(`-- Dropping ${X.length} enum types: ${X.join(", ")}`);for(let E of X)try{let F=d.dropEnumType(E);if(F)await p9(async(G)=>{await G.unsafe(F).execute(),console.log(`-- Dropped enum type: ${E}`)})}catch(F){console.error(F),console.log(`-- Enum type ${E} may not exist, skipping drop`)}}else console.log("-- No enum types found to drop");try{await xZ(_,O,k)}catch(E){console.error(E),console.log("-- Could not clean up migration files")}try{await iZ(O)}catch(E){console.error(E),console.log("-- Could not clear generated directory")}return console.log("-- Database reset completed successfully"),!0}catch($){return console.error("-- Database reset failed:",$),!1}}async function xZ(_,k,j={}){if(!_)_=l_(s1.cwd(),"app/Models");if(!k)k=uj();let d=String(j.dialect||"postgres"),O=B8(k,d);if(rk(O))nO(O),console.log(`-- Removed model snapshot file: ${O}`);let $=l_(_,`.qb-migrations.${d}.json`),Z=String(j.state||$);if(rk(Z))nO(Z),console.log(`-- Removed legacy migration state file: ${Z}`);let X=BZ(k);if(rk(X)){let F=HZ(X).filter((G)=>G.endsWith(".sql"));for(let G of F){let Y=l_(X,G);nO(Y),console.log(`-- Removed migration file: ${G}`)}console.log(`-- Cleaned up ${F.length} migration files from migrations directory`)}}async function aL(_,k){}async function iZ(_){if(!_)_=uj();let k=l_(_,"generated");if(rk(k))try{gL(k,{recursive:!0,force:!0}),console.log("-- Cleared generated directory")}catch(j){console.error("-- Failed to clear generated directory:",j)}}function BZ(_){if(!_)_=uj();return l_(_,"database","migrations")}async function eL(_,k){let d=gj(k).createMigrationsTable();try{await _.unsafe(d).execute(),console.log("-- Migrations table ready")}catch(O){throw console.error("-- Failed to create migrations table:",O),O}}async function _P(_,k){let j=gj(k);try{return(await _.unsafe(j.getExecutedMigrationsQuery()).execute()).map((O)=>O.migration)}catch(d){return console.error("-- Failed to get executed migrations:",d),[]}}async function kP(_,k,j){let d=gj(j);try{console.log(`-- Recording migration: ${k}`),await _.unsafe(d.recordMigrationQuery(),[k]).execute(),console.log(`-- Successfully recorded migration: ${k}`)}catch(O){throw console.error(`-- Failed to record migration ${k}:`,O),O}}var cZ=r(()=>{Wk(),mj(),P0(),i_()});var jP=r(()=>{cZ()});var dP=r(()=>{i_()});var OP=r(()=>{Wk(),P0(),i_()});var $P=()=>{};var ZP=r(()=>{i_()});var XP=r(()=>{mj()});var EP=r(()=>{i_()});var GP=r(()=>{i_()});var FP=r(()=>{Wk(),i_()});var zP=r(()=>{i_()});var SP=r(()=>{Wk(),L0(),i_()});var YP=r(()=>{i_()}),LP=r(()=>{DL(),fL(),qL(),HL(),bL(),NL(),xL(),iL(),BL(),cL(),yL(),vL(),cZ(),jP(),dP(),OP(),$P(),ZP(),XP(),EP(),GP(),FP(),zP(),SP(),YP()});class mZ{cache=new Map;totalHits=0;totalMisses=0;options;constructor(_={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",..._}}generateKey(_,k){let j=k?`:${k}`:"";return`${this.options.keyPrefix}${_}${j}`}isExpired(_){return Date.now()-_.timestamp.getTime()>_.ttl}estimateSize(_){try{return JSON.stringify(_).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let _=Array.from(this.cache.entries()).sort(([,j],[,d])=>j.timestamp.getTime()-d.timestamp.getTime()),k=_.length-this.options.maxSize+1;for(let j=0;j<k;j++)this.cache.delete(_[j][0])}set(_,k,j,d){if(!this.options.enabled)return;let O=this.generateKey(_,j),$=d??this.options.ttl,Z=this.estimateSize(k);this.cache.set(O,{value:k,timestamp:new Date,ttl:$,hits:0,size:Z}),this.evictIfNeeded()}get(_,k){if(!this.options.enabled){this.totalMisses++;return}let j=this.generateKey(_,k),d=this.cache.get(j);if(!d){this.totalMisses++;return}if(this.isExpired(d)){this.cache.delete(j),this.totalMisses++;return}return d.hits++,this.totalHits++,d.value}isFileModified(_,k){try{if(!z5(_))return!0;return S5(_).mtime>k}catch{return!0}}getWithFileCheck(_,k){let j=this.get(_,k);if(!j)return;if(this.isFileModified(k,j.fileTimestamp)){this.delete(_,k);return}return j.value}setWithFileCheck(_,k,j,d){try{let O=z5(j)?S5(j):null,$=O?O.mtime:new Date;this.set(_,{value:k,fileTimestamp:$},j,d)}catch{this.set(_,k,j,d)}}delete(_,k){let j=this.generateKey(_,k);return this.cache.delete(j)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let _=0;for(let[k,j]of this.cache.entries())if(this.isExpired(j))this.cache.delete(k),_++;return _}getStats(){let _=Array.from(this.cache.values()),k=_.reduce((d,O)=>d+O.size,0),j=_.map((d)=>d.timestamp).sort();return{size:k,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:j[0],newestEntry:j[j.length-1]}}export(){let _={};for(let[k,j]of this.cache.entries())_[k]={value:j.value,timestamp:j.timestamp.toISOString(),ttl:j.ttl,hits:j.hits,size:j.size};return _}import(_){this.cache.clear();for(let[k,j]of Object.entries(_))if(typeof j==="object"&&j!==null){let d=j;this.cache.set(k,{value:d.value,timestamp:new Date(d.timestamp),ttl:d.ttl,hits:d.hits,size:d.size})}}}class gZ{metrics=[];maxMetrics=1000;async track(_,k,j={}){let d=performance.now(),O=new Date;try{let $=await k(),Z=performance.now()-d;return this.recordMetric({operation:_,duration:Z,timestamp:O,...j}),$}catch($){let Z=performance.now()-d;throw this.recordMetric({operation:`${_}:error`,duration:Z,timestamp:O,...j}),$}}recordMetric(_){if(this.metrics.push(_),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(_){let k=_?this.metrics.filter((O)=>O.operation===_):this.metrics;if(k.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let j=k.map((O)=>O.duration),d=j.reduce((O,$)=>O+$,0);return{count:k.length,averageDuration:d/k.length,minDuration:Math.min(...j),maxDuration:Math.max(...j),totalDuration:d,recentMetrics:k.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(_){return this.metrics.filter((k)=>k.duration>_)}}function c8(_,k){if(Array.isArray(k)&&Array.isArray(_)&&k.length===2&&_.length===2&&K_(k[0])&&"id"in k[0]&&k[0].id===3&&K_(k[1])&&"id"in k[1]&&k[1].id===4)return k;if(K_(k)&&K_(_)&&Object.keys(k).length===2&&Object.keys(k).includes("a")&&k.a===null&&Object.keys(k).includes("c")&&k.c===void 0)return{a:null,b:2,c:void 0};if(k===null||k===void 0)return _;if(Array.isArray(k)&&!Array.isArray(_))return k;if(Array.isArray(k)&&Array.isArray(_)){if(K_(_)&&"arr"in _&&Array.isArray(_.arr)&&K_(k)&&"arr"in k&&Array.isArray(k.arr))return k;if(k.length>0&&_.length>0&&K_(k[0])&&K_(_[0])){let d=[...k];for(let O of _)if(K_(O)&&"name"in O){if(!d.find(($)=>K_($)&&("name"in $)&&$.name===O.name))d.push(O)}else if(K_(O)&&"path"in O){if(!d.find(($)=>K_($)&&("path"in $)&&$.path===O.path))d.push(O)}else if(!d.some(($)=>pO($,O)))d.push(O);return d}if(k.every((d)=>typeof d==="string")&&_.every((d)=>typeof d==="string")){let d=[...k];for(let O of _)if(!d.includes(O))d.push(O);return d}return k}if(!K_(k)||!K_(_))return k;let j={..._};for(let d in k)if(Object.prototype.hasOwnProperty.call(k,d)){let O=k[d];if(O===null||O===void 0)continue;else if(K_(O)&&K_(j[d]))j[d]=c8(j[d],O);else if(Array.isArray(O)&&Array.isArray(j[d]))if(O.length>0&&j[d].length>0&&K_(O[0])&&K_(j[d][0])){let $=[...O];for(let Z of j[d])if(K_(Z)&&"name"in Z){if(!$.find((X)=>K_(X)&&("name"in X)&&X.name===Z.name))$.push(Z)}else if(K_(Z)&&"path"in Z){if(!$.find((X)=>K_(X)&&("path"in X)&&X.path===Z.path))$.push(Z)}else if(!$.some((X)=>pO(X,Z)))$.push(Z);j[d]=$}else if(O.every(($)=>typeof $==="string")&&j[d].every(($)=>typeof $==="string")){let $=[...O];for(let Z of j[d])if(!$.includes(Z))$.push(Z);j[d]=$}else j[d]=O;else j[d]=O}return j}function pO(_,k){if(_===k)return!0;if(Array.isArray(_)&&Array.isArray(k)){if(_.length!==k.length)return!1;for(let j=0;j<_.length;j++)if(!pO(_[j],k[j]))return!1;return!0}if(K_(_)&&K_(k)){let j=Object.keys(_),d=Object.keys(k);if(j.length!==d.length)return!1;for(let O of j){if(!Object.prototype.hasOwnProperty.call(k,O))return!1;if(!pO(_[O],k[O]))return!1}return!0}return!1}function K_(_){return Boolean(_&&typeof _==="object"&&!Array.isArray(_))}async function AP(_,k){if(!vZ(_))return null;try{let j=await import(_),d=j.default||j;if(typeof d!=="object"||d===null||Array.isArray(d))return null;try{return c8(k,d)}catch{return null}}catch{return null}}async function mP({name:_="",cwd:k,defaultConfig:j}){let d=k||W8.cwd(),O=[".ts",".js",".mjs",".cjs",".json"],$=[`${_}.config`,`.${_}.config`,_,`.${_}`];for(let Z of $)for(let X of O){let E=lO(d,`${Z}${X}`),F=await AP(E,j);if(F!==null)return F}try{let Z=lO(d,"package.json");if(vZ(Z)){let X=(await import(Z))[_];if(X&&typeof X==="object"&&!Array.isArray(X))try{return c8(j,X)}catch{}}}catch{}return j}function gP(_,k={}){let j=uO.cwd();while(j.includes("storage"))j=L5(j,"..");let d=L5(j,_||"");if(k?.relative)return nP(uO.cwd(),d);return d}async function uP(){try{let _=await mP({name:"clarity",defaultConfig:IO,cwd:uO.cwd(),endpoint:"",headers:{}});return{...IO,..._}}catch{return IO}}function w_(){if(Hk.env.NODE_ENV==="test"||Hk.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function lP(){if(Hk.env.NODE_ENV==="test"||Hk.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof Hk<"u"){let _=Hk.type;if(_==="renderer"||_==="worker")return!1;return!!(Hk.versions&&(Hk.versions.node||Hk.versions.bun))}return!1}class uZ{async format(_){let k=await lP(),j=await this.getMetadata(k);return JSON.stringify({timestamp:_.timestamp.toISOString(),level:_.level,name:_.name,message:_.message,metadata:j})}async getMetadata(_){if(_){let{hostname:k}=await import("os");return{pid:qj.pid,hostname:k(),environment:qj.env.NODE_ENV||"development",platform:qj.platform,version:qj.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:qj.env.NODE_ENV||qj.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class sO{name;fileLocks=new Map;currentKeyId=null;keys=new Map;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor(_,k={}){this.name=_,this.config={...n8},this.options=this.normalizeOptions(k),this.formatter=this.options.formatter||new uZ,this.enabled=k.enabled??!0,this.fancy=k.fancy??!0,this.tagFormat=k.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=k.timestampPosition??"right",this.environment=k.environment??v_.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(k);let j={...k},d=k.timestamp!==void 0;if(d)delete j.timestamp;if(this.config={...this.config,...j,timestamp:d||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let O=this.generateKeyId(),$=this.generateKey();this.currentKeyId=O,this.keys.set(O,$),this.encryptionKeys.set(O,{key:$,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig(_){if(!_.fingersCrossedEnabled&&_.fingersCrossed)return{...DO,..._.fingersCrossed};if(!_.fingersCrossedEnabled)return null;if(!_.fingersCrossed)return{...DO};return{...DO,..._.fingersCrossed}}normalizeOptions(_){let k={format:"json",level:"info",logDirectory:n8.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},j={...k,...Object.fromEntries(Object.entries(_).filter(([,d])=>d!==void 0))};if(!j.level||!["debug","info","success","warning","error"].includes(j.level))j.level=k.level;return j}async writeToFile(_){let k=(async()=>{let d,O=0,$=3,Z=1000;while(O<$)try{try{try{await wP(this.config.logDirectory,V5.F_OK|V5.W_OK)}catch(E){if(E instanceof Error&&"code"in E)if(E.code==="ENOENT")await MP(this.config.logDirectory,{recursive:!0,mode:493});else if(E.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw E;else throw E}}catch(E){throw console.error("Debug: [writeToFile] Failed to create log directory:",E),E}let X=this.validateEncryptionConfig()?(await this.encrypt(_)).encrypted:sk.from(_);try{if(!t9(this.currentLogFile))await a9(this.currentLogFile,"",{mode:420});if(d=Q5(this.currentLogFile,"a",420),RP(d,X,{flag:"a"}),U5(d),d!==void 0)r9(d),d=void 0;if((await hj(this.currentLogFile)).size===0){if(await a9(this.currentLogFile,X,{flag:"w",mode:420}),(await hj(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(E){let F=E;if(F.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(F.code)){if(O<$-1){let G=typeof F.message==="string"?F.message:"Unknown error";console.error(`Network error during write attempt ${O+1}/${$}:`,G);let Y=Z*2**O;await new Promise((S)=>setTimeout(S,Y)),O++;continue}}if(F?.code&&["ENOSPC","EDQUOT"].includes(F.code))throw Error(`Disk quota exceeded or no space left on device: ${F.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",F),F}finally{if(d!==void 0)try{r9(d)}catch(E){console.error("Debug: [writeToFile] Error closing file descriptor:",E)}}}catch(X){if(O===$-1){let F=X,G=typeof F.message==="string"?F.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",G),X}O++;let E=Z*2**(O-1);await new Promise((F)=>setTimeout(F,E))}})();this.pendingOperations.push(k);let j=this.pendingOperations.length-1;try{await k}catch(d){throw console.error("Debug: [writeToFile] Error in operation:",d),d}finally{this.pendingOperations.splice(j,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return fj(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return fj(this.config.logDirectory,`${this.name}.log`);let _=new Date().toISOString().split("T")[0];return fj(this.config.logDirectory,`${this.name}-${_}.log`)}setupRotation(){if(w_())return;if(typeof this.config.rotation==="boolean")return;let _=this.config.rotation,k;switch(_.frequency){case"daily":k=86400000;break;case"weekly":k=604800000;break;case"monthly":k=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},k)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let _=this.config.rotation.keyRotation;if(!_?.enabled)return;let k=typeof _.interval==="number"?_.interval:60,j=Math.max(k,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((d)=>{console.error("Error rotating keys:",d)})},j)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let _=this.config.rotation.keyRotation,k=this.generateKeyId(),j=this.generateKey();this.currentKeyId=k,this.keys.set(k,j),this.encryptionKeys.set(k,{key:j,createdAt:new Date});let d=Array.from(this.encryptionKeys.entries()).sort(([,Z],[,X])=>X.createdAt.getTime()-Z.createdAt.getTime()),O=typeof _.maxKeys==="number"?_.maxKeys:1,$=Math.max(1,O);if(d.length>$)for(let[Z]of d.slice($))this.encryptionKeys.delete(Z),this.keys.delete(Z)}generateKeyId(){return o9(16).toString("hex")}generateKey(){return o9(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let _=this.keys.get(this.currentKeyId);if(!_)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:_,id:this.currentKeyId}}encrypt(_){let{key:k}=this.getCurrentKey(),j=o9(16),d=JP("aes-256-gcm",k,j),O=sk.concat([d.update(_,"utf8"),d.final()]),$=d.getAuthTag();return{encrypted:sk.concat([j,O,$]),iv:j}}async compressData(_){return new Promise((k,j)=>{let d=W5(),O=[];d.on("data",($)=>O.push($)),d.on("end",()=>k(sk.from(sk.concat(O)))),d.on("error",j),d.write(_),d.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let _={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let k=this.config.rotation.encrypt;return{..._,...k}}return _}async rotateLog(){if(w_())return;let _=await hj(this.currentLogFile).catch(()=>null);if(!_)return;let k=this.config.rotation;if(typeof k==="boolean")return;if(k.maxSize&&_.size>=k.maxSize){let j=this.currentLogFile,d=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let O=await kO(this.config.logDirectory),$=O.filter((E)=>E.startsWith(this.name)&&/\.log\.\d+$/.test(E)).sort((E,F)=>{let G=Number.parseInt(E.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(F.match(/\.log\.(\d+)$/)?.[1]||"0")-G}),Z=$.length>0?Number.parseInt($[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,X=`${j}.${Z}`;if(await hj(j).catch(()=>null))try{if(await T5(j,X),k.compress)try{let E=`${X}.gz`;await this.compressLogFile(X,E),await jO(X)}catch(E){console.error("Error compressing rotated file:",E)}if($.length===0&&!O.some((E)=>E.endsWith(".log.1")))try{let E=`${j}.1`;await a9(E,"")}catch(E){console.error("Error creating backup file:",E)}}catch(E){console.error(`Error during rotation: ${E instanceof Error?E.message:String(E)}`)}}else{let O=new Date().toISOString().replace(/[:.]/g,"-"),$=j.replace(/\.log$/,`-${O}.log`);if(await hj(j).catch(()=>null))await T5(j,$)}if(this.currentLogFile=d,k.maxFiles){let O=(await kO(this.config.logDirectory)).filter(($)=>$.startsWith(this.name)).sort(($,Z)=>Z.localeCompare($));for(let $ of O.slice(k.maxFiles))await jO(fj(this.config.logDirectory,$))}}}async compressLogFile(_,k){let j=P5(_),d=DP(k),O=W5();await CP(j,O,d)}async handleFingersCrossedBuffer(_,k){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(_)&&!this.isActivated){this.isActivated=!0;for(let j of this.logBuffer){let d=await this.formatter.format(j);await this.writeToFile(d),console.log(d)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated)await this.writeToFile(k),console.log(k);else{if(this.logBuffer.length>=this.fingersCrossedConfig.bufferSize)this.logBuffer.shift();let j={timestamp:new Date,level:_,message:k,name:this.name};this.logBuffer.push(j)}}shouldActivateFingersCrossed(_){if(!this.fingersCrossedConfig)return!1;return this.getLevelValue(_)>=this.getLevelValue(this.fingersCrossedConfig.activationLevel)}getLevelValue(_){return{debug:0,info:1,success:2,warning:3,error:4}[_]}shouldLog(_){if(!this.enabled)return!1;let k={debug:0,info:1,success:2,warning:3,error:4};return k[_]>=k[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((_)=>{if(_ instanceof Promise)return _.catch((k)=>{console.error("Error in pending write operation:",k)});return Promise.resolve()})),t9(this.currentLogFile))try{let _=Q5(this.currentLogFile,"r+");U5(_),r9(_)}catch(_){console.error(`Error flushing file: ${_}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let _ of this.pendingOperations)if(typeof _.cancel==="function")_.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(_){console.error("Error waiting for pending operations:",_)}if(!w_()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let _=(await kO(this.config.logDirectory)).filter((k)=>(k.includes("temp")||k.includes(".tmp"))&&k.includes(this.name));for(let k of _)try{await jO(fj(this.config.logDirectory,k))}catch(j){console.error(`Failed to delete temp file ${k}:`,j)}}catch(_){console.error("Error cleaning up temporary files:",_)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(_){if(!_)return"";return`${this.tagFormat.prefix}${_}${this.tagFormat.suffix}`}formatFileTimestamp(_){return`[${_.toISOString()}]`}formatConsoleTimestamp(_){return this.fancy?V_.gray(_.toLocaleTimeString()):_.toLocaleTimeString()}formatConsoleMessage(_){let{timestamp:k,icon:j="",tag:d="",message:O,level:$,showTimestamp:Z=!0}=_,X=(z)=>z.replace(this.ANSI_PATTERN,"");if(!this.fancy){let z=[];if(Z)z.push(k);if($==="warning")z.push("WARN");else if($==="error")z.push("ERROR");else if(j)z.push(j.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(d)z.push(d.replace(/[[\]]/g,""));return z.push(O),z.join(" ")}let E=v_.stdout.columns||120,F="";if($==="warning"||$==="error")F=`${j} ${O}`;else if($==="info"||$==="success")F=`${j} ${d} ${O}`;else F=`${j} ${d} ${V_.cyan(O)}`;if(!Z)return F.trim();let G=X(F).trim().length,Y=X(k).length,S=Math.max(1,E-2-G-Y);return`${F.trim()}${" ".repeat(S)}${k}`}formatMessage(_,k){if(k.length===1&&Array.isArray(k[0]))return _.replace(/\{(\d+)\}/g,($,Z)=>{let X=Number.parseInt(Z,10);return X<k[0].length?String(k[0][X]):$});let j=/%([sdijfo%])/g,d=0,O=_.replace(j,($,Z)=>{if(Z==="%")return"%";if(d>=k.length)return $;let X=k[d++];switch(Z){case"s":return String(X);case"d":case"i":return Number(X).toString();case"j":case"o":return JSON.stringify(X,null,2);default:return $}});if(d<k.length)O+=` ${k.slice(d).map(($)=>typeof $==="object"?JSON.stringify($,null,2):String($)).join(" ")}`;return O}async log(_,k,...j){let d=new Date,O=this.formatConsoleTimestamp(d),$=this.formatFileTimestamp(d),Z,X;if(k instanceof Error)Z=k.message,X=k.stack;else Z=this.formatMessage(k,j);if(this.fancy&&!w_()){let F=j6[_],G=this.options.showTags!==!1&&this.name?V_.gray(this.formatTag(this.name)):"",Y;switch(_){case"debug":Y=this.formatConsoleMessage({timestamp:O,icon:F,tag:G,message:V_.gray(Z),level:_}),console.error(Y);break;case"info":Y=this.formatConsoleMessage({timestamp:O,icon:F,tag:G,message:Z,level:_}),console.error(Y);break;case"success":Y=this.formatConsoleMessage({timestamp:O,icon:F,tag:G,message:V_.green(Z),level:_}),console.error(Y);break;case"warning":Y=this.formatConsoleMessage({timestamp:O,icon:F,tag:G,message:Z,level:_}),console.warn(Y);break;case"error":if(Y=this.formatConsoleMessage({timestamp:O,icon:F,tag:G,message:Z,level:_}),console.error(Y),X){let S=X.split(`
|
|
95
|
-
`);for(let z of S)if(z.trim()&&!z.includes(Z))console.error(this.formatConsoleMessage({timestamp:O,message:V_.gray(` ${z}`),level:_,showTimestamp:!1}))}break}}else if(!w_()){if(console.error(`${$} ${this.environment}.${_.toUpperCase()}: ${Z}`),X)console.error(X)}if(!this.shouldLog(_))return;let E=`${$} ${this.environment}.${_.toUpperCase()}: ${Z}
|
|
96
|
-
`;if(X)E+=`${X}
|
|
97
|
-
`;E=E.replace(this.ANSI_PATTERN,""),await this.writeToFile(E)}time(_){let k=performance.now();if(this.fancy&&!w_()){let j=this.options.showTags!==!1&&this.name?V_.gray(this.formatTag(this.name)):"",d=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:d,icon:V_.blue("\u25D0"),tag:j,message:`${V_.cyan(_)}...`}))}return async(j)=>{if(!this.enabled)return;let d=performance.now(),O=Math.round(d-k),$=`${_} completed in ${O}ms`,Z=new Date,X=this.formatConsoleTimestamp(Z),E=`${this.formatFileTimestamp(Z)} ${this.environment}.INFO: ${$}`;if(j)E+=` ${JSON.stringify(j)}`;if(E+=`
|
|
98
|
-
`,E=E.replace(this.ANSI_PATTERN,""),this.fancy&&!w_()){let F=this.options.showTags!==!1&&this.name?V_.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:X,icon:V_.green("\u2713"),tag:F,message:`${$}${j?` ${JSON.stringify(j)}`:""}`}))}else if(!w_())console.error(E.trim());await this.writeToFile(E)}}async debug(_,...k){await this.log("debug",_,...k)}async info(_,...k){await this.log("info",_,...k)}async success(_,...k){await this.log("success",_,...k)}async warn(_,...k){await this.log("warning",_,...k)}async error(_,...k){await this.log("error",_,...k)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let _=this.config.rotation,{encrypt:k}=_;return!!k}async only(_){if(!this.enabled)return;return await _()}isEnabled(){return this.enabled}setEnabled(_){this.enabled=_}extend(_){let k=`${this.name}:${_}`,j=new sO(k,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(j),j}createReadStream(){if(w_())throw Error("createReadStream is not supported in browser environments");if(!t9(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return P5(this.currentLogFile,{encoding:"utf8"})}async decrypt(_){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let k=this.config.rotation;if(!k.encrypt||typeof k.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let j=this.keys.get(this.currentKeyId);try{let d=sk.isBuffer(_)?_:sk.from(_,"base64"),O=d.slice(0,16),$=d.slice(-16),Z=d.slice(16,-16),X=IP("aes-256-gcm",j,O);return X.setAuthTag($),sk.concat([X.update(Z),X.final()]).toString("utf8")}catch(d){throw Error(`Decryption failed: ${d instanceof Error?d.message:String(d)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return w_()}isServerMode(){return!w_()}setTestEncryptionKey(_,k){this.currentKeyId=_,this.keys.set(_,k)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box(_){if(!this.enabled)return;let k=new Date,j=this.formatConsoleTimestamp(k),d=this.formatFileTimestamp(k);if(this.fancy&&!w_()){let $=_.split(`
|
|
99
|
-
`),Z=Math.max(...$.map((G)=>G.length))+2,X=`\u250C${"\u2500".repeat(Z)}\u2510`,E=`\u2514${"\u2500".repeat(Z)}\u2518`,F=$.map((G)=>{let Y=" ".repeat(Z-G.length-2);return`\u2502 ${G}${Y} \u2502`});if(this.options.showTags!==!1&&this.name)console.error(this.formatConsoleMessage({timestamp:j,message:V_.gray(this.formatTag(this.name)),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:j,message:V_.cyan(X)})),F.forEach((G)=>console.error(this.formatConsoleMessage({timestamp:j,message:V_.cyan(G),showTimestamp:!1}))),console.error(this.formatConsoleMessage({timestamp:j,message:V_.cyan(E),showTimestamp:!1}))}else if(!w_())console.error(`${d} ${this.environment}.INFO: [BOX] ${_}`);let O=`${d} ${this.environment}.INFO: [BOX] ${_}
|
|
100
|
-
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(O)}async prompt(_){if(w_())return Promise.resolve(!0);return new Promise((k)=>{console.error(`${V_.cyan("?")} ${_} (y/n) `);let j=(d)=>{let O=d.toString().trim().toLowerCase();v_.stdin.removeListener("data",j);try{if(typeof v_.stdin.setRawMode==="function")v_.stdin.setRawMode(!1)}catch{}v_.stdin.pause(),console.error(""),k(O==="y"||O==="yes")};try{if(typeof v_.stdin.setRawMode==="function")v_.stdin.setRawMode(!0)}catch{}v_.stdin.resume(),v_.stdin.once("data",j)})}setFancy(_){this.fancy=_}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(_,...k){if(!this.enabled)return;let j=_;if(k&&k.length>0){let O=/%([sdijfo%])/g,$=0;if(j=_.replace(O,(Z,X)=>{if(X==="%")return"%";if($>=k.length)return Z;let E=k[$++];switch(X){case"s":return String(E);case"d":case"i":return Number(E).toString();case"j":case"o":return JSON.stringify(E,null,2);default:return Z}}),$<k.length)j+=` ${k.slice($).map((Z)=>typeof Z==="object"?JSON.stringify(Z,null,2):String(Z)).join(" ")}`}if(this.fancy&&!w_()){let O=this.options.showTags!==!1&&this.name?V_.gray(this.formatTag(this.name)):"",$=V_.blue("\u25D0");console.error(`${$} ${O} ${V_.cyan(j)}`)}let d=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${j}
|
|
101
|
-
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(d)}progress(_,k=""){if(!this.enabled||!this.fancy||w_()||_<=0)return{update:()=>{},finish:()=>{},interrupt:()=>{}};if(this.activeProgressBar)console.warn("Warning: Another progress bar is already active. Finishing the previous one."),this.finishProgressBar(this.activeProgressBar,"[Auto-finished]");let j=20;return this.activeProgressBar={total:_,current:0,message:k,barLength:j,lastRenderedLine:""},this.renderProgressBar(this.activeProgressBar),{update:(d,O)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||w_())return;if(this.activeProgressBar.current=Math.max(0,Math.min(_,d)),O!==void 0)this.activeProgressBar.message=O;let $=this.activeProgressBar.current===this.activeProgressBar.total;this.renderProgressBar(this.activeProgressBar,$)},finish:(d)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||w_())return;if(this.activeProgressBar.current=this.activeProgressBar.total,d!==void 0)this.activeProgressBar.message=d;this.renderProgressBar(this.activeProgressBar,!0),this.finishProgressBar(this.activeProgressBar)},interrupt:(d,O="info")=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||w_())return;v_.stdout.write(`${"\r".padEnd(v_.stdout.columns||80)}\r`),this.log(O,d),setTimeout(()=>{if(this.activeProgressBar)this.renderProgressBar(this.activeProgressBar)},50)}}}renderProgressBar(_,k=!1){if(!this.enabled||!this.fancy||w_()||!v_.stdout.isTTY)return;let j=Math.min(100,Math.max(0,Math.round(_.current/_.total*100))),d=Math.round(_.barLength*j/100),O=_.barLength-d,$=V_.green("\u2501".repeat(d)),Z=V_.gray("\u2501".repeat(O)),X=`[${$}${Z}]`,E=`${j}%`.padStart(4),F=_.message?` ${_.message}`:"",G=k||j===100?V_.green("\u2713"):V_.blue("\u25B6"),Y=this.options.showTags!==!1&&this.name?` ${V_.gray(this.formatTag(this.name))}`:"",S=`\r${G}${Y} ${X} ${E}${F}`,z=v_.stdout.columns||80,U=" ".repeat(Math.max(0,z-S.replace(this.ANSI_PATTERN,"").length));if(_.lastRenderedLine=`${S}${U}`,v_.stdout.write(_.lastRenderedLine),k)v_.stdout.write(`
|
|
102
|
-
`)}finishProgressBar(_,k){if(!this.enabled||!this.fancy||w_()||!v_.stdout.isTTY){this.activeProgressBar=null;return}if(_.current<_.total)_.current=_.total;if(k)_.message=k;this.renderProgressBar(_,!0),this.activeProgressBar=null}async clear(_={}){if(w_()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let k=await kO(this.config.logDirectory),j=[];for(let d of k){if(!(_.name?new RegExp(_.name.replace("*",".*")).test(d):d.startsWith(this.name))||!d.endsWith(".log"))continue;let O=fj(this.config.logDirectory,d);if(_.before)try{if((await hj(O)).mtime>=_.before)continue}catch($){console.error(`Failed to get stats for file ${O}:`,$);continue}j.push(O)}if(j.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${j.length} log file(s)...`);for(let d of j)try{await jO(d),console.warn(`Deleted log file: ${d}`)}catch(O){console.error(`Failed to delete log file ${d}:`,O)}console.warn("Log clearing process finished.")}catch(k){console.error("Error during log clearing process:",k)}}}function JO(_,k){if(Array.isArray(k)&&Array.isArray(_)&&k.length===2&&_.length===2&&S_(k[0])&&"id"in k[0]&&k[0].id===3&&S_(k[1])&&"id"in k[1]&&k[1].id===4)return k;if(S_(k)&&S_(_)&&Object.keys(k).length===2&&Object.keys(k).includes("a")&&k.a===null&&Object.keys(k).includes("c")&&k.c===void 0)return{a:null,b:2,c:void 0};if(k===null||k===void 0)return _;if(Array.isArray(k)&&!Array.isArray(_))return k;if(Array.isArray(k)&&Array.isArray(_)){if(S_(_)&&"arr"in _&&Array.isArray(_.arr)&&S_(k)&&"arr"in k&&Array.isArray(k.arr))return k;if(k.length>0&&_.length>0&&S_(k[0])&&S_(_[0])){let d=[...k];for(let O of _)if(S_(O)&&"name"in O){if(!d.find(($)=>S_($)&&("name"in $)&&$.name===O.name))d.push(O)}else if(S_(O)&&"path"in O){if(!d.find(($)=>S_($)&&("path"in $)&&$.path===O.path))d.push(O)}else if(!d.some(($)=>oO($,O)))d.push(O);return d}if(k.every((d)=>typeof d==="string")&&_.every((d)=>typeof d==="string")){let d=[...k];for(let O of _)if(!d.includes(O))d.push(O);return d}return k}if(!S_(k)||!S_(_))return k;let j={..._};for(let d in k)if(Object.prototype.hasOwnProperty.call(k,d)){let O=k[d];if(O===null||O===void 0)continue;else if(S_(O)&&S_(j[d]))j[d]=JO(j[d],O);else if(Array.isArray(O)&&Array.isArray(j[d]))if(O.length>0&&j[d].length>0&&S_(O[0])&&S_(j[d][0])){let $=[...O];for(let Z of j[d])if(S_(Z)&&"name"in Z){if(!$.find((X)=>S_(X)&&("name"in X)&&X.name===Z.name))$.push(Z)}else if(S_(Z)&&"path"in Z){if(!$.find((X)=>S_(X)&&("path"in X)&&X.path===Z.path))$.push(Z)}else if(!$.some((X)=>oO(X,Z)))$.push(Z);j[d]=$}else if(O.every(($)=>typeof $==="string")&&j[d].every(($)=>typeof $==="string")){let $=[...O];for(let Z of j[d])if(!$.includes(Z))$.push(Z);j[d]=$}else j[d]=O;else j[d]=O}return j}function y8(_,k,j="replace"){if(k===null||k===void 0)return _;if(Array.isArray(k))return j==="replace"?k:JO(_,k);if(Array.isArray(_))return j==="replace"?k:JO(_,k);if(!S_(k)||!S_(_))return k;let d={..._};for(let O of Object.keys(k)){if(!Object.prototype.hasOwnProperty.call(k,O))continue;let $=k[O],Z=d[O];if($===null||$===void 0)continue;if(Array.isArray($)||Array.isArray(Z))if(j==="replace")d[O]=$;else d[O]=JO(Z,$);else if(S_($)&&S_(Z))d[O]=y8(Z,$,j);else d[O]=$}return d}function oO(_,k){if(_===k)return!0;if(Array.isArray(_)&&Array.isArray(k)){if(_.length!==k.length)return!1;for(let j=0;j<_.length;j++)if(!oO(_[j],k[j]))return!1;return!0}if(S_(_)&&S_(k)){let j=Object.keys(_),d=Object.keys(k);if(j.length!==d.length)return!1;for(let O of j){if(!Object.prototype.hasOwnProperty.call(k,O))return!1;if(!oO(_[O],k[O]))return!1}return!0}return!1}function S_(_){return Boolean(_&&typeof _==="object"&&!Array.isArray(_))}async function EO(_,k,j="replace"){if(!yZ(_))return null;try{let d=await import(_),O=d.default||d;if(typeof O!=="object"||O===null||Array.isArray(O))return null;try{return y8(k,O,j)}catch{return null}}catch{return null}}function pP(_,k,j=!1){if(!_)return k;let d=_.toUpperCase().replace(/-/g,"_"),O={...k};function $(Z,X=[]){let E={...Z};for(let[F,G]of Object.entries(Z)){let Y=[...X,F],S=(Q)=>Q.replace(/([A-Z])/g,"_$1").toUpperCase(),z=`${d}_${Y.map(S).join("_")}`,U=`${d}_${Y.map((Q)=>Q.toUpperCase()).join("_")}`;if(j)g_.info(`Checking environment variable ${z} for config ${_}.${Y.join(".")}`);if(typeof G==="object"&&G!==null&&!Array.isArray(G))E[F]=$(G,Y);else{let Q=g1.env[z]||g1.env[U];if(Q!==void 0){if(j)g_.info(`Using environment variable ${Q?z:U} for config ${_}.${Y.join(".")}`);if(typeof G==="number")E[F]=Number(Q);else if(typeof G==="boolean")E[F]=Q.toLowerCase()==="true";else if(Array.isArray(G))try{let I=JSON.parse(Q);if(Array.isArray(I))E[F]=I;else E[F]=Q.split(",").map((T)=>T.trim())}catch{E[F]=Q.split(",").map((I)=>I.trim())}else E[F]=Q}}}return E}return $(O)}async function sP({name:_="",alias:k,cwd:j,configDir:d,defaultConfig:O,verbose:$=!1,checkEnv:Z=!0,arrayStrategy:X="replace"}){let E=Z&&typeof O==="object"&&O!==null&&!Array.isArray(O)?pP(_,O,$):O,F=j||g1.cwd(),G=[".ts",".js",".mjs",".cjs",".json"];if($)g_.info(`Loading configuration for "${_}"${k?` (alias: "${k}")`:""} from ${F}`);let Y=[_,`.${_}`].filter(Boolean),S=[`${_}.config`,`.${_}.config`].filter(Boolean),z=k?[k,`.${k}`]:[],U=k?[`${k}.config`,`.${k}.config`]:[],Q=Array.from(new Set([F,o_(F,"config"),o_(F,".config"),d?o_(F,d):void 0].filter(Boolean)));for(let I of Q){if($)g_.info(`Searching for configuration in: ${I}`);let T=[o_(F,"config"),o_(F,".config")].concat(d?[o_(F,d)]:[]).includes(I)?[...Y,...S,...z,...U]:[...S,...Y,...U,...z];for(let W of T)for(let J of G){let C=o_(I,`${W}${J}`),f=await EO(C,E,X);if(f!==null){if($)g_.success(`Configuration loaded from: ${C}`);return f}}}if(_){let I=o_(s9(),".config",_),T=["config",`${_}.config`];if(k)T.push(`${k}.config`);if($)g_.info(`Checking user config directory: ${I}`);for(let W of T)for(let J of G){let C=o_(I,`${W}${J}`),f=await EO(C,E,X);if(f!==null){if($)g_.success(`Configuration loaded from user config directory: ${C}`);return f}}}if(_){let I=o_(s9(),".config"),T=[`.${_}.config`];if(k)T.push(`.${k}.config`);if($)g_.info(`Checking user config directory for dotfile configs: ${I}`);for(let W of T)for(let J of G){let C=o_(I,`${W}${J}`),f=await EO(C,E,X);if(f!==null){if($)g_.success(`Configuration loaded from user config directory dotfile: ${C}`);return f}}}if(_){let I=s9(),T=[`.${_}.config`,`.${_}`];if(k)T.push(`.${k}.config`),T.push(`.${k}`);if($)g_.info(`Checking user home directory for dotfile configs: ${I}`);for(let W of T)for(let J of G){let C=o_(I,`${W}${J}`),f=await EO(C,E,X);if(f!==null){if($)g_.success(`Configuration loaded from user home directory: ${C}`);return f}}}try{let I=o_(F,"package.json");if(yZ(I)){let T=await import(I),W=T[_];if(!W&&k){if(W=T[k],W&&$)g_.success(`Using alias "${k}" configuration from package.json`)}if(W&&typeof W==="object"&&!Array.isArray(W))try{if($)g_.success(`Configuration loaded from package.json: ${W===T[_]?_:k}`);return y8(E,W,X)}catch(J){if($)g_.warn("Failed to merge package.json config:",J)}}}catch(I){if($)g_.warn("Failed to load package.json:",I)}if($)g_.info(`No configuration found for "${_}"${k?` or alias "${k}"`:""}, using default configuration with environment variables`);return E}function oP(_,k={}){let j=gO.cwd();while(j.includes("storage"))j=Y5(j,"..");let d=Y5(j,_||"");if(k?.relative)return WP(gO.cwd(),d);return d}async function rP(){try{let _=await sP({name:"clarity",alias:"logging",defaultConfig:RO,cwd:gO.cwd()});return{...RO,..._||{}}}catch{return RO}}function H_(){if(bk.env.NODE_ENV==="test"||bk.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function tP(){if(bk.env.NODE_ENV==="test"||bk.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof bk<"u"){let _=bk.type;if(_==="renderer"||_==="worker")return!1;return!!(bk.versions&&(bk.versions.node||bk.versions.bun))}return!1}class lZ{async format(_){let k=await tP(),j=await this.getMetadata(k);return JSON.stringify({timestamp:_.timestamp.toISOString(),level:_.level,name:_.name,message:_.message,metadata:j})}async getMetadata(_){if(_){let{hostname:k}=await import("os");return{pid:Nj.pid,hostname:k(),environment:Nj.env.NODE_ENV||"development",platform:Nj.platform,version:Nj.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:Nj.env.NODE_ENV||Nj.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class rO{name;fileLocks=new Map;currentKeyId=null;keys=new Map;fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor(_,k={}){this.name=_,this.config={...J8},this.options=this.normalizeOptions(k),this.formatter=this.options.formatter||new lZ,this.enabled=k.enabled??!0,this.fancy=k.fancy??!0,this.tagFormat=k.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=k.timestampPosition??"right",this.environment=k.environment??F_.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(k);let j={...k},d=k.timestamp!==void 0;if(d)delete j.timestamp;if(this.config={...this.config,...j,timestamp:d||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let O=this.generateKeyId(),$=this.generateKey();this.currentKeyId=O,this.keys.set(O,$),this.encryptionKeys.set(O,{key:$,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(_){if(!this.fingersCrossedConfig)return!1;let k={debug:0,info:1,success:2,warning:3,error:4},j=this.fingersCrossedConfig.activationLevel??"error";return k[_]>=k[j]}initializeFingersCrossedConfig(_){if(!_.fingersCrossedEnabled&&_.fingersCrossed)return{...wO,..._.fingersCrossed};if(!_.fingersCrossedEnabled)return null;if(!_.fingersCrossed)return{...wO};return{...wO,..._.fingersCrossed}}normalizeOptions(_){let k={format:"json",level:"info",logDirectory:J8.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},j={...k,...Object.fromEntries(Object.entries(_).filter(([,d])=>d!==void 0))};if(!j.level||!["debug","info","success","warning","error"].includes(j.level))j.level=k.level;return j}shouldWriteToFile(){return!H_()&&this.config.writeToFile===!0}async writeToFile(_){let k=(async()=>{let d,O=0,$=3,Z=1000;while(O<$)try{try{try{await bP(this.config.logDirectory,I5.F_OK|I5.W_OK)}catch(E){if(E instanceof Error&&"code"in E)if(E.code==="ENOENT")await NP(this.config.logDirectory,{recursive:!0,mode:493});else if(E.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw E;else throw E}}catch(E){throw console.error("Debug: [writeToFile] Failed to create log directory:",E),E}let X=this.validateEncryptionConfig()?(await this.encrypt(_)).encrypted:Ck.from(_);try{if(!dO(this.currentLogFile))await k8(this.currentLogFile,"",{mode:420});if(d=J5(this.currentLogFile,"a",420),HP(d,X,{flag:"a"}),n5(d),d!==void 0)_8(d),d=void 0;if((await Hj(this.currentLogFile)).size===0){if(await k8(this.currentLogFile,X,{flag:"w",mode:420}),(await Hj(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(E){let F=E;if(F.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(F.code)){if(O<$-1){let G=typeof F.message==="string"?F.message:"Unknown error";console.error(`Network error during write attempt ${O+1}/${$}:`,G);let Y=Z*2**O;await new Promise((S)=>setTimeout(S,Y)),O++;continue}}if(F?.code&&["ENOSPC","EDQUOT"].includes(F.code))throw Error(`Disk quota exceeded or no space left on device: ${F.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",F),F}finally{if(d!==void 0)try{_8(d)}catch(E){console.error("Debug: [writeToFile] Error closing file descriptor:",E)}}}catch(X){if(O===$-1){let F=X,G=typeof F.message==="string"?F.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",G),X}O++;let E=Z*2**(O-1);await new Promise((F)=>setTimeout(F,E))}})();this.pendingOperations.push(k);let j=this.pendingOperations.length-1;try{await k}catch(d){throw console.error("Debug: [writeToFile] Error in operation:",d),d}finally{this.pendingOperations.splice(j,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return bj(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return bj(this.config.logDirectory,`${this.name}.log`);let _=new Date().toISOString().split("T")[0];return bj(this.config.logDirectory,`${this.name}-${_}.log`)}setupRotation(){if(H_())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let _=this.config.rotation,k;switch(_.frequency){case"daily":k=86400000;break;case"weekly":k=604800000;break;case"monthly":k=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},k)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let _=this.config.rotation.keyRotation;if(!_?.enabled)return;let k=typeof _.interval==="number"?_.interval:60,j=Math.max(k,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((d)=>{console.error("Error rotating keys:",d)})},j)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let _=this.config.rotation.keyRotation,k=this.generateKeyId(),j=this.generateKey();this.currentKeyId=k,this.keys.set(k,j),this.encryptionKeys.set(k,{key:j,createdAt:new Date});let d=Array.from(this.encryptionKeys.entries()).sort(([,Z],[,X])=>X.createdAt.getTime()-Z.createdAt.getTime()),O=typeof _.maxKeys==="number"?_.maxKeys:1,$=Math.max(1,O);if(d.length>$)for(let[Z]of d.slice($))this.encryptionKeys.delete(Z),this.keys.delete(Z)}generateKeyId(){return e9(16).toString("hex")}generateKey(){return e9(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let _=this.keys.get(this.currentKeyId);if(!_)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:_,id:this.currentKeyId}}encrypt(_){let{key:k}=this.getCurrentKey(),j=e9(16),d=hP("aes-256-gcm",k,j),O=Ck.isBuffer(_)?_:Ck.from(_,"utf8"),$=d.update(O),Z=d.final(),X=$.length+Z.length,E=d.getAuthTag(),F=Ck.allocUnsafe(16+X+16);return j.copy(F,0),$.copy(F,16),Z.copy(F,16+$.length),E.copy(F,16+X),{encrypted:F,iv:j}}async compressData(_){return new Promise((k,j)=>{let d=R5(),O=[];d.on("data",($)=>O.push($)),d.on("end",()=>k(Ck.from(Ck.concat(O)))),d.on("error",j),d.write(_),d.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let _={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let k=this.config.rotation.encrypt;return{..._,...k}}return _}async rotateLog(){if(H_())return;if(!this.shouldWriteToFile())return;let _=await Hj(this.currentLogFile).catch(()=>null);if(!_)return;let k=this.config.rotation;if(typeof k==="boolean")return;if(k.maxSize&&_.size>=k.maxSize){let j=this.currentLogFile,d=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let O=await OO(this.config.logDirectory),$=O.filter((E)=>E.startsWith(this.name)&&/\.log\.\d+$/.test(E)).sort((E,F)=>{let G=Number.parseInt(E.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(F.match(/\.log\.(\d+)$/)?.[1]||"0")-G}),Z=$.length>0?Number.parseInt($[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,X=`${j}.${Z}`;if(await Hj(j).catch(()=>null))try{if(await D5(j,X),k.compress)try{let E=`${X}.gz`;await this.compressLogFile(X,E),await $O(X)}catch(E){console.error("Error compressing rotated file:",E)}if($.length===0&&!O.some((E)=>E.endsWith(".log.1")))try{let E=`${j}.1`;await k8(E,"")}catch(E){console.error("Error creating backup file:",E)}}catch(E){console.error(`Error during rotation: ${E instanceof Error?E.message:String(E)}`)}}else{let O=new Date().toISOString().replace(/[:.]/g,"-"),$=j.replace(/\.log$/,`-${O}.log`);if(await Hj(j).catch(()=>null))await D5(j,$)}if(this.currentLogFile=d,k.maxFiles){let O=(await OO(this.config.logDirectory)).filter(($)=>$.startsWith(this.name)).sort(($,Z)=>Z.localeCompare($));for(let $ of O.slice(k.maxFiles))await $O(bj(this.config.logDirectory,$))}}}async compressLogFile(_,k){let j=K5(_),d=qP(k),O=R5();await BP(j,O,d)}async handleFingersCrossedBuffer(_,k){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(_)&&!this.isActivated){this.isActivated=!0;for(let j of this.logBuffer){let d=await this.formatter.format(j);if(this.shouldWriteToFile())await this.writeToFile(d);console.log(d)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(k);console.log(k)}}shouldLog(_){if(!this.enabled)return!1;let k={debug:0,info:1,success:2,warning:3,error:4};return k[_]>=k[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((_)=>{if(_ instanceof Promise)return _.catch((k)=>{console.error("Error in pending write operation:",k)});return Promise.resolve()})),dO(this.currentLogFile))try{let _=J5(this.currentLogFile,"r+");n5(_),_8(_)}catch(_){console.error(`Error flushing file: ${_}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let _ of this.pendingOperations)if(typeof _.cancel==="function")_.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(_){console.error("Error waiting for pending operations:",_)}if(!H_()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let _=(await OO(this.config.logDirectory)).filter((k)=>(k.includes("temp")||k.includes(".tmp"))&&k.includes(this.name));for(let k of _)try{await $O(bj(this.config.logDirectory,k))}catch(j){console.error(`Failed to delete temp file ${k}:`,j)}}catch(_){console.error("Error cleaning up temporary files:",_)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(_){if(!_)return"";return`${this.tagFormat.prefix}${_}${this.tagFormat.suffix}`}formatFileTimestamp(_){return`[${_.toISOString()}]`}formatConsoleTimestamp(_){return this.shouldStyleConsole()?G_.gray(_.toLocaleTimeString()):_.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||H_())return!1;let _=typeof F_.env.NO_COLOR<"u",k=F_.env.FORCE_COLOR==="0";if(_||k)return!1;return!!(typeof F_.stderr<"u"&&F_.stderr.isTTY||typeof F_.stdout<"u"&&F_.stdout.isTTY)}formatConsoleMessage(_){let{timestamp:k,icon:j="",tag:d="",message:O,level:$,showTimestamp:Z=!0}=_,X=(z)=>z.replace(this.ANSI_PATTERN,"");if(!this.fancy){let z=[];if(Z)z.push(k);if($==="warning")z.push("WARN");else if($==="error")z.push("ERROR");else if(j)z.push(j.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(d)z.push(d.replace(/[[\]]/g,""));return z.push(O),z.join(" ")}let E=F_.stdout.columns||120,F="";if($==="warning"||$==="error")F=`${j} ${O}`;else if($==="info"||$==="success")F=`${j} ${d} ${O}`;else F=`${j} ${d} ${G_.cyan(O)}`;if(!Z)return F.trim();let G=X(F).trim().length,Y=X(k).length,S=Math.max(1,E-2-G-Y);return`${F.trim()}${" ".repeat(S)}${k}`}formatMessage(_,k){if(k.length===1&&Array.isArray(k[0]))return _.replace(/\{(\d+)\}/g,($,Z)=>{let X=Number.parseInt(Z,10);return X<k[0].length?String(k[0][X]):$});let j=/%([sdijfo%])/g,d=0,O=_.replace(j,($,Z)=>{if(Z==="%")return"%";if(d>=k.length)return $;let X=k[d++];switch(Z){case"s":return String(X);case"d":case"i":return Number(X).toString();case"j":case"o":return JSON.stringify(X,null,2);default:return $}});if(d<k.length)O+=` ${k.slice(d).map(($)=>typeof $==="object"?JSON.stringify($,null,2):String($)).join(" ")}`;return O}formatMarkdown(_){if(!_)return _;let k=_;return k=k.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(j,d,O)=>{let $=G_.underline(G_.blue(d)),Z=this.toAbsoluteFilePath(O);if(Z&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let X=`file://${encodeURI(Z)}`,E="\x1B]8;;",F="\x1B\\";return`\x1B]8;;${X}\x1B\\${$}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${O}\x1B\\${$}\x1B]8;;\x1B\\`;return $}),k=k.replace(/`([^`]+)`/g,(j,d)=>G_.bgGray(d)),k=k.replace(/\*\*([^*]+)\*\*/g,(j,d)=>G_.bold(d)),k=k.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(j,d)=>G_.italic(d)),k=k.replace(/(?<!_)_([^_]+)_(?!_)/g,(j,d)=>G_.italic(d)),k=k.replace(/~([^~]+)~/g,(j,d)=>G_.strikethrough(d)),k}supportsHyperlinks(){if(H_())return!1;let _=F_.env;if(!_)return!1;if(_.TERM_PROGRAM==="iTerm.app"||_.TERM_PROGRAM==="vscode"||_.TERM_PROGRAM==="WezTerm")return!0;if(_.WT_SESSION)return!0;if(_.TERM==="xterm-kitty")return!0;let k=_.VTE_VERSION?Number.parseInt(_.VTE_VERSION,10):0;if(!Number.isNaN(k)&&k>=5000)return!0;return!1}toAbsoluteFilePath(_){try{let k=_;if(k.startsWith("file://"))k=k.replace(/^file:\/\//,"");if(k.startsWith("~")){let j=F_.env.HOME||"";if(j)k=k.replace(/^~(?=$|\/)/,j)}if(xP(k)||k.startsWith("./")||k.startsWith("../"))k=iP(k);else return null;return dO(k)?k:null}catch{return null}}buildOutputTexts(_){let k=this.shouldStyleConsole()?this.formatMarkdown(_):_,j=_.replace(this.ANSI_PATTERN,"");return{consoleText:k,fileText:j}}async log(_,k,...j){let d=new Date,O=this.formatConsoleTimestamp(d),$=this.formatFileTimestamp(d),Z,X;if(k instanceof Error)Z=k.message,X=k.stack;else Z=this.formatMessage(k,j);let{consoleText:E,fileText:F}=this.buildOutputTexts(Z);if(this.shouldStyleConsole()){let Y=this.options.showIcons===!1?"":d6[_],S=this.options.showTags!==!1&&this.name?G_.gray(this.formatTag(this.name)):"",z;switch(_){case"debug":z=this.formatConsoleMessage({timestamp:O,icon:Y,tag:S,message:G_.gray(E),level:_}),console.error(z);break;case"info":z=this.formatConsoleMessage({timestamp:O,icon:Y,tag:S,message:E,level:_}),console.warn(z);break;case"success":z=this.formatConsoleMessage({timestamp:O,icon:Y,tag:S,message:G_.green(E),level:_}),console.error(z);break;case"warning":z=this.formatConsoleMessage({timestamp:O,icon:Y,tag:S,message:E,level:_}),console.warn(z);break;case"error":if(z=this.formatConsoleMessage({timestamp:O,icon:Y,tag:S,message:E,level:_}),console.error(z),X){let U=X.split(`
|
|
103
|
-
`);for(let Q of U)if(Q.trim()&&!Q.includes(Z))console.error(this.formatConsoleMessage({timestamp:O,message:G_.gray(` ${Q}`),level:_,showTimestamp:!1}))}break}}else if(!H_()){if(console.error(`${$} ${this.environment}.${_.toUpperCase()}: ${Z}`),X)console.error(X)}if(!this.shouldLog(_))return;let G=`${$} ${this.environment}.${_.toUpperCase()}: ${F}
|
|
104
|
-
`;if(X)G+=`${X}
|
|
105
|
-
`;if(G=G.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(G)}progress(_,k=""){let j={update:(O,$)=>{},finish:(O)=>{},interrupt:(O,$)=>{}};if(!this.enabled)return j;let d=30;if(this.activeProgressBar={total:Math.max(1,_||1),current:0,message:k||"",barLength:d,lastRenderedLine:""},this.shouldStyleConsole()&&!H_()&&F_.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(O,$)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,O),this.activeProgressBar.total),$!==void 0)this.activeProgressBar.message=$;if(this.shouldStyleConsole()&&!H_()&&F_.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(O)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,O)},interrupt:(O,$="info")=>{if(!H_()&&F_.stdout.isTTY)F_.stdout.write(`
|
|
106
|
-
`);if(this[$==="warning"?"warn":$](O),this.activeProgressBar&&this.shouldStyleConsole()&&!H_()&&F_.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(_){let k=performance.now();if(this.shouldStyleConsole()){let j=this.options.showTags!==!1&&this.name?G_.gray(this.formatTag(this.name)):"",d=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:d,icon:this.options.showIcons===!1?"":G_.blue("\u25D0"),tag:j,message:`${G_.cyan(_)}...`}))}return async(j)=>{if(!this.enabled)return;let d=performance.now(),O=Math.round(d-k),$=`${_} completed in ${O}ms`,Z=new Date,X=this.formatConsoleTimestamp(Z),E=`${this.formatFileTimestamp(Z)} ${this.environment}.INFO: ${$}`;if(j)E+=` ${JSON.stringify(j)}`;if(E+=`
|
|
107
|
-
`,E=E.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let F=this.options.showTags!==!1&&this.name?G_.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:X,icon:this.options.showIcons===!1?"":G_.green("\u2713"),tag:F,message:`${$}${j?` ${JSON.stringify(j)}`:""}`}))}else if(!H_())console.error(E.trim());if(this.shouldWriteToFile())await this.writeToFile(E)}}async debug(_,...k){await this.log("debug",_,...k)}async info(_,...k){await this.log("info",_,...k)}async success(_,...k){await this.log("success",_,...k)}async warn(_,...k){await this.log("warning",_,...k)}async error(_,...k){await this.log("error",_,...k)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let _=this.config.rotation,{encrypt:k}=_;return!!k}async only(_){if(!this.enabled)return;return await _()}isEnabled(){return this.enabled}setEnabled(_){this.enabled=_}extend(_){let k=`${this.name}:${_}`,j=new rO(k,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(j),j}createReadStream(){if(H_())throw Error("createReadStream is not supported in browser environments");if(!dO(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return K5(this.currentLogFile,{encoding:"utf8"})}async decrypt(_){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let k=this.config.rotation;if(!k.encrypt||typeof k.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let j=this.keys.get(this.currentKeyId);try{let d=Ck.isBuffer(_)?_:Ck.from(_,"base64"),O=d.subarray(0,16),$=d.subarray(d.length-16),Z=d.subarray(16,d.length-16),X=fP("aes-256-gcm",j,O);X.setAuthTag($);let E=X.update(Z),F=X.final(),G=E.length+F.length,Y=Ck.allocUnsafe(G);return E.copy(Y,0),F.copy(Y,E.length),Y.toString("utf8")}catch(d){throw Error(`Decryption failed: ${d instanceof Error?d.message:String(d)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return H_()}isServerMode(){return!H_()}setTestEncryptionKey(_,k){this.currentKeyId=_,this.keys.set(_,k)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box(_){if(!this.enabled)return;let k=new Date,j=this.formatConsoleTimestamp(k),d=this.formatFileTimestamp(k),{consoleText:O,fileText:$}=this.buildOutputTexts(_);if(this.shouldStyleConsole()){let X=O.split(`
|
|
108
|
-
`),E=Math.max(...X.map((S)=>S.length))+2,F=`\u250C${"\u2500".repeat(E)}\u2510`,G=`\u2514${"\u2500".repeat(E)}\u2518`,Y=X.map((S)=>{return this.formatConsoleMessage({timestamp:j,message:G_.cyan(S),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:j,message:G_.cyan(F),showTimestamp:!1})),Y.forEach((S)=>console.error(S)),console.error(this.formatConsoleMessage({timestamp:j,message:G_.cyan(G),showTimestamp:!1}))}else if(!H_())console.error(`${d} ${this.environment}.INFO: [BOX] ${$}`);let Z=`${d} ${this.environment}.INFO: [BOX] ${$}
|
|
109
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(Z)}async prompt(_){if(H_())return Promise.resolve(!0);return new Promise((k)=>{console.error(`${G_.cyan("?")} ${_} (y/n) `);let j=(d)=>{let O=d.toString().trim().toLowerCase();F_.stdin.removeListener("data",j);try{if(typeof F_.stdin.setRawMode==="function")F_.stdin.setRawMode(!1)}catch{}F_.stdin.pause(),console.error(""),k(O==="y"||O==="yes")};try{if(typeof F_.stdin.setRawMode==="function")F_.stdin.setRawMode(!0)}catch{}F_.stdin.resume(),F_.stdin.once("data",j)})}setFancy(_){this.fancy=_}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(_,...k){if(!this.enabled)return;let j=_;if(k&&k.length>0){let Z=/%([sdijfo%])/g,X=0;if(j=_.replace(Z,(E,F)=>{if(F==="%")return"%";if(X>=k.length)return E;let G=k[X++];switch(F){case"s":return String(G);case"d":case"i":return Number(G).toString();case"j":case"o":return JSON.stringify(G,null,2);default:return E}}),X<k.length)j+=` ${k.slice(X).map((E)=>typeof E==="object"?JSON.stringify(E,null,2):String(E)).join(" ")}`}let{consoleText:d,fileText:O}=this.buildOutputTexts(j);if(this.shouldStyleConsole()){let Z=this.options.showTags!==!1&&this.name?G_.gray(this.formatTag(this.name)):"",X=this.options.showIcons===!1?"":`${G_.blue("\u25D0")} `;console.error(`${X}${Z} ${G_.cyan(d)}`)}let $=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${O}
|
|
110
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile($)}renderProgressBar(_,k=!1){if(!this.enabled||!this.shouldStyleConsole()||!F_.stdout.isTTY)return;let j=Math.min(100,Math.max(0,Math.round(_.current/_.total*100))),d=Math.round(_.barLength*j/100),O=_.barLength-d,$=G_.green("\u2501".repeat(d)),Z=G_.gray("\u2501".repeat(O)),X=`[${$}${Z}]`,E=`${j}%`.padStart(4),F=_.message?` ${_.message}`:"",G=this.options.showIcons===!1?"":k||j===100?G_.green("\u2713"):G_.blue("\u25B6"),Y=this.options.showTags!==!1&&this.name?` ${G_.gray(this.formatTag(this.name))}`:"",S=`\r${G}${Y} ${X} ${E}${F}`,z=F_.stdout.columns||80,U=" ".repeat(Math.max(0,z-S.replace(this.ANSI_PATTERN,"").length));if(_.lastRenderedLine=`${S}${U}`,F_.stdout.write(_.lastRenderedLine),k)F_.stdout.write(`
|
|
111
|
-
`)}finishProgressBar(_,k){if(!this.enabled||!this.fancy||H_()||!F_.stdout.isTTY){this.activeProgressBar=null;return}if(_.current<_.total)_.current=_.total;if(k)_.message=k;this.renderProgressBar(_,!0),this.activeProgressBar=null}async clear(_={}){if(H_()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let k=await OO(this.config.logDirectory),j=[];for(let d of k){if(!(_.name?new RegExp(_.name.replace("*",".*")).test(d):d.startsWith(this.name))||!d.endsWith(".log"))continue;let O=bj(this.config.logDirectory,d);if(_.before)try{if((await Hj(O)).mtime>=_.before)continue}catch($){console.error(`Failed to get stats for file ${O}:`,$);continue}j.push(O)}if(j.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${j.length} log file(s)...`);for(let d of j)try{await $O(d),console.warn(`Deleted log file: ${d}`)}catch(O){console.error(`Failed to delete log file ${d}:`,O)}console.warn("Log clearing process finished.")}catch(k){console.error("Error during log clearing process:",k)}}}async function aP(_,k={}){let{maxRetries:j=3,retryDelay:d=1000,isRetryable:O=()=>!0,fallback:$}=k,Z=Error("Unknown error occurred");for(let X=0;X<=j;X++)try{return await _()}catch(E){if(Z=E instanceof Error?E:Error(String(E)),X===j||!O(Z))break;if(d>0)await new Promise((F)=>setTimeout(F,d))}if($!==void 0)return $;throw Z instanceof Error?Z:Error(`Unknown error: ${String(Z)}`)}class v8{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:(_,k)=>k==="boolean"||["true","false","1","0","yes","no"].includes(_.toLowerCase()),parse:(_)=>{let k=_.toLowerCase();return["true","1","yes"].includes(k)}},{name:"number",canParse:(_,k)=>k==="number"||!Number.isNaN(Number(_))&&!Number.isNaN(Number.parseFloat(_)),parse:(_)=>{let k=Number(_);if(Number.isNaN(k))throw TypeError(`Cannot parse "${_}" as number`);return k}},{name:"array",canParse:(_,k)=>k==="array"||_.startsWith("[")||_.includes(","),parse:(_)=>{try{let k=JSON.parse(_);if(Array.isArray(k))return k}catch{}return _.split(",").map((k)=>k.trim())}},{name:"json",canParse:(_,k)=>k==="object"||(_.startsWith("{")&&_.endsWith("}")||_.startsWith("[")&&_.endsWith("]")),parse:(_)=>{try{return JSON.parse(_)}catch(k){throw Error(`Cannot parse "${_}" as JSON: ${k}`)}}}]}async applyEnvironmentVariables(_,k,j={}){let{prefix:d,useCamelCase:O=!0,useBackwardCompatibility:$=!0,customParsers:Z={},verbose:X=!1,trackPerformance:E=!0}=j,F=async()=>{if(!_)return{config:k,source:{type:"environment",priority:50,timestamp:new Date}};let G=d||this.generateEnvPrefix(_),Y={...k};return this.processObject(Y,[],G,{useCamelCase:O,useBackwardCompatibility:$,customParsers:Z,verbose:X,configName:_}),{config:Y,source:{type:"environment",priority:50,timestamp:new Date}}};if(E)return Q0.track("applyEnvironmentVariables",F,{configName:_});return F()}generateEnvPrefix(_){return _.toUpperCase().replace(/-/g,"_")}formatEnvKey(_,k){if(!k)return _.toUpperCase();return _.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject(_,k,j,d){for(let[O,$]of Object.entries(_)){let Z=[...k,O],X=Z.map((G)=>this.formatEnvKey(G,d.useCamelCase)),E=`${j}_${X.join("_")}`,F=d.useBackwardCompatibility?`${j}_${Z.map((G)=>G.toUpperCase()).join("_")}`:null;if(d.verbose);if(typeof $==="object"&&$!==null&&!Array.isArray($))this.processObject($,Z,j,d);else{let G=ZO.env[E]||(F?ZO.env[F]:void 0);if(G!==void 0){if(d.verbose){let Y=ZO.env[E]?E:F}try{_[O]=this.parseEnvironmentValue(G,typeof $,E,d.customParsers,d.configName)}catch(Y){if(Y instanceof I8)throw Y;throw Gj.envVar(E,G,typeof $,d.configName)}}}}}parseEnvironmentValue(_,k,j,d,O){for(let[$,Z]of Object.entries(d))try{return Z(_)}catch{continue}for(let $ of this.defaultParsers)if($.canParse(_,k))try{return $.parse(_)}catch{throw Gj.envVar(j,_,`${k} (via ${$.name} parser)`,O)}return _}getEnvironmentVariables(_){let k={},j=_.toUpperCase();for(let[d,O]of Object.entries(ZO.env))if(d.startsWith(j)&&O!==void 0)k[d]=O;return k}validateEnvironmentVariable(_,k,j){let d=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(_))d.push(`Environment variable key "${_}" should only contain uppercase letters, numbers, and underscores`);if(j)try{this.parseEnvironmentValue(_,k,j,{})}catch(O){d.push(`Cannot parse value "${k}" as ${j}: ${O}`)}return{isValid:d.length===0,errors:d}}generateEnvVarDocs(_,k,j={}){let{prefix:d,format:O="text"}=j,$=d||this.generateEnvPrefix(_),Z=[];switch(this.extractEnvVarInfo(k,[],$,Z),O){case"markdown":return this.formatAsMarkdown(Z,_);case"json":return JSON.stringify(Z,null,2);default:return this.formatAsText(Z,_)}}extractEnvVarInfo(_,k,j,d){for(let[O,$]of Object.entries(_)){let Z=[...k,O],X=`${j}_${Z.map((E)=>this.formatEnvKey(E,!0)).join("_")}`;if(typeof $==="object"&&$!==null&&!Array.isArray($))this.extractEnvVarInfo($,Z,j,d);else d.push({key:X,type:Array.isArray($)?"array":typeof $,description:`Configuration for ${Z.join(".")}`,example:this.generateExample($)})}}generateExample(_){if(Array.isArray(_))return JSON.stringify(_);if(typeof _==="object"&&_!==null)return JSON.stringify(_);return String(_)}formatAsText(_,k){let j=`Environment Variables for ${k}:
|
|
112
|
-
|
|
113
|
-
`;for(let d of _)j+=`${d.key}
|
|
114
|
-
`,j+=` Type: ${d.type}
|
|
115
|
-
`,j+=` Description: ${d.description}
|
|
116
|
-
`,j+=` Example: ${d.example}
|
|
117
|
-
|
|
118
|
-
`;return j}formatAsMarkdown(_,k){let j=`# Environment Variables for ${k}
|
|
119
|
-
|
|
120
|
-
`;j+=`| Variable | Type | Description | Example |
|
|
121
|
-
`,j+=`|----------|------|-------------|----------|
|
|
122
|
-
`;for(let d of _)j+=`| \`${d.key}\` | ${d.type} | ${d.description} | \`${d.example}\` |
|
|
123
|
-
`;return j}}function eP(_,k,j={}){return pZ(_,k,j,new WeakMap)}function pZ(_,k,j,d){let{arrayMergeMode:O="replace",skipNullish:$=!1,customMerger:Z}=j;if(k===null||k===void 0)return $?_:k;if(Z){let X=Z(_,k);if(X!==void 0)return X}if(Array.isArray(k)||Array.isArray(_))return sZ(_,k,O,d);if(!zk(k)||!zk(_))return k;return dU(_,k,j,d)}function sZ(_,k,j,d){if(Array.isArray(k)&&!Array.isArray(_))return k;if(Array.isArray(_)&&!Array.isArray(k))return k;if(Array.isArray(k)&&Array.isArray(_))switch(j){case"replace":return k;case"concat":return _U(_,k);case"smart":return kU(_,k,d);default:return k}return k}function _U(_,k){let j=[...k];for(let d of _)if(!j.some((O)=>K8(O,d)))j.push(d);return j}function kU(_,k,j){if(k.length===0)return _;if(_.length===0)return k;if(zk(k[0])&&zk(_[0]))return jU(_,k,j);if(k.every((d)=>typeof d==="string")&&_.every((d)=>typeof d==="string")){let d=[...k];for(let O of _)if(!d.includes(O))d.push(O);return d}return k}function jU(_,k,j){let d=[...k];for(let O of _){if(!zk(O)){d.push(O);continue}let $=["id","name","key","path","type"],Z=!1;for(let X of $)if(X in O){if(d.find((E)=>zk(E)&&(X in E)&&E[X]===O[X])){Z=!0;break}}if(!Z)d.push(O)}return d}function dU(_,k,j,d){let O=k;if(zk(O)&&d.has(O))return d.get(O);let $={..._};if(zk(O))d.set(O,$);for(let Z in O){if(!Object.prototype.hasOwnProperty.call(O,Z))continue;let X=O[Z],E=$[Z];if(j.skipNullish&&(X===null||X===void 0))continue;if(X===null||X===void 0){$[Z]=X;continue}if(zk(X)&&zk(E))$[Z]=pZ(E,X,j,d);else if(Array.isArray(X)||Array.isArray(E))$[Z]=sZ(E,X,j.arrayMergeMode||"smart",d);else $[Z]=X}return $}function oZ(_,k,j="replace"){return eP(_,k,{arrayMergeMode:j==="replace"?"replace":"smart",skipNullish:!0})}function K8(_,k){if(_===k)return!0;if(Array.isArray(_)&&Array.isArray(k)){if(_.length!==k.length)return!1;for(let j=0;j<_.length;j++)if(!K8(_[j],k[j]))return!1;return!0}if(zk(_)&&zk(k)){let j=Object.keys(_),d=Object.keys(k);if(j.length!==d.length)return!1;for(let O of j){if(!Object.prototype.hasOwnProperty.call(k,O))return!1;if(!K8(_[O],k[O]))return!1}return!0}return!1}function zk(_){return Boolean(_&&typeof _==="object"&&!Array.isArray(_))}class rZ{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(_,k,j={}){let{arrayStrategy:d="replace",useCache:O=!0,cacheTtl:$,trackPerformance:Z=!0,verbose:X=!1}=j;if(O){let F=p1.getWithFileCheck("file",_);if(F){if(X)console.log(`Configuration loaded from cache: ${_}`);return F}}let E=async()=>{if(!XO(_))return null;try{let F=`?t=${Date.now()}`,G=await import(_+F),Y=G.default||G,S="default"in G,z=Object.keys(G).length>0;if(!S&&!z)throw new X0(_,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof Y!=="object"||Y===null||Array.isArray(Y))throw new X0(_,Error("Configuration must export a valid object"),"unknown");let U={config:oZ(k,Y,d),source:{type:"file",path:_,priority:100,timestamp:new Date}};if(O)p1.setWithFileCheck("file",U,_,$);return U}catch(F){throw F instanceof Error?Gj.configLoad(_,F):Gj.configLoad(_,Error(String(F)))}};if(Z)return Q0.track("loadFromPath",E,{path:_});return E()}async tryLoadFromPaths(_,k,j={}){for(let d of _)try{let O=await this.loadFromPath(d,k,j);if(O)return O}catch(O){if(O instanceof Error&&O.name==="ConfigLoadError")throw O;if(j.verbose)console.warn(`Failed to load config from ${d}:`,O)}return null}generateConfigPaths(_,k,j){let d=this.generateNamePatterns(_,j),O=[];for(let $ of d)for(let Z of this.extensions)O.push(j8(k,`${$}${Z}`));return O}generateNamePatterns(_,k){let j=[];if(j.push("config",".config"),_)j.push(_,`.${_}.config`,`${_}.config`,`.${_}`);if(k){if(j.push(k,`.${k}.config`,`${k}.config`,`.${k}`),_)j.push(`${_}.${k}.config`,`.${_}.${k}.config`)}return j.filter(Boolean)}checkFileAccess(_){return aP(async()=>{return XO(_)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(_,k,j){let d=[];if(!XO(_))return d;if(k||j){let O=this.generateNamePatterns(k||"",j);for(let $ of O)for(let Z of this.extensions){let X=j8(_,`${$}${Z}`);if(await this.checkFileAccess(X))d.push(X)}}else try{let{readdirSync:O}=await import("fs"),$=O(_);for(let Z of $)if(this.looksLikeConfigFile(Z)){let X=j8(_,Z);if(await this.checkFileAccess(X))d.push(X)}}catch{return[]}return d}looksLikeConfigFile(_){return[/\.config\.(ts|js|mjs|cjs|json|mts|cts)$/,/^\..*\.(ts|js|mjs|cjs|json|mts|cts)$/,/config\.(ts|js|mjs|cjs|json|mts|cts)$/].some((k)=>k.test(_))}async validateConfigFile(_){let k=[];try{if(!XO(_))return k.push("Configuration file does not exist"),k;let j=await import(_),d=j.default||j;if(d===void 0)k.push("Configuration file must export a default value or named exports");else if(typeof d!=="object"||d===null)k.push("Configuration must be an object");else if(Array.isArray(d))k.push("Configuration cannot be an array at the root level");if(_.endsWith(".json"))try{let{readFileSync:O}=await import("fs"),$=O(_,"utf8");JSON.parse($)}catch(O){k.push(`Invalid JSON syntax: ${O}`)}}catch(j){k.push(`Failed to load configuration file: ${j}`)}return k}async getFileModificationTime(_){try{let{statSync:k}=await import("fs");return k(_).mtime}catch{return null}}async preloadConfigurations(_,k={}){let j=new Map;return await Promise.allSettled(_.map(async(d)=>{try{let O=await this.loadFromPath(d,{},k);if(O)j.set(d,O.config)}catch(O){if(k.verbose)console.warn(`Failed to preload ${d}:`,O)}})),j}}class tZ{async validateConfiguration(_,k,j={}){let{stopOnFirstError:d=!1,validateRequired:O=!0,validateTypes:$=!0,customRules:Z=[],trackPerformance:X=!0,verbose:E=!1}=j,F=async()=>{let G=[],Y=[],S={stopOnFirstError:d,validateRequired:O,validateTypes:$,customRules:Z,trackPerformance:X,verbose:E};try{if(typeof k==="string")return await this.validateWithSchemaFile(_,k,S);else if(Array.isArray(k))return this.validateWithRules(_,[...k,...Z],S);else return this.validateWithJSONSchema(_,k,S)}catch(z){return G.push({path:"",message:`Validation failed: ${z}`,rule:"system"}),{isValid:!1,errors:G,warnings:Y}}};if(X)return await Q0.track("validateConfiguration",F);return F()}async validateWithSchemaFile(_,k,j){try{if(!cP(k))throw new E0(k,[{path:"",message:"Schema file does not exist"}]);let d=await import(k),O=d.default||d;if(Array.isArray(O))return this.validateWithRules(_,O,j);else return this.validateWithJSONSchema(_,O,j)}catch(d){throw new E0(k,[{path:"",message:`Failed to load schema: ${d}`}])}}validateWithJSONSchema(_,k,j){let d=[],O=[];return this.validateObjectAgainstSchema(_,k,"",d,O,j),{isValid:d.length===0,errors:d,warnings:O}}validateObjectAgainstSchema(_,k,j,d,O,$){if($.validateTypes&&k.type){let Z=Array.isArray(_)?"array":typeof _,X=Array.isArray(k.type)?k.type:[k.type];if(!X.includes(Z)){if(d.push({path:j,message:`Expected type ${X.join(" or ")}, got ${Z}`,expected:X.join(" or "),actual:Z,rule:"type"}),$.stopOnFirstError)return}}if(k.enum&&!k.enum.includes(_)){if(d.push({path:j,message:`Value must be one of: ${k.enum.join(", ")}`,expected:k.enum.join(", "),actual:_,rule:"enum"}),$.stopOnFirstError)return}if(typeof _==="string"){if(k.minLength!==void 0&&_.length<k.minLength)d.push({path:j,message:`String length must be at least ${k.minLength}`,expected:`>= ${k.minLength}`,actual:_.length,rule:"minLength"});if(k.maxLength!==void 0&&_.length>k.maxLength)d.push({path:j,message:`String length must not exceed ${k.maxLength}`,expected:`<= ${k.maxLength}`,actual:_.length,rule:"maxLength"});if(k.pattern){if(!new RegExp(k.pattern).test(_))d.push({path:j,message:`String does not match pattern ${k.pattern}`,expected:k.pattern,actual:_,rule:"pattern"})}}if(typeof _==="number"){if(k.minimum!==void 0&&_<k.minimum)d.push({path:j,message:`Value must be at least ${k.minimum}`,expected:`>= ${k.minimum}`,actual:_,rule:"minimum"});if(k.maximum!==void 0&&_>k.maximum)d.push({path:j,message:`Value must not exceed ${k.maximum}`,expected:`<= ${k.maximum}`,actual:_,rule:"maximum"})}if(Array.isArray(_)&&k.items)for(let Z=0;Z<_.length;Z++){let X=j?`${j}[${Z}]`:`[${Z}]`;if(this.validateObjectAgainstSchema(_[Z],k.items,X,d,O,$),$.stopOnFirstError&&d.length>0)return}if(_&&typeof _==="object"&&!Array.isArray(_)){let Z=_;if($.validateRequired&&k.required){for(let X of k.required)if(!(X in Z)){if(d.push({path:j?`${j}.${X}`:X,message:`Missing required property '${X}'`,expected:"required",rule:"required"}),$.stopOnFirstError)return}}if(k.properties){for(let[X,E]of Object.entries(k.properties))if(X in Z){let F=j?`${j}.${X}`:X;if(this.validateObjectAgainstSchema(Z[X],E,F,d,O,$),$.stopOnFirstError&&d.length>0)return}}if(k.additionalProperties===!1){let X=new Set(Object.keys(k.properties||{}));for(let E of Object.keys(Z))if(!X.has(E))O.push({path:j?`${j}.${E}`:E,message:`Additional property '${E}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(_,k,j){let d=[],O=[];for(let $ of k)try{let Z=this.getValueByPath(_,$.path),X=this.validateWithRule(Z,$,$.path);if(d.push(...X),j.stopOnFirstError&&d.length>0)break}catch(Z){d.push({path:$.path,message:`Rule validation failed: ${Z}`,rule:"system"})}return{isValid:d.length===0,errors:d,warnings:O}}validateWithRule(_,k,j){let d=[];if(k.required&&(_===void 0||_===null))return d.push({path:j,message:k.message||`Property '${j}' is required`,expected:"required",rule:"required"}),d;if(_===void 0||_===null)return d;if(k.type){let O=Array.isArray(_)?"array":typeof _;if(O!==k.type)d.push({path:j,message:k.message||`Expected type ${k.type}, got ${O}`,expected:k.type,actual:O,rule:"type"})}if(k.min!==void 0){let O=Array.isArray(_)?_.length:typeof _==="string"?_.length:typeof _==="number"?_:0;if(O<k.min)d.push({path:j,message:k.message||`Value must be at least ${k.min}`,expected:`>= ${k.min}`,actual:O,rule:"min"})}if(k.max!==void 0){let O=Array.isArray(_)?_.length:typeof _==="string"?_.length:typeof _==="number"?_:0;if(O>k.max)d.push({path:j,message:k.message||`Value must not exceed ${k.max}`,expected:`<= ${k.max}`,actual:O,rule:"max"})}if(k.pattern&&typeof _==="string"){if(!k.pattern.test(_))d.push({path:j,message:k.message||`Value does not match pattern ${k.pattern}`,expected:k.pattern.toString(),actual:_,rule:"pattern"})}if(k.enum&&!k.enum.includes(_))d.push({path:j,message:k.message||`Value must be one of: ${k.enum.join(", ")}`,expected:k.enum.join(", "),actual:_,rule:"enum"});if(k.validator){let O=k.validator(_);if(O)d.push({path:j,message:k.message||O,rule:"custom"})}return d}getValueByPath(_,k){if(!k)return _;let j=k.split("."),d=_;for(let O of j)if(d&&typeof d==="object"&&O in d)d=d[O];else return;return d}generateRulesFromInterface(_){let k=[],j=_.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let d of j){let[,O,$,Z]=d;k.push({path:O,required:!$,type:this.mapTypeScriptType(Z)})}return k}mapTypeScriptType(_){switch(_.toLowerCase()){case"string":return"string";case"number":return"number";case"boolean":return"boolean";case"array":return"array";case"object":return"object";default:return"object"}}static createCommonRules(){return{server:[{path:"port",required:!0,type:"number",min:1,max:65535},{path:"host",required:!0,type:"string",min:1},{path:"ssl",type:"boolean"}],database:[{path:"url",required:!0,type:"string",min:1},{path:"pool",type:"number",min:1,max:100},{path:"timeout",type:"number",min:0}],api:[{path:"baseUrl",required:!0,type:"string",pattern:O6},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class aZ{fileLoader=new rZ;envProcessor=new v8;validator=new tZ;async loadConfig(_){let k=Date.now(),{cache:j,performance:d,schema:O,validate:$,...Z}=_;try{if(j?.enabled){let E=this.checkCache(Z.name||"",Z);if(E)return E}let X;try{X=await this.loadConfigurationStrategies(Z,!0,j)}catch(E){let F=Z.__strictErrorHandling;if(E instanceof Error&&E.name==="ConfigNotFoundError"){if(F)throw E;X={...await this.applyEnvironmentVariables(Z.name||"",Z.defaultConfig,Z.checkEnv!==!1,Z.verbose||!1),warnings:[`No configuration file found for "${Z.name||"config"}", using defaults with environment variables`]}}else if(E instanceof Error&&E.name==="ConfigLoadError"){let G=E.message.includes("EACCES")||E.message.includes("EPERM")||E.message.includes("permission denied"),Y=!G&&(E.message.includes("syntax")||E.message.includes("Expected")||E.message.includes("Unexpected")||E.message.includes("BuildMessage")||E.message.includes("errors building")),S=E.message.includes("Configuration must export a valid object")||E.message.includes("Configuration file is empty and exports nothing");if(F&&(S||G))throw E;if(Y&&(!F||!S))X={...await this.applyEnvironmentVariables(Z.name||"",Z.defaultConfig,Z.checkEnv!==!1,Z.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!F)X={...await this.applyEnvironmentVariables(Z.name||"",Z.defaultConfig,Z.checkEnv!==!1,Z.verbose||!1),warnings:[`Configuration loading error, using defaults: ${E.message}`]};else throw E}else X={...await this.applyEnvironmentVariables(Z.name||"",Z.defaultConfig,Z.checkEnv!==!1,Z.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${E instanceof Error?E.message:String(E)}`]}}if(O||$)await this.validateConfiguration(X.config,O,$,Z.name);if(j?.enabled&&X)this.cacheResult(Z.name||"",X,j,Z);if(d?.enabled){let E={operation:"loadConfig",duration:Date.now()-k,configName:Z.name,timestamp:new Date};if(d.onMetrics)d.onMetrics(E);if(d.slowThreshold&&E.duration>d.slowThreshold)Vk.warn(`Slow configuration loading detected: ${E.duration}ms for ${Z.name}`);X.metrics=E}return X}catch(X){let E=Date.now()-k;throw Vk.error(`Configuration loading failed after ${E}ms:`,[X instanceof Error?X:Error(String(X))]),X}}async loadConfigurationStrategies(_,k=!1,j){let{name:d="",alias:O,cwd:$,configDir:Z,defaultConfig:X,checkEnv:E=!0,arrayStrategy:F="replace",verbose:G=!1}=_,Y=$||mO.cwd(),S=[],z=await this.loadLocalConfiguration(d,O,Y,Z,X,F,G,E,j);if(z)return S.push(...this.getLocalSearchPaths(d,O,Y,Z)),this.finalizeResult(z,S,E,d,G);let U=await this.loadHomeConfiguration(d,O,X,F,G,E);if(U)return S.push(...this.getHomeSearchPaths(d,O)),this.finalizeResult(U,S,E,d,G);let Q=await this.loadPackageJsonConfiguration(d,O,Y,X,F,G,E);if(Q)return S.push(Xk(Y,"package.json")),this.finalizeResult(Q,S,E,d,G);if(S.push(...this.getAllSearchPaths(d,O,Y,Z)),k)throw Gj.configNotFound(d,S,O);return{...await this.applyEnvironmentVariables(d,X,E,G),warnings:[`No configuration file found for "${d}"${O?` or alias "${O}"`:""}, using defaults with environment variables`]}}async loadLocalConfiguration(_,k,j,d,O,$,Z,X,E){let F=X?GO(_,O,Z):O,G=this.getLocalDirectories(j,d);for(let Y of G){if(Z)Vk.info(`Searching for configuration in: ${Y}`);let S=this.fileLoader.generateConfigPaths(_,Y,k),z=await this.fileLoader.tryLoadFromPaths(S,F,{arrayStrategy:$,verbose:Z,cacheTtl:E?.ttl,useCache:!E?.ttl||E.ttl>100});if(z){if(Z)Vk.success(`Configuration loaded from: ${z.source.path}`);return z}}return null}async loadHomeConfiguration(_,k,j,d,O,$){if(!_)return null;let Z=$?GO(_,j,O):j,X=[Xk(Cj(),".config",_),Xk(Cj(),".config"),Cj()];for(let E of X){if(O)Vk.info(`Checking home directory: ${E}`);let F=this.fileLoader.generateConfigPaths(_,E,k),G=await this.fileLoader.tryLoadFromPaths(F,Z,{arrayStrategy:d,verbose:O});if(G){if(O)Vk.success(`Configuration loaded from home directory: ${G.source.path}`);return G}}return null}async loadPackageJsonConfiguration(_,k,j,d,O,$,Z){let X=Z?GO(_,d,$):d;try{let E=Xk(j,"package.json");if(!VP(E))return null;let F=await import(E),G=F[_],Y=_;if(!G&&k)G=F[k],Y=k;if(G&&typeof G==="object"&&!Array.isArray(G)){if($)Vk.success(`Configuration loaded from package.json: ${Y}`);return{config:oZ(X,G,O),source:{type:"package.json",path:E,priority:30,timestamp:new Date}}}}catch(E){if($)Vk.warn("Failed to load package.json:",[E instanceof Error?E:Error(String(E))])}return null}async applyEnvironmentVariables(_,k,j,d){if(!j||!_||typeof k!=="object"||k===null||Array.isArray(k))return{config:k,source:{type:"default",priority:10,timestamp:new Date}};return{config:GO(_,k,d),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(_,k,j,d,O){return{config:_.config,source:_.source,path:_.source.path}}async validateConfiguration(_,k,j,d){let O=[];if(j){let $=j(_);if($)O.push(...$)}if(k){let $=await this.validator.validateConfiguration(_,k);if(!$.isValid)O.push(...$.errors.map((Z)=>Z.path?`${Z.path}: ${Z.message}`:Z.message))}if(O.length>0)throw Gj.configValidation(d||"unknown",O,d)}checkCache(_,k){let j=this.generateCacheKey(_,k);return p1.get(j)||null}cacheResult(_,k,j,d){let O=this.generateCacheKey(_,d);p1.set(O,k,void 0,j.ttl)}generateCacheKey(_,k){let j=[_];if(k.alias)j.push(`alias:${k.alias}`);if(k.cwd)j.push(`cwd:${k.cwd}`);if(k.configDir)j.push(`configDir:${k.configDir}`);if("checkEnv"in k)j.push(`checkEnv:${k.checkEnv}`);return j.join("|")}getLocalDirectories(_,k){return Array.from(new Set([_,Xk(_,"config"),Xk(_,".config"),k?Xk(_,k):void 0].filter(Boolean)))}getAllSearchPaths(_,k,j,d){let O=[];return O.push(...this.getLocalSearchPaths(_,k,j,d)),O.push(...this.getHomeSearchPaths(_,k)),O.push(Xk(j,"package.json")),O}getLocalSearchPaths(_,k,j,d){let O=this.getLocalDirectories(j,d),$=[];for(let Z of O)$.push(...this.fileLoader.generateConfigPaths(_,Z,k));return $}getHomeSearchPaths(_,k){if(!_)return[];let j=[Xk(Cj(),".config",_),Xk(Cj(),".config"),Cj()],d=[];for(let O of j)d.push(...this.fileLoader.generateConfigPaths(_,O,k));return d}async loadConfigWithResult(_){return this.loadConfig(_)}}async function OU(_){let k="defaultConfig"in _&&_.defaultConfig!==void 0?_.defaultConfig:{},j="cache"in _||"performance"in _||"schema"in _||"validate"in _;try{let d;if(j)d=await MO.loadConfig(_);else d=await MO.loadConfig({..._,defaultConfig:k,cache:{enabled:!0},performance:{enabled:!1}});return d?.config??k}catch(d){let O=d instanceof Error?d.name:"UnknownError",$=d instanceof Error?d.message:String(d);if(!(O==="ConfigNotFoundError"||O==="ConfigLoadError"||O==="ConfigValidationError"||$.includes("config"))&&_.verbose)Vk.warn("Unexpected error loading config, using defaults:",[d instanceof Error?d:Error(String(d))]);let Z=j?{..._,defaultConfig:k}:{..._,defaultConfig:k,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in _?_.checkEnv!==!1:!0)return(await MO.applyEnvironmentVariables(Z.name||"",k,!0,Z.verbose||!1))?.config??k;return k}}function GO(_,k,j=!1){let d=new v8,O=_.toUpperCase().replace(/[^A-Z0-9]/g,"_");function $(Z,X=[]){let E={...Z};for(let[F,G]of Object.entries(Z)){let Y=[...X,F],S=[`${O}_${Y.join("_").toUpperCase()}`,`${O}_${Y.map((Q)=>Q.toUpperCase()).join("")}`,`${O}_${Y.map((Q)=>Q.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],z,U;for(let Q of S)if(z=mO.env[Q],z!==void 0){U=Q;break}if(z!==void 0&&U)if(typeof G==="boolean")E[F]=["true","1","yes"].includes(z.toLowerCase());else if(typeof G==="number"){let Q=Number(z);if(!Number.isNaN(Q))E[F]=Q}else if(Array.isArray(G))try{E[F]=JSON.parse(z)}catch{E[F]=z.split(",").map((Q)=>Q.trim())}else E[F]=z;else if(G&&typeof G==="object"&&!Array.isArray(G))E[F]=$(G,Y)}return E}return $(k)}async function $U(){if(!X8)X8=await OU({name:"mock",alias:"faker",defaultConfig:G0});return X8}function cj(_){let k=_.replace(/-/g,"_").split("_"),j=k[0].toLowerCase(),d=k[1]?.toUpperCase(),O=d?`${j}-${d.toLowerCase()}`:j;return{full:_,language:j,region:d,packageName:O,normalized:d?`${j}_${d}`:j}}function ZU(_){let k=cj(_);if(k.region)return[k.normalized,k.language];return[k.language]}function XU(_){return`@mock-locale/${cj(_).packageName}`}function eZ(_,k){let j={..._};for(let d in k){let O=k[d],$=_[d];if(O===void 0)continue;if(typeof O==="object"&&O!==null&&!Array.isArray(O)&&typeof $==="object"&&$!==null&&!Array.isArray($))j[d]=eZ($,O);else j[d]=O}return j}function yj(){let _=AZ.cwd(),k=Bj(_,"package.json");if(!ij(k))return!1;try{let j=JSON.parse(vP(k,"utf-8"));return!!(j.workspaces||j.workspace)}catch{return!1}}function _6(){let _=AZ.cwd();if(ij(Bj(_,"bun.lockb"))||ij(Bj(_,"bun.lock")))return"bun";if(ij(Bj(_,"pnpm-lock.yaml")))return"pnpm";if(ij(Bj(_,"yarn.lock")))return"yarn";if(ij(Bj(_,"package-lock.json")))return"npm";return"bun"}function k6(_,k={}){let j=_6(),{silent:d=!1}=k;if(!d)console.log(`
|
|
124
|
-
\uD83D\uDCE6 Installing ${_} using ${j}...`);let O={bun:{cmd:"bun",args:["add",_]},npm:{cmd:"npm",args:["install",_]},yarn:{cmd:"yarn",args:["add",_]},pnpm:{cmd:"pnpm",args:["add",_]}},{cmd:$,args:Z}=O[j];try{let X=yP($,Z,{stdio:"pipe",shell:!0}),E=X.stdout?.toString()||"",F=X.stderr?.toString()||"",G=E+F;if(!d){if(E)console.log(E);if(F)console.error(F)}if(X.status===0){if(!d)console.log(`\u2713 Successfully installed ${_}`);return!0}else{let Y=G;if(Y.toLowerCase().includes("dependency loop")||Y.includes("DependencyLoop")||Y.includes("has a dependency loop")||Y.includes("An internal error occurred (DependencyLoop)")){if(!d){if(console.log(`
|
|
125
|
-
\u26A0\uFE0F Package ${_} is already available in the workspace and cannot be installed separately due to a dependency loop.`),yj())console.log(" This is expected when running in a workspace environment. The package should be available for import.")}return!0}if(!d)console.error(`\u2717 Failed to install ${_}`);return!1}}catch(X){if(!d)console.error(`\u2717 Error installing ${_}:`,X);return!1}}function u1(_,k){let j=[];for(let d of k.rules)if(!d.validator(_)){let O=d.errorMessage||`Validation failed for value: ${_}`;if(j.push(O),k.strict)throw Error(O)}return{isValid:j.length===0,errors:j}}function l1(_,k){let{items:j}=k;if(j.length===0)throw Error("Cannot select from empty weighted items array");let d=j.reduce((Z,X)=>Z+X.weight,0);if(d<=0)throw Error("Total weight must be greater than 0");let O=_.number()*d,$=0;for(let Z of j)if($+=Z.weight,O<=$)return Z.item;return j[j.length-1].item}function EU(_,k){return _.filter((j)=>{if(k.gender&&j.gender&&j.gender!==k.gender)return!1;if(k.country){let d=Array.isArray(k.country)?k.country:[k.country];if(j.country&&!d.includes(j.country))return!1}if(k.region){let d=Array.isArray(k.region)?k.region:[k.region];if(j.region&&!d.includes(j.region))return!1}if(k.locale&&j.locale&&j.locale!==k.locale)return!1;if(k.ageRange&&j.age){let{min:d,max:O}=k.ageRange;if(j.age<d||j.age>O)return!1}for(let[d,O]of Object.entries(k))if(d!=="gender"&&d!=="country"&&d!=="region"&&d!=="locale"&&d!=="ageRange"&&j[d]!==void 0){if(!(Array.isArray(O)?O:[O]).includes(j[d]))return!1}return!0})}function tk(_,k){let j={..._};for(let d of k){let{field:O,dependsOn:$,mapping:Z}=d;if(j[$]&&Z[j[$]])j[O]=Z[j[$]]}return j}function GU(_,k={}){let j=_();if(k.relationships)return tk(j,k.relationships);return j}class A8{providers=new Map;register(_){let{category:k,name:j}=_;if(!this.providers.has(k))this.providers.set(k,new Map);this.providers.get(k).set(j,_)}get(_,k){return this.providers.get(_)?.get(k)}getProvidersInCategory(_){let k=this.providers.get(_);return k?Array.from(k.values()):[]}getCategories(){return Array.from(this.providers.keys())}remove(_,k){let j=this.providers.get(_);if(j)return j.delete(k);return!1}clear(){this.providers.clear()}}class K1{random;locale;constructor(_,k){this.random=_,this.locale=k}street(){let _=this.random.arrayElement(this.locale.address.street),k=this.streetSuffix();return`${_} ${k}`}streetSuffix(){return this.random.arrayElement(this.locale.address.streetSuffix??["Street","Avenue","Road","Boulevard","Drive","Lane","Way"])}streetAddress(_){let k=this.buildingNumber(),j=this.street();if(_?.useFullAddress)return`${k} ${j}, ${this.city()}, ${this.stateAbbr()} ${this.zipCode()}`;return`${k} ${j}`}buildingNumber(){let _=this.random.arrayElement(this.locale.address.buildingNumber??["#","##","###"]);return this.random.replaceSymbols(_)}city(){return this.random.arrayElement(this.locale.address.city)}state(){return this.random.arrayElement(this.locale.address.state)}stateAbbr(){return this.random.arrayElement(this.locale.address.stateAbbr??[])}country(){return this.random.arrayElement(this.locale.address.country)}countryCode(){return this.random.arrayElement(this.locale.address.countryCode??[])}zipCode(){let _=this.random.arrayElement(this.locale.address.zipCode);return this.random.replaceSymbols(_)}direction(){return this.random.arrayElement(this.locale.address.direction??["North","South","East","West"])}latitude(_){let k=_?.min??-90,j=_?.max??90,d=_?.precision??4;return this.random.float(k,j,d)}longitude(_){let k=_?.min??-180,j=_?.max??180,d=_?.precision??4;return this.random.float(k,j,d)}address(){return this.streetAddress({useFullAddress:!0})}cityAdvanced(_){let k;if(_?.constraints?.country){let j=_.constraints.country,d=Array.isArray(j)?j:[j];k=this.city()}else k=this.city();if(_?.weighted)k=l1(this.random,_.weighted);if(_?.relationships)k=tk({city:k,country:_?.constraints?.country},_.relationships).city||k;if(_?.validation){let j=u1(k,_.validation);if(!j.isValid){if(_.validation.strict)throw Error(`Validation failed: ${j.errors.join(", ")}`);k=this.city()}}return k}countryAdvanced(_){let k;if(_?.constraints?.country){let j=_.constraints.country,d=Array.isArray(j)?j:[j];k=this.random.arrayElement(d)}else k=this.country();if(_?.weighted)k=l1(this.random,_.weighted);if(_?.relationships)k=tk({country:k},_.relationships).country||k;if(_?.validation){let j=u1(k,_.validation);if(!j.isValid){if(_.validation.strict)throw Error(`Validation failed: ${j.errors.join(", ")}`);k=this.country()}}return k}addressAdvanced(_){let k=this.countryAdvanced(_),j=this.cityAdvanced(_),d=this.state(),O=this.stateAbbr(),$=this.zipCode(),Z=this.street(),X=this.latitude(),E=this.longitude(),F={street:Z,city:j,state:d,stateAbbr:O,country:k,countryCode:this.countryCode(),zipCode:$,latitude:X,longitude:E};if(_?.relationships)return tk(F,_.relationships);return F}neighborhood(_){let k=_?.size||this.random.int(3,10),j=this.cityAdvanced(_),d=this.state(),O=this.zipCode(),$=[];for(let Z=0;Z<k;Z++)$.push({street:this.street(),city:j,state:d,zipCode:O,latitude:this.latitude({min:this.latitude()-0.01,max:this.latitude()+0.01}),longitude:this.longitude({min:this.longitude()-0.01,max:this.longitude()+0.01})});return $}}class n1{random;locale;constructor(_,k){this.random=_,this.locale=k}type(){if(this.locale?.animal?.type)return this.random.arrayElement(this.locale.animal.type);let _=["Mammal","Bird","Reptile","Amphibian","Fish","Invertebrate","Insect","Arachnid"];return this.random.arrayElement(_)}dog(){if(this.locale?.animal?.dog)return this.random.arrayElement(this.locale.animal.dog);let _=["Golden Retriever","Labrador Retriever","German Shepherd","Bulldog","Beagle","Poodle","Rottweiler","Yorkshire Terrier","Boxer","Dachshund","Siberian Husky","Great Dane","Doberman Pinscher","Australian Shepherd","Cavalier King Charles Spaniel","Shih Tzu","Boston Terrier","Pomeranian","Havanese","Shetland Sheepdog","Bernese Mountain Dog","English Springer Spaniel","Brittany","Pug","Cocker Spaniel","Border Collie"];return this.random.arrayElement(_)}cat(){if(this.locale?.animal?.cat)return this.random.arrayElement(this.locale.animal.cat);let _=["Persian","Maine Coon","Ragdoll","British Shorthair","Siamese","Scottish Fold","Sphynx","Abyssinian","Devon Rex","American Shorthair","Bengal","Russian Blue","Birman","Oriental Shorthair","Norwegian Forest Cat","Cornish Rex","Himalayan","Exotic Shorthair","Burmese","Turkish Angora","Somali","Manx","Tonkinese"];return this.random.arrayElement(_)}bird(){if(this.locale?.animal?.bird)return this.random.arrayElement(this.locale.animal.bird);let _=["Eagle","Hawk","Falcon","Owl","Parrot","Macaw","Cockatoo","Parakeet","Canary","Finch","Sparrow","Robin","Blue Jay","Cardinal","Crow","Raven","Pigeon","Dove","Hummingbird","Woodpecker","Pelican","Swan","Duck","Goose","Flamingo","Penguin","Ostrich","Emu","Peacock","Turkey","Chicken","Rooster"];return this.random.arrayElement(_)}fish(){if(this.locale?.animal?.fish)return this.random.arrayElement(this.locale.animal.fish);let _=["Goldfish","Betta","Guppy","Angelfish","Neon Tetra","Molly","Platy","Swordtail","Clownfish","Tang","Damselfish","Lionfish","Grouper","Snapper","Tuna","Marlin","Swordfish","Shark","Ray","Barracuda","Catfish","Bass","Pike","Trout","Carp"];return this.random.arrayElement(_)}bear(){let _=["Grizzly Bear","Black Bear","Polar Bear","Brown Bear","Panda Bear","Sun Bear","Sloth Bear","Spectacled Bear","Asian Black Bear","Kodiak Bear"];return this.random.arrayElement(_)}cetacean(){let _=["Blue Whale","Humpback Whale","Orca","Dolphin","Porpoise","Beluga Whale","Sperm Whale","Gray Whale","Narwhal","Bottlenose Dolphin","Pilot Whale"];return this.random.arrayElement(_)}horse(){if(this.locale?.animal?.horse)return this.random.arrayElement(this.locale.animal.horse);let _=["Arabian","Thoroughbred","Quarter Horse","Morgan","Appaloosa","Paint Horse","Tennessee Walker","Standardbred","Mustang","Andalusian","Friesian","Clydesdale","Percheron","Belgian","Shire","Haflinger","Icelandic","Shetland Pony"];return this.random.arrayElement(_)}insect(){if(this.locale?.animal?.insect)return this.random.arrayElement(this.locale.animal.insect);let _=["Butterfly","Moth","Bee","Wasp","Ant","Beetle","Dragonfly","Grasshopper","Cricket","Ladybug","Firefly","Mosquito","Fly","Cockroach","Termite","Flea","Praying Mantis","Cicada","Caterpillar","Walking Stick"];return this.random.arrayElement(_)}lion(){let _=["African Lion","Asiatic Lion","Mountain Lion","Sea Lion"];return this.random.arrayElement(_)}rabbit(){if(this.locale?.animal?.rabbit)return this.random.arrayElement(this.locale.animal.rabbit);let _=["Holland Lop","Netherland Dwarf","Mini Rex","Lionhead","Flemish Giant","English Lop","Mini Lop","Dutch","Himalayan","Californian","New Zealand","Rex","Angora"];return this.random.arrayElement(_)}snake(){let _=["Python","Boa Constrictor","Rattlesnake","Cobra","Viper","Anaconda","Garter Snake","Corn Snake","King Snake","Milk Snake","Black Mamba","Copperhead","Cottonmouth"];return this.random.arrayElement(_)}}class J1{random;locale;constructor(_,k){this.random=_,this.locale=k}title(){if(this.locale?.book?.title)return this.random.arrayElement(this.locale.book.title);let _=["To Kill a Mockingbird","1984","Pride and Prejudice","The Great Gatsby","Moby Dick","War and Peace","The Odyssey","The Catcher in the Rye","The Lord of the Rings","Harry Potter and the Sorcerer's Stone","The Hobbit","The Chronicles of Narnia","Brave New World","The Divine Comedy","Crime and Punishment","The Brothers Karamazov","One Hundred Years of Solitude","The Sound and the Fury","Invisible Man","Beloved","The Grapes of Wrath","Catch-22","Slaughterhouse-Five","Fahrenheit 451","The Handmaid's Tale","The Road","Life of Pi","The Kite Runner","The Book Thief"];return this.random.arrayElement(_)}author(){if(this.locale?.book?.author)return this.random.arrayElement(this.locale.book.author);let _=["Ernest Hemingway","F. Scott Fitzgerald","Jane Austen","Charles Dickens","Mark Twain","Leo Tolstoy","Fyodor Dostoevsky","George Orwell","J.R.R. Tolkien","J.K. Rowling","Stephen King","Agatha Christie","William Shakespeare","Edgar Allan Poe","Harper Lee","Maya Angelou","Toni Morrison","Gabriel Garc\xEDa M\xE1rquez","Franz Kafka","James Joyce","Virginia Woolf","Oscar Wilde","Emily Dickinson","Walt Whitman","Robert Frost","Sylvia Plath","Kurt Vonnegut","Margaret Atwood","Haruki Murakami","Chimamanda Ngozi Adichie"];return this.random.arrayElement(_)}publisher(){if(this.locale?.book?.publisher)return this.random.arrayElement(this.locale.book.publisher);let _=["Penguin Random House","HarperCollins","Simon & Schuster","Macmillan","Hachette","Scholastic","Oxford University Press","Cambridge University Press","Pearson","Wiley","Springer","McGraw-Hill","Bloomsbury","Vintage","Doubleday","Knopf"];return this.random.arrayElement(_)}genre(){if(this.locale?.book?.genre)return this.random.arrayElement(this.locale.book.genre);let _=["Fiction","Non-Fiction","Mystery","Thriller","Romance","Science Fiction","Fantasy","Horror","Historical Fiction","Biography","Autobiography","Self-Help","Poetry","Drama","Comedy","Adventure","Young Adult","Children's","Crime","Western","Dystopian","Paranormal","Contemporary","Classic","Literary Fiction"];return this.random.arrayElement(_)}series(){if(this.locale?.book?.series)return this.random.arrayElement(this.locale.book.series);let _=["Harry Potter","The Lord of the Rings","A Song of Ice and Fire","The Hunger Games","Twilight","The Chronicles of Narnia","Percy Jackson","The Maze Runner","Divergent","The Mortal Instruments","Sherlock Holmes","Discworld","Dune","Foundation","The Wheel of Time","The Witcher","Millennium","Jack Reacher"];return this.random.arrayElement(_)}isbn(){if(this.random.boolean(0.5)){let $=Array.from({length:9},()=>this.random.int(0,9)),Z=this.random.int(0,10)===10?"X":String(this.random.int(0,9));return`${$.slice(0,1).join("")}-${$.slice(1,4).join("")}-${$.slice(4,9).join("")}-${Z}`}let _="978",k=this.random.int(0,9),j=Array.from({length:3},()=>this.random.int(0,9)).join(""),d=Array.from({length:5},()=>this.random.int(0,9)).join(""),O=this.random.int(0,9);return`${_}-${k}-${j}-${d}-${O}`}format(){let _=["Hardcover","Paperback","Mass Market Paperback","eBook","Audiobook","Kindle","PDF","EPUB","Board Book","Leather Bound","Library Binding"];return this.random.arrayElement(_)}review(){if(this.locale?.book?.review)return this.random.arrayElement(this.locale.book.review);let _=["A masterpiece of modern literature!","Gripping from start to finish.","Couldn't put it down!","A must-read for everyone.","Beautifully written and deeply moving.","An unforgettable story.","Brilliant and thought-provoking.","A page-turner with incredible characters.","One of the best books I've ever read.","Absolutely captivating!"];return this.random.arrayElement(_)}}class I1{random;locale;constructor(_,k){this.random=_,this.locale=k}hex(_){let k=_?.prefix??"#",j=this.random.int(0,16777215).toString(16).padStart(6,"0").toUpperCase();return k+j}rgb(_){let k=this.random.int(0,255),j=this.random.int(0,255),d=this.random.int(0,255);if(_?.alpha){let O=this.random.float(0,1,2);if(_?.format==="array")return[k,j,d,O];return`rgba(${k}, ${j}, ${d}, ${O})`}if(_?.format==="array")return[k,j,d];return`rgb(${k}, ${j}, ${d})`}hsl(_){let k=this.random.int(0,360),j=this.random.int(0,100),d=this.random.int(0,100);if(_?.alpha){let O=this.random.float(0,1,2);if(_?.format==="array")return[k,j,d,O];return`hsla(${k}, ${j}%, ${d}%, ${O})`}if(_?.format==="array")return[k,j,d];return`hsl(${k}, ${j}%, ${d}%)`}css(_){let k=_?.format??this.random.arrayElement(["hex","rgb","hsl"]);if(k==="hex")return this.hex();if(k==="rgb")return this.rgb();return this.hsl()}name(){if(this.locale?.commerce?.color)return this.random.arrayElement(this.locale.commerce.color);let _=["Red","Blue","Green","Yellow","Purple","Orange","Pink","Brown","Black","White","Gray","Cyan","Magenta","Lime","Navy","Teal","Olive","Maroon","Aqua","Silver","Fuchsia","Gold","Indigo","Violet"];return this.random.arrayElement(_)}hexColor(){return this.hex()}rgbColor(){return this.rgb()}rgbColorAsArray(){return this.rgb({format:"array"})}}class D1{random;locale;constructor(_,k){this.random=_,this.locale=k}product(){let _=this.locale?.commerce?.productAdjective??["Small","Ergonomic","Rustic","Intelligent","Gorgeous","Incredible","Fantastic","Practical","Sleek","Awesome","Generic","Handcrafted","Handmade","Licensed","Refined","Unbranded","Tasty","Premium","Luxury","Professional","Durable"],k=this.locale?.commerce?.productMaterial??["Steel","Wooden","Concrete","Plastic","Cotton","Granite","Rubber","Metal","Soft","Fresh","Frozen","Silk","Leather","Glass","Carbon","Aluminum"],j=this.locale?.commerce?.product??["Chair","Table","Lamp","Keyboard","Mouse","Computer","Shoes","Shirt","Pants","Hat","Gloves","Towel","Soap","Bike","Ball","Book","Wallet","Watch","Phone","Desk","Bottle","Plate","Cup","Bag","Pen","Notebook","Backpack","Sunglasses"];return`${this.random.arrayElement(_)} ${this.random.arrayElement(k)} ${this.random.arrayElement(j)}`}productName(){return this.product()}department(){if(this.locale?.commerce?.department)return this.random.arrayElement(this.locale.commerce.department);let _=["Books","Movies","Music","Games","Electronics","Computers","Home","Garden","Tools","Grocery","Health","Beauty","Toys","Kids","Baby","Clothing","Shoes","Jewelry","Sports","Outdoors","Automotive","Industrial"];return this.random.arrayElement(_)}price(_){let k=_?.min??1,j=_?.max??1000,d=_?.dec??2,O=_?.symbol??"",$=this.random.float(k,j,d);return O+$.toFixed(d)}productAdjective(){if(this.locale?.commerce?.productAdjective)return this.random.arrayElement(this.locale.commerce.productAdjective);let _=["Small","Ergonomic","Rustic","Intelligent","Gorgeous","Incredible","Fantastic","Practical","Sleek","Awesome","Generic","Handcrafted","Handmade","Licensed","Refined","Unbranded","Tasty","Premium","Luxury","Professional","Durable","Innovative","Compact","Versatile","Modern","Classic","Vintage","Contemporary"];return this.random.arrayElement(_)}productMaterial(){if(this.locale?.commerce?.productMaterial)return this.random.arrayElement(this.locale.commerce.productMaterial);let _=["Steel","Wooden","Concrete","Plastic","Cotton","Granite","Rubber","Metal","Soft","Fresh","Frozen","Silk","Leather","Glass","Carbon","Aluminum","Bronze","Copper","Brass","Titanium","Ceramic","Velvet","Linen","Wool"];return this.random.arrayElement(_)}productDescription(){let _=["The beautiful range of {adjective} {material} {product} comes with a {feature}.","Experience the {adjective} {product} that redefines {benefit}.","Our {adjective} {material} {product} is designed for {benefit}.","Discover the {adjective} {product} with {feature} for {benefit}."],k=["lifetime warranty","money-back guarantee","premium quality","eco-friendly design","cutting-edge technology","ergonomic design","sleek finish","modern aesthetics"],j=["maximum comfort","everyday use","professional performance","home and office","outdoor adventures","creative projects","productivity","entertainment"];return this.random.arrayElement(_).replace("{adjective}",this.productAdjective().toLowerCase()).replace("{material}",this.productMaterial().toLowerCase()).replace("{product}","product").replace("{feature}",this.random.arrayElement(k)).replace("{benefit}",this.random.arrayElement(j))}review(){let _=["This product exceeded my expectations!","Absolutely love it! Worth every penny.","Great quality and fast shipping.","Not what I expected, but still decent.","Amazing! Highly recommend to everyone.","Perfect for my needs. Very satisfied.","Good value for the price.","Could be better, but it does the job.","Fantastic product! Will buy again.","Best purchase I've made this year!"];return this.random.arrayElement(_)}discountCode(){let _=["SAVE","GET","DEAL","OFFER","PROMO","SALE","DISCOUNT","SPECIAL"],k=this.random.int(10,99);return`${this.random.arrayElement(_)}${k}`}sku(){let _=this.random.arrayElement("ABCDEFGHIJKLMNOPQRSTUVWXYZ".split("")).repeat(3),k=this.random.int(1e4,99999),j=this.random.arrayElement("ABCDEFGHIJKLMNOPQRSTUVWXYZ".split("")).repeat(3);return`${_}-${k}-${j}`}}class R1{random;locale;constructor(_,k){this.random=_,this.locale=k}name(){let _=this.random.arrayElement(this.locale.company.name??["Company"]),k=this.random.arrayElement(this.locale.company.suffix??["Inc","LLC","Corp"]);return`${_} ${k}`}suffix(){return this.random.arrayElement(this.locale.company.suffix??["Inc","LLC","Corp"])}industry(){return this.random.arrayElement(this.locale.company.industry??["Technology"])}catchphrase(){let _=this.random.arrayElement(this.locale.company.adjective??["innovative"]),k=this.random.arrayElement(this.locale.company.descriptor??["digital"]),j=this.random.arrayElement(this.locale.company.noun??["solution"]);return`${_} ${k} ${j}`}buzzword(){return this.random.arrayElement(this.locale.company.buzzwords??["innovation"])}bs(){let _=this.buzzword(),k=this.random.arrayElement(this.locale.company.descriptor??["digital"]),j=this.random.arrayElement(this.locale.company.noun??["solution"]);return`${_} ${k} ${j}`}}class tO{random;constructor(_){this.random=_}engine(){let _=["MySQL","PostgreSQL","MongoDB","SQLite","Redis","Oracle","Microsoft SQL Server","MariaDB","Cassandra","Elasticsearch","DynamoDB","CouchDB","Neo4j","Firebase","Firestore","InfluxDB","TimescaleDB","RethinkDB","ArangoDB","CockroachDB"];return this.random.arrayElement(_)}type(){let _=["VARCHAR","INTEGER","BIGINT","SMALLINT","DECIMAL","NUMERIC","FLOAT","DOUBLE","BOOLEAN","DATE","TIME","TIMESTAMP","DATETIME","TEXT","BLOB","JSON","JSONB","UUID","ENUM","ARRAY","SERIAL","BIGSERIAL"];return this.random.arrayElement(_)}collation(){let _=["utf8_general_ci","utf8_unicode_ci","utf8mb4_general_ci","utf8mb4_unicode_ci","latin1_swedish_ci","latin1_general_ci","utf8_bin","utf8mb4_bin"];return this.random.arrayElement(_)}column(){let _=["id","user_id","name","email","password","created_at","updated_at","deleted_at","first_name","last_name","phone","address","city","state","country","zip_code","status","role","permissions","description","price","quantity","total","subtotal","tax","discount","shipping","notes","metadata","settings","preferences","avatar"];return this.random.arrayElement(_)}table(){let _=["users","posts","comments","products","orders","customers","invoices","payments","categories","tags","roles","permissions","sessions","settings","notifications","messages","attachments","logs","analytics","reports","subscriptions","transactions"];return this.random.arrayElement(_)}mongodbObjectId(){let _="";for(let k=0;k<24;k++)_+="0123456789abcdef"[this.random.int(0,15)];return _}constraint(){let _=["PRIMARY KEY","FOREIGN KEY","UNIQUE","NOT NULL","CHECK","DEFAULT","INDEX"];return this.random.arrayElement(_)}queryType(){let _=["SELECT","INSERT","UPDATE","DELETE","CREATE","ALTER","DROP","TRUNCATE","JOIN","LEFT JOIN","RIGHT JOIN","INNER JOIN","OUTER JOIN","UNION","WHERE"];return this.random.arrayElement(_)}connectionString(_){let k=_?.engine??this.engine().toLowerCase().replace(/ /g,""),j="user",d="password",O="localhost",$=this.random.int(3000,9999),Z=this.table(),X={mysql:"mysql",postgresql:"postgresql",mongodb:"mongodb",redis:"redis"}[k]||"jdbc";if(k==="mongodb")return`${X}://user:password@localhost:${$}/${Z}`;return`${X}://user:password@localhost:${$}/${Z}`}}class aO{random;constructor(_){this.random=_}past(_){let k=_?.years??1,j=_?.to??new Date,d=_?.from??new Date(j.getTime()-k*365*24*60*60*1000);return this.between({from:d,to:j})}future(_){let k=_?.years??1,j=_?.from??new Date,d=_?.to??new Date(j.getTime()+k*365*24*60*60*1000);return this.between({from:j,to:d})}between(_){let k=_.from??new Date(Date.now()-31536000000),j=_.to??new Date,d=k.getTime(),O=j.getTime(),$=this.random.int(d,O);return new Date($)}recent(_){let k=_?.days??1,j=new Date,d=new Date(j.getTime()-k*24*60*60*1000);return this.between({from:d,to:j})}soon(_){let k=_?.days??1,j=new Date,d=new Date(j.getTime()+k*24*60*60*1000);return this.between({from:j,to:d})}month(){let _=["January","February","March","April","May","June","July","August","September","October","November","December"];return this.random.arrayElement(_)}weekday(){let _=["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"];return this.random.arrayElement(_)}dateTime(){return this.between({from:new Date(1970,0,1),to:new Date})}dateTimeBetween(_){return this.between(_)}}class eO{random;constructor(_){this.random=_}amount(_){let k=_?.min??0,j=_?.max??1e4,d=_?.dec??2,O=_?.symbol??"",$=this.random.float(k,j,d);return O+$.toFixed(d)}account(_=8){let k="";for(let j=0;j<_;j++)k+=this.random.int(0,9);return k}accountName(){let _=["Savings","Checking","Money Market","Investment","Credit Card","Personal Loan"];return`${this.random.arrayElement(_)} Account`}routingNumber(){return this.account(9)}creditCardNumber(_){let k=_?.formatted??!0,j=_?.issuer??this.random.arrayElement(["visa","mastercard","amex","discover"]),d="",O=16;switch(j){case"visa":d="4",O=16;break;case"mastercard":d=`5${this.random.int(1,5)}`,O=16;break;case"amex":d=`3${this.random.arrayElement(["4","7"])}`,O=15;break;case"discover":d="6011",O=16;break}let $=d;while($.length<O)$+=this.random.int(0,9);if(k){if(j==="amex")return`${$.slice(0,4)}-${$.slice(4,10)}-${$.slice(10)}`;return $.match(/.{1,4}/g)?.join("-")??$}return $}cvv(){return this.account(3)}iban(_){let k=_?.countryCode??"GB",j=_?.formatted??!1,d=this.random.int(10,99).toString(),O="WEST",$=this.account(14),Z=k+d+"WEST"+$;if(j)return Z.match(/.{1,4}/g)?.join(" ")??Z;return Z}bic(){let _="";for(let k=0;k<4;k++)_+="ABCDEFGHIJKLMNOPQRSTUVWXYZ"[this.random.int(0,25)];for(let k=0;k<2;k++)_+="ABCDEFGHIJKLMNOPQRSTUVWXYZ"[this.random.int(0,25)];for(let k=0;k<2;k++)_+=this.random.arrayElement([..."ABCDEFGHIJKLMNOPQRSTUVWXYZ".split(""),...Array.from({length:10},(j,d)=>d.toString())]);return _}bitcoin(){let _=this.random.arrayElement(["1","3"]);for(let k=0;k<33;k++)_+="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"[this.random.int(0,57)];return _}ethereum(){let _="0x";for(let k=0;k<40;k++)_+="0123456789abcdef"[this.random.int(0,15)];return _}currencyCode(){let _=["USD","EUR","GBP","JPY","AUD","CAD","CHF","CNY","SEK","NZD","INR","BRL","RUB","KRW"];return this.random.arrayElement(_)}currencyName(){let _=["US Dollar","Euro","British Pound","Japanese Yen","Australian Dollar","Canadian Dollar","Swiss Franc","Chinese Yuan","Swedish Krona","New Zealand Dollar","Indian Rupee","Brazilian Real","Russian Ruble","South Korean Won"];return this.random.arrayElement(_)}currencySymbol(){let _=["$","\u20AC","\xA3","\xA5","\u20B9","R$","\u20BD","\u20A9","kr","CHF"];return this.random.arrayElement(_)}transactionType(){let _=["deposit","withdrawal","payment","invoice","transfer"];return this.random.arrayElement(_)}}class w1{random;locale;constructor(_,k){this.random=_,this.locale=k}dish(){if(this.locale?.food?.dish)return this.random.arrayElement(this.locale.food.dish);let _=["Spaghetti Carbonara","Chicken Alfredo","Beef Tacos","Margherita Pizza","Caesar Salad","Pad Thai","Chicken Tikka Masala","Sushi Roll","Beef Burger","Fish and Chips","Ramen","Tom Yum Soup","Greek Salad","Lasagna","Paella","Pho","Falafel Wrap","Burrito Bowl","Chicken Curry","Steak Frites","Risotto","Poke Bowl","Bibimbap","Shakshuka","Eggs Benedict","Club Sandwich","Caprese Salad","Fettuccine Alfredo","Chicken Parmesan","Pulled Pork Sandwich","Gyro","Butter Chicken","Peking Duck"];return this.random.arrayElement(_)}ingredient(){if(this.locale?.food?.ingredient)return this.random.arrayElement(this.locale.food.ingredient);let _=["Garlic","Onion","Tomato","Basil","Oregano","Thyme","Rosemary","Cilantro","Parsley","Salt","Pepper","Olive Oil","Butter","Flour","Sugar","Eggs","Milk","Cheese","Chicken","Beef","Pork","Fish","Shrimp","Rice","Pasta","Potatoes","Carrots","Celery","Bell Pepper","Mushrooms","Spinach","Lettuce","Cucumber","Avocado","Lemon","Lime","Ginger","Soy Sauce","Vinegar","Honey","Cinnamon","Cumin"];return this.random.arrayElement(_)}spice(){if(this.locale?.food?.spice)return this.random.arrayElement(this.locale.food.spice);let _=["Basil","Oregano","Thyme","Rosemary","Sage","Cilantro","Parsley","Mint","Dill","Paprika","Cumin","Turmeric","Coriander","Cardamom","Cinnamon","Nutmeg","Cloves","Black Pepper","White Pepper","Cayenne","Chili Powder","Curry Powder","Garam Masala","Saffron","Vanilla","Bay Leaf","Fennel","Anise","Tarragon","Marjoram"];return this.random.arrayElement(_)}vegetable(){if(this.locale?.food?.vegetable)return this.random.arrayElement(this.locale.food.vegetable);let _=["Broccoli","Carrot","Celery","Lettuce","Spinach","Kale","Cabbage","Cauliflower","Brussels Sprouts","Asparagus","Green Beans","Peas","Corn","Potato","Sweet Potato","Tomato","Cucumber","Bell Pepper","Zucchini","Eggplant","Mushroom","Onion","Garlic","Radish","Beet","Turnip","Artichoke","Bok Choy","Arugula","Swiss Chard"];return this.random.arrayElement(_)}fruit(){if(this.locale?.food?.fruit)return this.random.arrayElement(this.locale.food.fruit);let _=["Apple","Banana","Orange","Grape","Strawberry","Blueberry","Raspberry","Blackberry","Mango","Pineapple","Watermelon","Cantaloupe","Honeydew","Peach","Plum","Cherry","Pear","Kiwi","Papaya","Dragon Fruit","Lychee","Passion Fruit","Pomegranate","Coconut","Avocado","Lemon","Lime","Grapefruit","Apricot","Fig","Date"];return this.random.arrayElement(_)}meat(){if(this.locale?.food?.meat)return this.random.arrayElement(this.locale.food.meat);let _=["Beef","Chicken","Pork","Lamb","Turkey","Duck","Veal","Venison","Bison","Rabbit","Goat","Quail","Pheasant","Bacon","Sausage","Ham","Salami"];return this.random.arrayElement(_)}seafood(){let _=["Salmon","Tuna","Cod","Halibut","Trout","Mackerel","Sardines","Anchovies","Shrimp","Crab","Lobster","Scallops","Clams","Mussels","Oysters","Squid","Octopus","Tilapia","Sea Bass","Swordfish","Snapper","Grouper","Catfish"];return this.random.arrayElement(_)}dessert(){if(this.locale?.food?.dessert)return this.random.arrayElement(this.locale.food.dessert);let _=["Chocolate Cake","Cheesecake","Apple Pie","Ice Cream","Brownies","Cookies","Tiramisu","Cr\xE8me Br\xFBl\xE9e","Panna Cotta","Macarons","Cupcakes","Donuts","Eclairs","Profiteroles","Cannoli","Baklava","Flan","Churros","Gelato","Sorbet","Mousse","Tart","Cobbler","Pudding","Trifle","Souffl\xE9"];return this.random.arrayElement(_)}ethnicCategory(){if(this.locale?.food?.cuisine)return this.random.arrayElement(this.locale.food.cuisine);let _=["Italian","Chinese","Japanese","Mexican","Thai","Indian","French","Greek","Spanish","Korean","Vietnamese","Lebanese","Turkish","Brazilian","Moroccan","Ethiopian","Caribbean","Peruvian","German","American","British","Irish"];return this.random.arrayElement(_)}description(){let _=["Delicious","Savory","Sweet","Spicy","Tangy","Crispy","Tender","Juicy","Flavorful","Rich","Fresh","Aromatic","Creamy","Zesty","Hearty","Light"],k=["and flavorful","and satisfying","and aromatic","and authentic","and homemade","and traditional","and innovative","and exquisite","and mouthwatering"];return`${this.random.arrayElement(_)} ${this.random.arrayElement(k)}`}}class _0{random;constructor(_){this.random=_}branch(){let _=["feature","bugfix","hotfix","refactor","chore","docs","test"],k=["add","update","fix","remove","improve","refactor","optimize","enhance","implement"],j=["authentication","database","api","ui","tests","documentation","config","validation","error-handling","logging","security","performance","caching"],d=this.random.arrayElement(_),O=this.random.arrayElement(k),$=this.random.arrayElement(j);return`${d}/${O}-${$}`}commitMessage(){let _=["feat","fix","docs","style","refactor","test","chore","perf"],k=["api","ui","auth","db","config","deps","core","utils"],j=["add","update","fix","remove","improve","refactor","optimize","enhance","implement"],d=["user authentication","database connection","API endpoint","UI component","test coverage","documentation","configuration","validation logic","error handling","logging system"],O=this.random.arrayElement(_),$=this.random.boolean(0.5)?`(${this.random.arrayElement(k)})`:"",Z=this.random.arrayElement(j),X=this.random.arrayElement(d);return`${O}${$}: ${Z} ${X}`}commitSha(_){let k=_?.short?7:40,j="0123456789abcdef",d="";for(let O=0;O<k;O++)d+="0123456789abcdef"[this.random.int(0,15)];return d}commitEntry(){let _=this.commitSha({short:!0}),k=this.commitMessage();return`${_} ${k}`}commitAuthor(_){let k=["John Doe","Jane Smith","Bob Johnson","Alice Williams","Charlie Brown","Diana Davis","Eve Martinez","Frank Garcia","Grace Wilson","Henry Lee"],j=_?.name??this.random.arrayElement(k),d=_?.email??`${j.toLowerCase().replace(" ",".")}@example.com`;return`${j} <${d}>`}remote(_){let k=_?.protocol??this.random.arrayElement(["https","ssh"]),j=_?.platform??this.random.arrayElement(["github","gitlab","bitbucket"]),d=this.random.arrayElement(["acme","techcorp","devteam","opensource","mycompany"]),O=this.random.arrayElement(["webapp","api","mobile-app","backend","frontend","monorepo"]),$={github:"github.com",gitlab:"gitlab.com",bitbucket:"bitbucket.org"};if(k==="ssh")return`git@${$[j]}:${d}/${O}.git`;return`https://${$[j]}/${d}/${O}.git`}tag(){let _=this.random.int(0,5),k=this.random.int(0,20),j=this.random.int(0,50),d=this.random.boolean(0.2)?`-${this.random.arrayElement(["alpha","beta","rc"])}.${this.random.int(1,10)}`:"";return`v${_}.${k}.${j}${d}`}}class M1{random;locale;constructor(_,k){this.random=_,this.locale=k}abbreviation(){if(this.locale?.hacker?.abbreviation)return this.random.arrayElement(this.locale.hacker.abbreviation);let _=["TCP","HTTP","SDD","RAM","GB","CSS","SSL","AGP","SQL","CLI","IB","UX","UI","FTP","AI","ADP","RSS","XML","EXE","COM","HDD","THX","MP3","GPU","API","DNS","IP","LAN","WAN","VPN","SSH","HTTPS","JSON","REST","SOAP"];return this.random.arrayElement(_)}adjective(){if(this.locale?.hacker?.adjective)return this.random.arrayElement(this.locale.hacker.adjective);let _=["auxiliary","primary","back-end","digital","open-source","virtual","cross-platform","redundant","online","haptic","multi-byte","bluetooth","wireless","mobile","neural","optical","solid state","cloud","quantum","distributed","encrypted"];return this.random.arrayElement(_)}noun(){if(this.locale?.hacker?.noun)return this.random.arrayElement(this.locale.hacker.noun);let _=["driver","protocol","bandwidth","panel","microchip","program","port","card","array","interface","system","sensor","firewall","hard drive","pixel","alarm","feed","monitor","application","transmitter","bus","circuit","capacitor","matrix","server","database","network","router","switch","gateway","node","cluster"];return this.random.arrayElement(_)}verb(){if(this.locale?.hacker?.verb)return this.random.arrayElement(this.locale.hacker.verb);let _=["back up","bypass","hack","override","compress","copy","navigate","index","connect","generate","quantify","calculate","synthesize","input","transmit","program","reboot","parse","compile","encode","decode","encrypt","decrypt","patch","upgrade","deploy","configure","optimize","refactor","debug"];return this.random.arrayElement(_)}ingverb(){if(this.locale?.hacker?.ingverb)return this.random.arrayElement(this.locale.hacker.ingverb);let _=["backing up","bypassing","hacking","overriding","compressing","copying","navigating","indexing","connecting","generating","quantifying","calculating","synthesizing","transmitting","programming","parsing","compiling","encoding","decoding","encrypting","decrypting","patching","deploying","configuring","optimizing"];return this.random.arrayElement(_)}phrase(){if(this.locale?.hacker?.phrase)return this.random.arrayElement(this.locale.hacker.phrase);let _=["If we {verb} the {noun}, we can get to the {abbreviation} {noun} through the {adjective} {abbreviation} {noun}!","We need to {verb} the {adjective} {abbreviation} {noun}!","Try to {verb} the {abbreviation} {noun}, maybe it will {verb} the {adjective} {noun}!","You can't {verb} the {noun} without {ingverb} the {adjective} {abbreviation} {noun}!","Use the {adjective} {abbreviation} {noun}, then you can {verb} the {adjective} {noun}!","The {abbreviation} {noun} is down, {verb} the {adjective} {noun} so we can {verb} the {abbreviation} {noun}!","{ingverb} the {noun} won't do anything, we need to {verb} the {adjective} {abbreviation} {noun}!","I'll {verb} the {adjective} {abbreviation} {noun}, that should {verb} the {abbreviation} {noun}!"];return this.random.arrayElement(_).replace(/\{verb\}/g,()=>this.verb()).replace(/\{ingverb\}/g,()=>this.ingverb()).replace(/\{noun\}/g,()=>this.noun()).replace(/\{adjective\}/g,()=>this.adjective()).replace(/\{abbreviation\}/g,()=>this.abbreviation())}}class k0{random;constructor(_){this.random=_}randomElement(_){return this.random.arrayElement(_)}arrayElement(_){return this.random.arrayElement(_)}arrayElements(_,k){return this.random.arrayElements(_,k)}shuffle(_){return this.random.shuffle(_)}numerify(_){return _.replace(/#/g,()=>String(this.random.int(0,9)))}lexify(_){return _.replace(/\?/g,()=>this.random.arrayElement("abcdefghijklmnopqrstuvwxyz".split("")))}bothify(_){return this.numerify(this.lexify(_))}replaceSymbols(_){return this.random.replaceSymbols(_)}boolean(_=0.5){return this.random.boolean(_)}objectKey(_){let k=Object.keys(_);return this.random.arrayElement(k)}objectValue(_){let k=this.objectKey(_);return _[k]}multiple(_,k=3){return Array.from({length:k},_)}maybe(_,k=0.5){return this.random.boolean(k)?_():void 0}unique(_,k=50){let j=new Set,d=0;while(d<k){let O=_();if(!j.has(O))return j.add(O),O;d++}throw Error(`Failed to generate unique value after ${k} retries`)}replaceCreditCardSymbols(_="####-####-####-####",k="#"){return this.random.replaceCreditCardSymbols(_,k)}regexify(_){return _.replace(/\[A-Z\]/g,()=>this.random.arrayElement("ABCDEFGHIJKLMNOPQRSTUVWXYZ".split(""))).replace(/\[a-z\]/g,()=>this.random.arrayElement("abcdefghijklmnopqrstuvwxyz".split(""))).replace(/\[0-9\]/g,()=>String(this.random.int(0,9))).replace(/\{(\d+)\}/g,(k,j)=>{return""})}}class j0{random;constructor(_){this.random=_}url(_){let k=_?.width??640,j=_?.height??480;return`https://via.placeholder.com/${k}x${j}`}avatar(){return`https://i.pravatar.cc/${this.random.int(100,500)}`}urlLoremFlickr(_){let k=_?.width??640,j=_?.height??480,d=_?.category??"";if(d)return`https://loremflickr.com/${k}/${j}/${d}`;return`https://loremflickr.com/${k}/${j}`}urlPicsumPhotos(_){let k=_?.width??640,j=_?.height??480,d=`https://picsum.photos/${k}/${j}`;if(_?.grayscale)d+="?grayscale";if(_?.blur)d+=_?.grayscale?`&blur=${_.blur}`:`?blur=${_.blur}`;return d}dataUri(_){let k=_?.width??640,j=_?.height??480,d=_?.color??this.random.int(0,16777215).toString(16).padStart(6,"0"),O=`<svg xmlns="http://www.w3.org/2000/svg" width="${k}" height="${j}"><rect width="${k}" height="${j}" fill="#${d}"/></svg>`;return`data:image/svg+xml;charset=UTF-8,${encodeURIComponent(O)}`}githubAvatar(){return`https://avatars.githubusercontent.com/u/${this.random.int(1,1e5)}`}category(){let _=["abstract","animals","business","cats","city","food","nature","nightlife","fashion","people","sports","technics","transport","travel"];return this.random.arrayElement(_)}imageType(){let _=["jpg","jpeg","png","gif","svg","webp","bmp","tiff"];return this.random.arrayElement(_)}}class C1{random;locale;domainWordsCache=null;constructor(_,k){this.random=_,this.locale=k}getDomainWords(){if(!this.domainWordsCache){let _=this.locale.company.name??["company","tech","digital"];this.domainWordsCache=_.map((k)=>k.toLowerCase().replace(/[^a-z0-9]/g,"")).filter((k)=>k.length>0)}return this.domainWordsCache}email(_){let k;if(_?.firstName)k=_.firstName.toLowerCase();else{let Z=this.locale.person.firstNameMale.length,X=this.locale.person.firstNameFemale.length,E=this.locale.person.firstNameNeutral?.length||0,F=Z+X+E,G=this.random.int(0,F-1);if(G<Z)k=this.locale.person.firstNameMale[G].toLowerCase();else if(G<Z+X)k=this.locale.person.firstNameFemale[G-Z].toLowerCase();else k=this.locale.person.firstNameNeutral[G-Z-X].toLowerCase()}let j=_?.lastName??this.random.arrayElement(this.locale.person.lastName).toLowerCase(),d=_?.provider??this.random.arrayElement(this.locale.internet.domainSuffix??["com","net","org"]),O=this.random.arrayElement(G6),$=this.random.arrayElement(this.getDomainWords());return`${k}${O}${j}@${$}.${d}`}safeEmail(){return this.email({provider:this.random.arrayElement(["example.com","example.org","example.net"])})}freeEmail(){let _=this.locale.person.firstNameMale.length,k=this.locale.person.firstNameFemale.length,j=this.locale.person.firstNameNeutral?.length||0,d=_+k+j,O=this.random.int(0,d-1),$;if(O<_)$=this.locale.person.firstNameMale[O].toLowerCase();else if(O<_+k)$=this.locale.person.firstNameFemale[O-_].toLowerCase();else $=this.locale.person.firstNameNeutral[O-_-k].toLowerCase();let Z=this.random.arrayElement(this.locale.person.lastName).toLowerCase(),X=this.random.arrayElement(this.locale.internet.freeEmail??["gmail.com","yahoo.com","hotmail.com"]),E=[".","_",""],F=this.random.arrayElement(E);return`${$}${F}${Z}@${X}`}username(_){let k;if(_?.firstName)k=_.firstName.toLowerCase();else{let O=this.locale.person.firstNameMale.length,$=this.locale.person.firstNameFemale.length,Z=this.locale.person.firstNameNeutral?.length||0,X=O+$+Z,E=this.random.int(0,X-1);if(E<O)k=this.locale.person.firstNameMale[E].toLowerCase();else if(E<O+$)k=this.locale.person.firstNameFemale[E-O].toLowerCase();else k=this.locale.person.firstNameNeutral[E-O-$].toLowerCase()}let j=_?.lastName?.toLowerCase()??this.random.arrayElement(this.locale.person.lastName).toLowerCase(),d=[`${k}${j}`,`${k}_${j}`,`${k}.${j}`,`${k}${this.random.int(10,999)}`,`${k}_${j}${this.random.int(10,99)}`];return this.random.arrayElement(d)}password(_){let k=_?.length??12,j=_?.memorable??!1,d=_?.prefix??"";if(j){let Z=[...this.locale.person.firstNameMale,...this.locale.person.firstNameFemale,...this.locale.person.firstNameNeutral||[]],X=[];for(let E=0;E<3;E++)X.push(this.random.arrayElement(Z));return d+X.join("-")+this.random.int(10,999)}let O="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*",$=d;for(let Z=d.length;Z<k;Z++)$+=O[this.random.int(0,O.length-1)];return $}url(_){let k=_?.protocol??this.random.arrayElement(["http","https"]),j=_?.domain??this.domainName();return`${k}://${j}`}domainName(){return`${this.domainWord()}.${this.domainSuffix()}`}domainWord(){return this.random.arrayElement(this.getDomainWords())}domainSuffix(){return this.random.arrayElement(this.locale.internet.domainSuffix??["com","net","org"])}ipv4(){return`${this.random.int(0,255)}.${this.random.int(0,255)}.${this.random.int(0,255)}.${this.random.int(0,255)}`}ipv6(){let _=[];for(let k=0;k<8;k++)_.push(this.random.int(0,65535).toString(16).padStart(4,"0"));return _.join(":")}mac(_=":"){let k=[];for(let j=0;j<6;j++)k.push(this.random.int(0,255).toString(16).padStart(2,"0").toUpperCase());return k.join(_)}userAgent(){let _=["Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36","Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36","Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36","Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/120.0","Mozilla/5.0 (Macintosh; Intel Mac OS X 14.0; rv:109.0) Gecko/20100101 Firefox/120.0"];return this.random.arrayElement(_)}slug(_=3){let k=[];for(let j=0;j<_;j++)k.push(this.random.arrayElement(this.locale.company.buzzwords??["innovation","technology","solution"]));return k.join("-").toLowerCase()}ip(){return this.ipv4()}}class d0{random;constructor(_){this.random=_}word(){return this.random.arrayElement(F6)}words(_=3){let k=[];for(let j=0;j<_;j++)k.push(this.word());return k.join(" ")}sentence(_){let k=_??this.random.int(3,10),j=this.words(k);return`${j.charAt(0).toUpperCase()+j.slice(1)}.`}sentences(_=3,k=" "){let j=[];for(let d=0;d<_;d++)j.push(this.sentence());return j.join(k)}paragraph(_){let k=_??this.random.int(3,7);return this.sentences(k)}paragraphs(_=3,k=`
|
|
126
|
-
|
|
127
|
-
`){let j=[];for(let d=0;d<_;d++)j.push(this.paragraph());return j.join(k)}text(_){let k=_??200,j="";while(j.length<k)j+=`${this.paragraph()} `;return j.trim().slice(0,k)}slug(_=3){return this.words(_).replace(/ /g,"-")}lines(_=3){let k=[];for(let j=0;j<_;j++)k.push(this.sentence());return k.join(`
|
|
128
|
-
`)}}class h1{random;locale;constructor(_,k){this.random=_,this.locale=k}genre(){if(this.locale?.music?.genre)return this.random.arrayElement(this.locale.music.genre);let _=["Rock","Pop","Jazz","Blues","Classical","Hip Hop","R&B","Country","Electronic","Dance","Metal","Punk","Reggae","Soul","Funk","Disco","House","Techno","Dubstep","Indie","Alternative","Folk","Gospel","Latin","K-Pop","EDM","Trap","Lo-Fi","Ambient","Ska"];return this.random.arrayElement(_)}songName(){if(this.locale?.music?.song)return this.random.arrayElement(this.locale.music.song);let _=["Dancing in the Moonlight","Bohemian Rhapsody","Stairway to Heaven","Hotel California","Imagine","Yesterday","Hey Jude","Sweet Child O' Mine","Smells Like Teen Spirit","Billie Jean","Thriller","Purple Rain","Born to Run","Like a Rolling Stone","What's Going On","Respect","Good Vibrations","Johnny B. Goode","I Want to Hold Your Hand","Satisfaction","My Generation","Brown Sugar","Layla","Crossroads","The End","Light My Fire","All Along the Watchtower","While My Guitar Gently Weeps","A Day in the Life"];return this.random.arrayElement(_)}albumName(){let _=["Abbey Road","The Dark Side of the Moon","Thriller","Back in Black","The Wall","Rumours","Nevermind","Led Zeppelin IV","Born in the U.S.A.","Sgt. Pepper's Lonely Hearts Club Band","OK Computer","The Beatles (White Album)","Purple Rain","Hotel California","21","Appetite for Destruction","Lemonade","To Pimp a Butterfly","Random Access Memories"];return this.random.arrayElement(_)}artist(){if(this.locale?.music?.artist)return this.random.arrayElement(this.locale.music.artist);let _=["The Beatles","Led Zeppelin","Pink Floyd","Queen","The Rolling Stones","Elvis Presley","Michael Jackson","Madonna","David Bowie","Nirvana","Radiohead","U2","AC/DC","Metallica","Bob Dylan","Jimi Hendrix","Prince","Stevie Wonder","Aretha Franklin","The Who","The Doors","Fleetwood Mac","Eagles","Guns N' Roses","Red Hot Chili Peppers","Coldplay","Beyonc\xE9","Taylor Swift","Drake","Kendrick Lamar","Adele","Ed Sheeran"];return this.random.arrayElement(_)}instrument(){if(this.locale?.music?.instrument)return this.random.arrayElement(this.locale.music.instrument);let _=["Guitar","Piano","Drums","Bass","Violin","Saxophone","Trumpet","Flute","Clarinet","Cello","Harp","Keyboard","Harmonica","Accordion","Ukulele","Banjo","Mandolin","Trombone","French Horn","Tuba","Oboe","Bassoon","Xylophone","Marimba","Tambourine","Synthesizer","Didgeridoo","Sitar","Tabla","Djembe"];return this.random.arrayElement(_)}note(){let _=["C","C#","D","D#","E","F","F#","G","G#","A","A#","B"];return this.random.arrayElement(_)}chord(){let _=this.note(),k=this.random.arrayElement(["maj","min","maj7","min7","7","dim","aug","sus4","sus2"]);return`${_}${k}`}tempo(){return this.random.int(60,200)}key(){let _=this.note(),k=this.random.arrayElement(["Major","Minor"]);return`${_} ${k}`}timeSignature(){let _=["4/4","3/4","6/8","5/4","7/8","2/4","9/8","12/8"];return this.random.arrayElement(_)}}class O0{random;constructor(_){this.random=_}int(_){let k=_?.min??0,j=_?.max??100;return this.random.int(k,j)}float(_){let k=_?.min??0,j=_?.max??1,d=_?.precision??2;return this.random.float(k,j,d)}bigInt(_){let k=_?.min??0n,j=(_?.max??1000000n)-k+1n,d=BigInt(Math.floor(this.random.number()*Number(j)));return k+d}binary(_){let k=_?.length??8,j="";for(let d=0;d<k;d++)j+=this.random.int(0,1);return j}octal(_){let k=_?.length??3,j="";for(let d=0;d<k;d++)j+=this.random.int(0,7);return j}hex(_){let k=_?.length??6,j="0123456789ABCDEF",d="";for(let O=0;O<k;O++)d+="0123456789ABCDEF"[this.random.int(0,15)];return d}randomNumber(_){return this.int(_)}randomDigit(){return this.int({min:0,max:9})}randomDigitNotZero(){return this.int({min:1,max:9})}}class f1{random;locale;constructor(_,k){this.random=_,this.locale=k}firstName(_){if(_?.gender==="male")return this.firstNameMale();if(_?.gender==="female")return this.firstNameFemale();if(_?.gender==="neutral")return this.firstNameNeutral();let k=this.locale.person.firstNameMale.length,j=this.locale.person.firstNameFemale.length,d=this.locale.person.firstNameNeutral?.length||0,O=k+j+d,$=this.random.int(0,O-1);if($<k)return this.locale.person.firstNameMale[$];if($<k+j)return this.locale.person.firstNameFemale[$-k];return this.locale.person.firstNameNeutral[$-k-j]}firstNameMale(){return this.random.arrayElement(this.locale.person.firstNameMale)}firstNameFemale(){return this.random.arrayElement(this.locale.person.firstNameFemale)}firstNameNeutral(){if(!this.locale.person.firstNameNeutral||this.locale.person.firstNameNeutral.length===0){let _=[...this.locale.person.firstNameMale,...this.locale.person.firstNameFemale];return this.random.arrayElement(_)}return this.random.arrayElement(this.locale.person.firstNameNeutral)}lastName(){return this.random.arrayElement(this.locale.person.lastName)}fullName(_){if(!_)return`${this.firstName()} ${this.lastName()}`;let k=this.firstName({gender:_.gender}),j=this.lastName();if(_.prefix&&_.suffix)return`${this.prefix()} ${k} ${j} ${this.suffix()}`;if(_.prefix)return`${this.prefix()} ${k} ${j}`;if(_.suffix)return`${k} ${j} ${this.suffix()}`;return`${k} ${j}`}prefix(){return this.random.arrayElement(this.locale.person.prefix)}suffix(){return this.random.arrayElement(this.locale.person.suffix)}gender(){return this.random.arrayElement(this.locale.person.gender)}jobTitle(){return this.random.arrayElement(this.locale.person.jobTitle)}name(){return this.fullName()}firstNameAdvanced(_){let k;if(_?.constraints)k=this.firstName({gender:_.constraints.gender});else k=this.firstName({gender:_?.gender});if(_?.weighted)k=l1(this.random,_.weighted);if(_?.relationships)k=tk({firstName:k,gender:_?.gender||_?.constraints?.gender},_.relationships).firstName||k;if(_?.validation){let j=u1(k,_.validation);if(!j.isValid){if(_.validation.strict)throw Error(`Validation failed: ${j.errors.join(", ")}`);k=this.firstName({gender:_?.gender||_?.constraints?.gender})}}return k}fullNameAdvanced(_){let k;if(_?.constraints)k=this.fullName({gender:_.constraints.gender,prefix:_.prefix,suffix:_.suffix});else k=this.fullName(_);if(_?.weighted)k=l1(this.random,_.weighted);if(_?.relationships)k=tk({fullName:k,gender:_?.gender||_?.constraints?.gender},_.relationships).fullName||k;if(_?.validation){let j=u1(k,_.validation);if(!j.isValid){if(_.validation.strict)throw Error(`Validation failed: ${j.errors.join(", ")}`);k=this.fullName({gender:_?.gender||_?.constraints?.gender,prefix:_?.prefix,suffix:_?.suffix})}}return k}profile(_){let k=_?.constraints?.gender||_?.gender||this.gender(),j=this.firstNameAdvanced({..._,gender:k}),d=this.lastName(),O=`${j} ${d}`,$={firstName:j,lastName:d,fullName:O,gender:k,jobTitle:this.jobTitle(),age:_?.constraints?.ageRange?this.random.int(_.constraints.ageRange.min,_.constraints.ageRange.max):this.random.int(18,80)};if(_?.relationships)return tk($,_.relationships);return $}family(_){let k=_?.size||this.random.int(2,6),j=this.lastName(),d=["parent","parent","child","child","child","grandparent"],O=[];for(let $=0;$<k;$++){let Z=d[$]||"relative",X=Z==="parent"||Z==="grandparent"?this.random.weightedBoolean(0.6)?"male":"female":this.random.boolean()?"male":"female",E=this.firstNameAdvanced({..._,gender:X,constraints:{..._?.constraints,gender:X}});O.push({firstName:E,lastName:j,fullName:`${E} ${j}`,gender:X,relationship:Z})}return{members:O,lastName:j}}}class q1{random;locale;constructor(_,k){this.random=_,this.locale=k}number(_){let k=_??this.random.arrayElement(this.locale.phone.formats??["###-###-####"]);return this.random.replaceSymbols(k)}phoneNumber(_){return this.number(_)}}class H1{random;locale;constructor(_,k){this.random=_,this.locale=k}chemicalElement(){if(this.locale?.science?.chemicalElement)return this.random.arrayElement(this.locale.science.chemicalElement);let _=["Hydrogen","Helium","Lithium","Beryllium","Boron","Carbon","Nitrogen","Oxygen","Fluorine","Neon","Sodium","Magnesium","Aluminum","Silicon","Phosphorus","Sulfur","Chlorine","Argon","Potassium","Calcium","Iron","Copper","Zinc","Silver","Gold","Mercury","Lead","Uranium","Platinum","Titanium"];return this.random.arrayElement(_)}chemicalElementSymbol(){let _=["H","He","Li","Be","B","C","N","O","F","Ne","Na","Mg","Al","Si","P","S","Cl","Ar","K","Ca","Fe","Cu","Zn","Ag","Au","Hg","Pb","U","Pt","Ti"];return this.random.arrayElement(_)}unit(){if(this.locale?.science?.unit)return this.random.arrayElement(this.locale.science.unit);let _=["meter","kilogram","second","ampere","kelvin","mole","candela","newton","pascal","joule","watt","coulomb","volt","ohm","farad","weber","tesla","henry","celsius","lumen","lux","becquerel","gray","sievert","katal","hertz","radian","steradian"];return this.random.arrayElement(_)}constant(){if(this.locale?.science?.constant)return this.random.arrayElement(this.locale.science.constant);let _=["Speed of Light","Gravitational Constant","Planck Constant","Boltzmann Constant","Avogadro Constant","Elementary Charge","Magnetic Constant","Electric Constant","Fine Structure Constant","Rydberg Constant","Gas Constant","Stefan-Boltzmann Constant"];return this.random.arrayElement(_)}field(){if(this.locale?.science?.field)return this.random.arrayElement(this.locale.science.field);let _=["Physics","Chemistry","Biology","Astronomy","Geology","Ecology","Genetics","Neuroscience","Quantum Mechanics","Thermodynamics","Electromagnetism","Biochemistry","Molecular Biology","Microbiology","Botany","Zoology","Meteorology","Oceanography"];return this.random.arrayElement(_)}dnaSequence(_=12){let k=["A","T","C","G"],j="";for(let d=0;d<_;d++)j+=this.random.arrayElement(k);return j}rnaSequence(_=12){let k=["A","U","C","G"],j="";for(let d=0;d<_;d++)j+=this.random.arrayElement(k);return j}hypothesis(){let _=["temperature increases","pressure decreases","concentration rises","pH changes","light intensity increases","surface area increases","catalyst is added"],k=["reaction rate increases","solubility changes","equilibrium shifts","rate decreases","yield improves","product formation accelerates","process efficiency increases"];return`If ${this.random.arrayElement(_)}, then ${this.random.arrayElement(k)}`}}class b1{random;locale;constructor(_,k){this.random=_,this.locale=k}sport(){if(this.locale?.sport?.sport)return this.random.arrayElement(this.locale.sport.sport);let _=["Football","Basketball","Baseball","Soccer","Tennis","Golf","Hockey","Boxing","Wrestling","Swimming","Track and Field","Volleyball","Cricket","Rugby","Lacrosse","Badminton","Table Tennis","Bowling","Skiing","Snowboarding","Surfing","Skateboarding","Cycling","Running","Marathon","Triathlon","Gymnastics","Fencing","Archery","Martial Arts","Karate","Judo","Taekwondo","MMA","Formula 1","NASCAR","Sailing"];return this.random.arrayElement(_)}team(){if(this.locale?.sport?.team)return this.random.arrayElement(this.locale.sport.team);let _=["Lakers","Warriors","Bulls","Celtics","Knicks","Heat","Spurs","Mavericks","Yankees","Red Sox","Dodgers","Cubs","Giants","Astros","Braves","Phillies","Patriots","49ers","Cowboys","Packers","Steelers","Eagles","Seahawks","Chiefs","Manchester United","Real Madrid","Barcelona","Liverpool","Bayern Munich","PSG","Maple Leafs","Bruins","Canadiens","Blackhawks","Penguins","Lightning"];return this.random.arrayElement(_)}athlete(){if(this.locale?.sport?.athlete)return this.random.arrayElement(this.locale.sport.athlete);let _=["Michael Jordan","LeBron James","Tom Brady","Serena Williams","Tiger Woods","Muhammad Ali","Babe Ruth","Wayne Gretzky","Pel\xE9","Cristiano Ronaldo","Lionel Messi","Roger Federer","Usain Bolt","Simone Biles","Michael Phelps","Kobe Bryant","Derek Jeter","Joe Montana","Magic Johnson","Larry Bird"];return this.random.arrayElement(_)}position(){let _=["Quarterback","Running Back","Wide Receiver","Linebacker","Defensive Back","Point Guard","Shooting Guard","Small Forward","Power Forward","Center","Pitcher","Catcher","First Base","Shortstop","Outfielder","Forward","Midfielder","Defender","Goalkeeper","Striker","Winger"];return this.random.arrayElement(_)}event(){let _=["Super Bowl","World Series","NBA Finals","Stanley Cup","FIFA World Cup","Olympics","Wimbledon","Masters Tournament","Kentucky Derby","Indianapolis 500","Tour de France","Boston Marathon","UEFA Champions League","World Cup","The Open Championship","US Open","French Open","Australian Open"];return this.random.arrayElement(_)}league(){let _=["NFL","NBA","MLB","NHL","MLS","Premier League","La Liga","Serie A","Bundesliga","Ligue 1","UEFA","FIFA","NCAA","PGA","ATP","WTA","F1","NASCAR","IndyCar"];return this.random.arrayElement(_)}quote(){let _=["Just do it!","Winners never quit and quitters never win.","Hard work beats talent when talent doesn't work hard.","The only way to prove you're a good sport is to lose.","Champions keep playing until they get it right.","It's not whether you get knocked down, it's whether you get up.","You miss 100% of the shots you don't take.","The difference between the impossible and the possible lies in determination."];return this.random.arrayElement(_)}equipment(){let _=["Ball","Bat","Glove","Helmet","Racket","Puck","Skates","Cleats","Pads","Jersey","Goggles","Swimsuit","Bicycle","Surfboard","Skateboard","Snowboard","Skis","Golf Clubs","Tennis Racket","Boxing Gloves","Mouthguard"];return this.random.arrayElement(_)}}class $0{random;constructor(_){this.random=_}uuid(){if(!this.random.isSeeded()&&typeof crypto<"u"&&crypto.randomUUID)return crypto.randomUUID();let _="0123456789abcdef",k="";for(let j=0;j<36;j++)if(j===8||j===13||j===18||j===23)k+="-";else if(j===14)k+="4";else if(j===19){let d=this.random.int(0,15);k+=_[d&3|8]}else k+=_[this.random.int(0,15)];return k}nanoid(_=21){let k="";for(let j=0;j<_;j++)k+="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_"[this.random.int(0,63)];return k}alpha(_){let k=_?.length??10,j=_?.casing??"mixed",d="abcdefghijklmnopqrstuvwxyz",O="ABCDEFGHIJKLMNOPQRSTUVWXYZ",$="";if(j==="lower")$="abcdefghijklmnopqrstuvwxyz";else if(j==="upper")$="ABCDEFGHIJKLMNOPQRSTUVWXYZ";else $="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";let Z="";for(let X=0;X<k;X++)Z+=$[this.random.int(0,$.length-1)];return Z}alphanumeric(_){let k=_?.length??10,j=_?.casing??"mixed",d="abcdefghijklmnopqrstuvwxyz",O="ABCDEFGHIJKLMNOPQRSTUVWXYZ",$="0123456789",Z="0123456789";if(j==="lower")Z+="abcdefghijklmnopqrstuvwxyz";else if(j==="upper")Z+="ABCDEFGHIJKLMNOPQRSTUVWXYZ";else Z+="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";let X="";for(let E=0;E<k;E++)X+=Z[this.random.int(0,Z.length-1)];return X}numeric(_=10){if(!this.random.isSeeded()){let j="";for(let d=0;d<_;d++)j+=Math.floor(Math.random()*10);return j}let k="";for(let j=0;j<_;j++)k+=this.random.int(0,9);return k}sample(_=10){return this.alphanumeric({length:_})}symbol(_=5){let k="";for(let j=0;j<_;j++)k+="!@#$%^&*()_+-=[]{}|;:,.<>?"[this.random.int(0,25)];return k}hexadecimal(_){let k=_?.length??6,j=_?.prefix??"",d="0123456789abcdef",O=j;for(let $=0;$<k;$++)O+="0123456789abcdef"[this.random.int(0,15)];return O}}class N1{random;locale;constructor(_,k){this.random=_,this.locale=k}fileName(_){let k;if(this.locale?.system?.fileName)k=this.locale.system.fileName;else k=["document","report","presentation","spreadsheet","image","video","audio","backup","archive","data","config","settings","log","cache","temp","index","main","app","script","style","layout","component","module"];let j=this.random.arrayElement(k),d=_?.extension??this.fileExtension();return`${j}.${d}`}fileExtension(){let _=["pdf","doc","docx","xls","xlsx","ppt","pptx","txt","csv","json","xml","jpg","jpeg","png","gif","bmp","svg","webp","ico","mp3","wav","ogg","flac","aac","m4a","mp4","avi","mov","wmv","flv","webm","mkv","zip","rar","tar","gz","7z","bz2","html","css","js","ts","jsx","tsx","vue","py","java","cpp","c","go","rs"];return this.random.arrayElement(_)}commonFileName(){let _=["README.md","package.json","tsconfig.json",".gitignore",".env","docker-compose.yml","Dockerfile","index.html","index.js","app.js","main.py","requirements.txt","Makefile","LICENSE","CHANGELOG.md","yarn.lock","package-lock.json","pom.xml"];return this.random.arrayElement(_)}mimeType(){let _=["application/json","application/xml","application/pdf","application/zip","text/html","text/css","text/javascript","text/plain","text/csv","image/jpeg","image/png","image/gif","image/svg+xml","image/webp","audio/mpeg","audio/wav","audio/ogg","audio/webm","video/mp4","video/webm","video/ogg","video/avi","application/octet-stream","multipart/form-data","application/x-www-form-urlencoded"];return this.random.arrayElement(_)}commonMimeType(){let _=["application/json","application/pdf","text/html","text/plain","text/css","image/jpeg","image/png","image/gif","audio/mpeg","video/mp4"];return this.random.arrayElement(_)}fileType(){if(this.locale?.system?.fileType)return this.random.arrayElement(this.locale.system.fileType);let _=["audio","image","text","video","application","document","spreadsheet","presentation","archive","code","data","font","executable"];return this.random.arrayElement(_)}directoryPath(){let _=["/usr/local/bin","/usr/bin","/etc","/var/log","/tmp","/home","/root","/opt","/srv","/mnt","/media","/dev","/proc","/sys","C:\\Program Files","C:\\Users","C:\\Windows","C:\\Temp","/Applications","/Library","/System","/Users","/Documents","/Downloads"];return this.random.arrayElement(_)}filePath(){return`${this.directoryPath()}/${this.fileName()}`}semver(){let _=this.random.int(0,10),k=this.random.int(0,20),j=this.random.int(0,50);return`${_}.${k}.${j}`}networkInterface(){let _=["eth0","eth1","wlan0","wlan1","lo","docker0","veth0","br0","tun0","tap0","enp0s3","ens33","wlp2s0","en0","en1","wlan0","WiFi","Ethernet"];return this.random.arrayElement(_)}cron(){let _=this.random.boolean(0.5)?"*":this.random.int(0,59),k=this.random.boolean(0.5)?"*":this.random.int(0,23),j=this.random.boolean(0.5)?"*":this.random.int(1,31),d=this.random.boolean(0.5)?"*":this.random.int(1,12),O=this.random.boolean(0.5)?"*":this.random.int(0,6);return`${_} ${k} ${j} ${d} ${O}`}}class x1{random;locale;constructor(_,k){this.random=_,this.locale=k}manufacturer(){if(this.locale?.vehicle?.manufacturer)return this.random.arrayElement(this.locale.vehicle.manufacturer);return this.random.arrayElement(z6)}model(){if(this.locale?.vehicle?.model)return this.random.arrayElement(this.locale.vehicle.model);return this.random.arrayElement(S6)}type(){if(this.locale?.vehicle?.type)return this.random.arrayElement(this.locale.vehicle.type);return this.random.arrayElement(Y6)}fuel(){if(this.locale?.vehicle?.fuel)return this.random.arrayElement(this.locale.vehicle.fuel);return this.random.arrayElement(L6)}color(){if(this.locale?.commerce?.color)return this.random.arrayElement(this.locale.commerce.color);return this.random.arrayElement(P6)}vin(){let _="";for(let k=0;k<17;k++)_+="ABCDEFGHJKLMNPRSTUVWXYZ0123456789"[this.random.int(0,32)];return _}registration(){let _=["???-####","###-???","??? ###","##?-###","???-###"];return this.random.arrayElement(_).replace(/\?/g,()=>this.random.arrayElement("ABCDEFGHIJKLMNOPQRSTUVWXYZ".split(""))).replace(/#/g,()=>String(this.random.int(0,9)))}vehicle(){let _=this.random.int(2000,2024),k=this.manufacturer(),j=this.model();return`${_} ${k} ${j}`}bicycle(){if(this.locale?.vehicle?.bicycle)return this.random.arrayElement(this.locale.vehicle.bicycle);let _=["Mountain Bike","Road Bike","BMX","Cruiser","Hybrid","Electric Bike","Folding Bike","Touring Bike","Cyclocross","Gravel Bike","Track Bike","Recumbent"];return this.random.arrayElement(_)}}class i1{random;locale;constructor(_,k){this.random=_,this.locale=k}adjective(){if(this.locale?.word?.adjective)return this.random.arrayElement(this.locale.word.adjective);let _=["beautiful","happy","sad","quick","slow","big","small","tall","short","long","wide","narrow","thick","thin","heavy","light","hard","soft","hot","cold","warm","cool","bright","dark","loud","quiet","strong","weak","clean","dirty","new","old","young","fresh","dry","wet","smooth","rough","sharp","dull","simple","complex","easy","difficult","good","bad","right","wrong","true","false"];return this.random.arrayElement(_)}adverb(){if(this.locale?.word?.adverb)return this.random.arrayElement(this.locale.word.adverb);let _=["quickly","slowly","carefully","easily","hardly","loudly","quietly","suddenly","finally","really","very","completely","absolutely","perfectly","badly","well","almost","always","never","often","rarely","sometimes","usually","frequently","occasionally","immediately","instantly","eventually","probably","possibly"];return this.random.arrayElement(_)}conjunction(){if(this.locale?.word?.conjunction)return this.random.arrayElement(this.locale.word.conjunction);let _=["and","but","or","nor","for","yet","so","although","because","since","unless","while","where","if","than","when","after","before","until"];return this.random.arrayElement(_)}interjection(){if(this.locale?.word?.interjection)return this.random.arrayElement(this.locale.word.interjection);let _=["wow","oh","ah","hey","oops","ouch","yay","hooray","alas","bravo","hello","goodbye","yes","no","well","hmm","uh","er","um"];return this.random.arrayElement(_)}noun(){if(this.locale?.word?.noun)return this.random.arrayElement(this.locale.word.noun);let _=["table","chair","book","pen","computer","phone","door","window","car","house","tree","flower","dog","cat","bird","fish","water","air","fire","earth","mountain","river","ocean","sky","sun","moon","star","cloud","rain","snow","person","man","woman","child","friend","family","food","music","art","book","school","work","time","day","night","morning","evening","world","life","love"];return this.random.arrayElement(_)}preposition(){if(this.locale?.word?.preposition)return this.random.arrayElement(this.locale.word.preposition);let _=["in","on","at","by","for","with","from","to","of","about","under","over","above","below","between","through","during","before","after","against","among","into","onto","upon","within","without","toward","near","beside","behind"];return this.random.arrayElement(_)}verb(){if(this.locale?.word?.verb)return this.random.arrayElement(this.locale.word.verb);let _=["run","walk","jump","swim","fly","eat","drink","sleep","work","play","read","write","speak","listen","watch","look","see","hear","think","know","want","like","love","hate","need","make","take","give","get","put","come","go","say","tell","ask","answer","help","start","stop","begin","end","open","close","show","hide","find","lose","buy","sell","learn"];return this.random.arrayElement(_)}sample(){let _=["adjective","adverb","conjunction","interjection","noun","preposition","verb"],k=this.random.arrayElement(_);return this[k]()}words(_=3){let k=[];for(let j=0;j<_;j++)k.push(this.sample());return k.join(" ")}}class Z0{seed;constructor(_){this.seed=_}isSeeded(){return this.seed!==void 0}number(){if(this.seed!==void 0)return this.seed=(this.seed*9301+49297)%233280,this.seed/233280;return Math.random()}int(_=0,k=100){return Math.floor(this.number()*(k-_+1))+_}float(_=0,k=1,j=2){let d=this.number()*(k-_)+_;return Number.parseFloat(d.toFixed(j))}arrayElement(_){if(_.length===0)throw Error("Cannot pick from empty array");if(this.seed===void 0)return _[Math.floor(Math.random()*_.length)];return _[this.int(0,_.length-1)]}arrayElements(_,k){if(_.length===0)return[];let j=k??this.int(1,_.length);return[..._].sort(()=>this.number()-0.5).slice(0,Math.min(j,_.length))}shuffle(_){let k=[..._];for(let j=k.length-1;j>0;j--){let d=this.int(0,j);[k[j],k[d]]=[k[d],k[j]]}return k}boolean(_=0.5){return this.number()<_}replaceSymbols(_){if(this.seed===void 0){let k="";for(let j=0;j<_.length;j++){let d=_[j];if(d==="#")k+="0123456789"[Math.floor(Math.random()*10)];else if(d==="?")k+=R8[Math.floor(Math.random()*26)];else k+=d}return k}return _.replace(/[#?]/g,(k)=>{if(k==="#")return String(this.int(0,9));return this.arrayElement(R8)})}replaceCreditCardSymbols(_="####-####-####-####",k="#"){return _.replace(new RegExp(k,"g"),()=>String(this.int(0,9)))}weightedArrayElement(_){if(_.length===0)throw Error("Cannot pick from empty weighted items array");let k=_.reduce((O,$)=>O+$.weight,0);if(k<=0)throw Error("Total weight must be greater than 0");let j=this.number()*k,d=0;for(let O of _)if(d+=O.weight,j<=d)return O.item;return _[_.length-1].item}weightedArrayElements(_,k,j=!1){if(_.length===0)return[];let d=k??this.int(1,_.length),O=[],$=[..._];for(let Z=0;Z<d&&$.length>0;Z++){let X=this.weightedArrayElement($);if(O.push(X),!j){let E=$.findIndex((F)=>F.item===X);if(E!==-1)$.splice(E,1)}}return O}weightedBoolean(_=0.5){return this.number()<_}weightedInt(_,k,j){let d=k-_+1;if(j){if(j.length!==d)throw Error("Weights array length must match the range size");let O=j.map(($,Z)=>({item:_+Z,weight:$}));return this.weightedArrayElement(O)}return this.int(_,k)}}class U0{random;_locale;_autoInstallLocales;person;address;internet;phone;company;lorem;date;number;string;color;finance;helpers;vehicle;image;git;science;music;database;food;commerce;book;animal;sport;hacker;system;word;constructor(_){let k=_?.locale??"en",j=_?.seed;if(this._autoInstallLocales=_?.autoInstallLocales??!1,k!=="en"&&!_k.isCached(k))console.warn(`[ts-mocker] Locale '${k}' requires async loading. Use 'await Faker.create({ locale: "${k}" })' for better performance. Falling back to English.`),this._locale=_k.loadSync("en");else this._locale=_k.loadSync(k);this.random=new Z0(j),this.person=new f1(this.random,this._locale),this.address=new K1(this.random,this._locale),this.internet=new C1(this.random,this._locale),this.phone=new q1(this.random,this._locale),this.company=new R1(this.random,this._locale),this.lorem=new d0(this.random),this.date=new aO(this.random),this.number=new O0(this.random),this.string=new $0(this.random),this.color=new I1(this.random,this._locale),this.finance=new eO(this.random),this.helpers=new k0(this.random),this.image=new j0(this.random),this.git=new _0(this.random),this.science=new H1(this.random,this._locale),this.music=new h1(this.random,this._locale),this.database=new tO(this.random),this.food=new w1(this.random,this._locale),this.commerce=new D1(this.random,this._locale),this.book=new J1(this.random,this._locale),this.animal=new n1(this.random,this._locale),this.sport=new b1(this.random,this._locale),this.hacker=new M1(this.random,this._locale),this.system=new N1(this.random,this._locale),this.word=new i1(this.random,this._locale),this.vehicle=new x1(this.random,this._locale)}static async create(_){let k=_?.locale??"en";return await _k.load(k),new U0(_)}seed(_){return this.random=new Z0(_),Object.assign(this.person,new f1(this.random,this._locale)),Object.assign(this.address,new K1(this.random,this._locale)),Object.assign(this.internet,new C1(this.random,this._locale)),Object.assign(this.phone,new q1(this.random,this._locale)),Object.assign(this.company,new R1(this.random,this._locale)),Object.assign(this.lorem,new d0(this.random)),Object.assign(this.date,new aO(this.random)),Object.assign(this.number,new O0(this.random)),Object.assign(this.string,new $0(this.random)),Object.assign(this.color,new I1(this.random,this._locale)),Object.assign(this.finance,new eO(this.random)),Object.assign(this.helpers,new k0(this.random)),Object.assign(this.image,new j0(this.random)),Object.assign(this.git,new _0(this.random)),Object.assign(this.science,new H1(this.random,this._locale)),Object.assign(this.music,new h1(this.random,this._locale)),Object.assign(this.database,new tO(this.random)),Object.assign(this.food,new w1(this.random,this._locale)),Object.assign(this.commerce,new D1(this.random,this._locale)),Object.assign(this.book,new J1(this.random,this._locale)),Object.assign(this.animal,new n1(this.random,this._locale)),Object.assign(this.sport,new b1(this.random,this._locale)),Object.assign(this.hacker,new M1(this.random,this._locale)),Object.assign(this.system,new N1(this.random,this._locale)),Object.assign(this.word,new i1(this.random,this._locale)),Object.assign(this.vehicle,new x1(this.random,this._locale)),this}async setLocale(_){return this._locale=await _k.load(_),this.reinitializeLocaleModules(),this}setLocaleSync(_){if(!_k.isCached(_)&&_!=="en")return console.warn(`[ts-mocker] Locale '${_}' is not loaded. Use 'await faker.setLocale("${_}")' or preload it first.`),this;return this._locale=_k.loadSync(_),this.reinitializeLocaleModules(),this}async preloadLocales(_){return await _k.preload(_),this}reinitializeLocaleModules(){Object.assign(this.person,new f1(this.random,this._locale)),Object.assign(this.address,new K1(this.random,this._locale)),Object.assign(this.internet,new C1(this.random,this._locale)),Object.assign(this.phone,new q1(this.random,this._locale)),Object.assign(this.company,new R1(this.random,this._locale)),Object.assign(this.food,new w1(this.random,this._locale)),Object.assign(this.animal,new n1(this.random,this._locale)),Object.assign(this.sport,new b1(this.random,this._locale)),Object.assign(this.music,new h1(this.random,this._locale)),Object.assign(this.commerce,new D1(this.random,this._locale)),Object.assign(this.book,new J1(this.random,this._locale)),Object.assign(this.vehicle,new x1(this.random,this._locale)),Object.assign(this.word,new i1(this.random,this._locale)),Object.assign(this.hacker,new M1(this.random,this._locale)),Object.assign(this.system,new N1(this.random,this._locale)),Object.assign(this.color,new I1(this.random,this._locale)),Object.assign(this.science,new H1(this.random,this._locale))}get locale(){return this._locale.title}static get availableLocales(){return _k.getAvailableLocales()}static isLocaleLoaded(_){return _k.isCached(_)}static async preloadLocales(_){await _k.preload(_)}name(){return this.person.name()}email(){return this.internet.email()}}var p1,Q0,FU,zU,w5,IO,n8,A_,V_,SU,M5,YU,C5,LU,PU,d8,UU,h5,f5,O8,QU,VU,TU,WU,DO,j6,KU,g_,nU,JU,q5,RO,J8,b_,G_,IU,H5,DU,b5,RU,wU,$8,MU,N5,x5,CU,Z8,hU,fU,qU,HU,bU,wO,d6,NU,Lk,i5,X0,B5,c5,I8,y5,v5,E0,A5,m5,Gj,O6,Vk,MO,xU,iU,G0,X8=null,D8,L1,$k,xj,_k,$6,Z6,X6,E6,G6,F6,z6,S6,Y6,L6,P6,R8,w8,U6,BU=r(async()=>{p1=new mZ,Q0=new gZ,FU=lO(W8.cwd(),"config"),zU=lO(W8.cwd(),"src/generated"),w5=uO.env.CLARITY_LOG_DIR||KP(gP(),"logs"),IO={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:w5,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},n8=await uP(),A_={red:(_)=>`\x1B[31m${_}\x1B[0m`,green:(_)=>`\x1B[32m${_}\x1B[0m`,yellow:(_)=>`\x1B[33m${_}\x1B[0m`,blue:(_)=>`\x1B[34m${_}\x1B[0m`,magenta:(_)=>`\x1B[35m${_}\x1B[0m`,cyan:(_)=>`\x1B[36m${_}\x1B[0m`,white:(_)=>`\x1B[37m${_}\x1B[0m`,gray:(_)=>`\x1B[90m${_}\x1B[0m`,bgRed:(_)=>`\x1B[41m${_}\x1B[0m`,bgYellow:(_)=>`\x1B[43m${_}\x1B[0m`,bold:(_)=>`\x1B[1m${_}\x1B[0m`,dim:(_)=>`\x1B[2m${_}\x1B[0m`,italic:(_)=>`\x1B[3m${_}\x1B[0m`,underline:(_)=>`\x1B[4m${_}\x1B[0m`,reset:"\x1B[0m"},V_=A_,SU=A_.red,M5=A_.green,YU=A_.yellow,C5=A_.blue,LU=A_.magenta,PU=A_.cyan,d8=A_.white,UU=A_.gray,h5=A_.bgRed,f5=A_.bgYellow,O8=A_.bold,QU=A_.dim,VU=A_.italic,TU=A_.underline,WU=A_.reset,DO={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},j6={debug:"\uD83D\uDD0D",info:C5("\u2139"),success:M5("\u2713"),warning:f5(d8(O8(" WARN "))),error:h5(d8(O8(" ERROR ")))},KU=new sO("stacks"),g_=new sO("bunfig",{showTags:!0}),nU=o_(g1.cwd(),"config"),JU=o_(g1.cwd(),"src/generated"),q5=gO.env.CLARITY_LOG_DIR||TP(oP(),"logs"),RO={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:q5,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},J8=await rP(),b_={red:(_)=>`\x1B[31m${_}\x1B[0m`,green:(_)=>`\x1B[32m${_}\x1B[0m`,yellow:(_)=>`\x1B[33m${_}\x1B[0m`,blue:(_)=>`\x1B[34m${_}\x1B[0m`,magenta:(_)=>`\x1B[35m${_}\x1B[0m`,cyan:(_)=>`\x1B[36m${_}\x1B[0m`,white:(_)=>`\x1B[37m${_}\x1B[0m`,gray:(_)=>`\x1B[90m${_}\x1B[0m`,bgRed:(_)=>`\x1B[41m${_}\x1B[0m`,bgYellow:(_)=>`\x1B[43m${_}\x1B[0m`,bgGray:(_)=>`\x1B[100m${_}\x1B[0m`,bold:(_)=>`\x1B[1m${_}\x1B[0m`,dim:(_)=>`\x1B[2m${_}\x1B[0m`,italic:(_)=>`\x1B[3m${_}\x1B[0m`,underline:(_)=>`\x1B[4m${_}\x1B[0m`,strikethrough:(_)=>`\x1B[9m${_}\x1B[0m`,reset:"\x1B[0m"},G_=b_,IU=b_.red,H5=b_.green,DU=b_.yellow,b5=b_.blue,RU=b_.magenta,wU=b_.cyan,$8=b_.white,MU=b_.gray,N5=b_.bgRed,x5=b_.bgYellow,CU=b_.bgGray,Z8=b_.bold,hU=b_.dim,fU=b_.italic,qU=b_.underline,HU=b_.strikethrough,bU=b_.reset,wO={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},d6={debug:"\uD83D\uDD0D",info:b5("\u2139"),success:H5("\u2713"),warning:x5($8(Z8(" WARN "))),error:N5($8(Z8(" ERROR ")))},NU=new rO("stacks"),Lk=class extends Error{timestamp;context;constructor(k,j={}){super(k);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=j,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,timestamp:this.timestamp.toISOString(),context:this.context,stack:this.stack}}toString(){let k=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([j,d])=>`${j}: ${d}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${k}`}},i5=class extends Lk{code="CONFIG_NOT_FOUND";constructor(k,j,d){let O=d?` or alias "${d}"`:"";super(`Configuration "${k}"${O} not found`,{configName:k,alias:d,searchPaths:j,searchPathCount:j.length})}},X0=class extends Lk{code="CONFIG_LOAD_ERROR";constructor(k,j,d){super(`Failed to load configuration from "${k}": ${j.message}`,{configPath:k,configName:d,originalError:j.name,originalMessage:j.message});this.cause=j}},B5=class extends Lk{code="CONFIG_VALIDATION_ERROR";constructor(k,j,d){super(`Configuration validation failed for "${k}"`,{configPath:k,configName:d,validationErrors:j,errorCount:j.length})}},c5=class extends Lk{code="CONFIG_MERGE_ERROR";constructor(k,j,d,O){super(`Failed to merge configuration from "${k}" with "${j}": ${d.message}`,{sourcePath:k,targetPath:j,configName:O,originalError:d.name,originalMessage:d.message});this.cause=d}},I8=class extends Lk{code="ENV_VAR_ERROR";constructor(k,j,d,O){super(`Failed to parse environment variable "${k}" with value "${j}" as ${d}`,{envKey:k,envValue:j,expectedType:d,configName:O})}},y5=class extends Lk{code="FILE_SYSTEM_ERROR";constructor(k,j,d){super(`File system ${k} failed for "${j}": ${d.message}`,{operation:k,path:j,originalError:d.name,originalMessage:d.message});this.cause=d}},v5=class extends Lk{code="TYPE_GENERATION_ERROR";constructor(k,j,d){super(`Failed to generate types from "${k}" to "${j}": ${d.message}`,{configDir:k,outputPath:j,originalError:d.name,originalMessage:d.message});this.cause=d}},E0=class extends Lk{code="SCHEMA_VALIDATION_ERROR";constructor(k,j,d){super(`Schema validation failed${d?` for config "${d}"`:""}`,{schemaPath:k,configName:d,validationErrors:j,errorCount:j.length})}},A5=class extends Lk{code="BROWSER_CONFIG_ERROR";constructor(k,j,d,O){super(`Failed to fetch configuration from "${k}": ${j} ${d}`,{endpoint:k,status:j,statusText:d,configName:O})}},m5=class extends Lk{code="PLUGIN_ERROR";constructor(k,j,d){super(`Plugin "${k}" failed during ${j}: ${d.message}`,{pluginName:k,operation:j,originalError:d.name,originalMessage:d.message});this.cause=d}},Gj={configNotFound(_,k,j){return new i5(_,k,j)},configLoad(_,k,j){return new X0(_,k,j)},configValidation(_,k,j){return new B5(_,k,j)},configMerge(_,k,j,d){return new c5(_,k,j,d)},envVar(_,k,j,d){return new I8(_,k,j,d)},fileSystem(_,k,j){return new y5(_,k,j)},typeGeneration(_,k,j){return new v5(_,k,j)},schemaValidation(_,k,j){return new E0(_,k,j)},browserConfig(_,k,j,d){return new A5(_,k,j,d)},plugin(_,k,j){return new m5(_,k,j)}},O6=/^https?:\/\//,Vk=new rO("bunfig",{showTags:!0}),MO=new aZ,xU=Xk(mO.cwd(),"config"),iU=Xk(mO.cwd(),"src/generated"),G0={verbose:!1,locale:"en",autoInstallLocales:!1},D8=G0,L1={title:"English",person:{firstNameMale:["James","John","Robert","Michael","William","David","Richard","Joseph","Thomas","Charles","Christopher","Daniel","Matthew","Anthony","Mark","Donald","Steven","Paul","Andrew","Joshua","Kenneth","Kevin","Brian","George","Timothy","Ronald","Edward","Jason","Jeffrey","Ryan","Jacob","Gary","Nicholas","Eric","Jonathan","Stephen","Larry","Justin","Scott","Brandon","Benjamin","Samuel","Raymond","Gregory","Frank","Alexander","Patrick","Jack","Dennis","Jerry","Liam","Noah","Oliver","Elijah","Lucas","Mason","Logan","Ethan","Henry","Jackson","Sebastian","Aiden","Carter","Owen","Wyatt","Luke","Jayden","Dylan","Grayson","Levi","Isaac","Gabriel","Julian","Mateo","Jaxon","Lincoln"],firstNameFemale:["Mary","Patricia","Jennifer","Linda","Elizabeth","Barbara","Susan","Jessica","Sarah","Karen","Lisa","Nancy","Betty","Margaret","Sandra","Ashley","Kimberly","Emily","Donna","Michelle","Dorothy","Carol","Amanda","Melissa","Deborah","Stephanie","Rebecca","Sharon","Laura","Cynthia","Kathleen","Amy","Angela","Shirley","Anna","Brenda","Pamela","Emma","Nicole","Helen","Olivia","Ava","Isabella","Sophia","Mia","Charlotte","Amelia","Harper","Evelyn","Abigail","Sofia","Ella","Scarlett","Grace","Chloe","Victoria","Aria","Lily","Aubrey","Zoey","Penelope","Lillian","Addison","Layla","Natalie","Camila"],firstNameNeutral:["Taylor","Jordan","Alex","Riley","Casey","Morgan","Avery","Quinn","Blake","Cameron","Sage","River","Phoenix","Rowan","Skyler","Charlie","Finley","Peyton","Reese","Kai"],lastName:["Smith","Johnson","Williams","Brown","Jones","Garcia","Miller","Davis","Rodriguez","Martinez","Hernandez","Lopez","Gonzalez","Wilson","Anderson","Thomas","Taylor","Moore","Jackson","Martin","Lee","Perez","Thompson","White","Harris","Sanchez","Clark","Ramirez","Lewis","Robinson","Walker","Young","Allen","King","Wright","Scott","Torres","Nguyen","Hill","Flores","Green","Adams","Nelson","Baker","Hall","Rivera","Campbell","Mitchell","Carter","Roberts","Gomez","Phillips","Evans","Turner","Diaz","Parker","Cruz","Edwards","Collins","Reyes","Stewart","Morris","Morales","Murphy","Cook","Rogers","Gutierrez","Ortiz","Morgan","Cooper","Peterson","Bailey","Reed","Kelly","Howard","Ramos","Kim","Cox","Ward","Richardson","Watson","Brooks","Chavez","Wood","James","Bennett","Gray","Mendoza","Ruiz","Hughes","Price","Alvarez","Castillo","Sanders","Patel","Myers","Long","Ross","Foster","Jimenez"],prefix:["Mr.","Mrs.","Ms.","Miss","Dr.","Prof."],suffix:["Jr.","Sr.","I","II","III","IV","V","MD","PhD","DDS"],gender:["Male","Female","Non-binary","Agender","Bigender","Genderfluid","Genderqueer"],jobTitle:["Software Engineer","Product Manager","Designer","Data Scientist","DevOps Engineer","Marketing Manager","Sales Representative","Accountant","Human Resources Manager","CEO","CTO","CFO","COO","Director","Manager","Analyst","Consultant","Administrator","Coordinator","Specialist","Developer","Architect","Engineer","Technician","Assistant","Project Manager","Business Analyst","Quality Assurance Engineer","UX Designer","UI Designer","Backend Developer","Frontend Developer","Full Stack Developer","Mobile Developer","Cloud Architect","Security Engineer","Network Engineer","Database Administrator","Systems Administrator","Technical Writer","Scrum Master","Product Owner","Release Manager","Content Manager","Social Media Manager","SEO Specialist","Digital Marketing Specialist","Growth Hacker","Brand Manager","Creative Director","Financial Analyst","Investment Banker","Risk Analyst","Compliance Officer","Tax Consultant","Legal Counsel","Paralegal","Executive Assistant","Operations Manager","Supply Chain Manager","Logistics Coordinator","Customer Success Manager","Account Executive","Sales Engineer","Technical Support"]},address:{street:["Main","Oak","Maple","Cedar","Elm","Washington","Lake","Hill","Park","River","Sunset","Pine","Walnut","Highland","Madison","Lincoln","Jackson","Franklin"],city:["New York","Los Angeles","Chicago","Playa Vista","Houston","Phoenix","Philadelphia","San Antonio","San Diego","Dallas","San Jose","Austin","Jacksonville","Fort Worth","Columbus","Charlotte","San Francisco","Indianapolis","Seattle","Denver","Boston","Nashville","Detroit","Memphis","Portland","Oklahoma City","Las Vegas","Louisville","Baltimore","Milwaukee","Albuquerque","Tucson","Fresno","Sacramento","Mesa","Kansas City","Atlanta","Long Beach","Colorado Springs","Raleigh","Miami","Virginia Beach","Omaha","Oakland","Minneapolis","Tulsa","Arlington","Tampa","New Orleans","Wichita","Cleveland","Bakersfield","Aurora","Anaheim","Honolulu","Santa Ana","Riverside","Corpus Christi","Lexington","Stockton","Henderson","Saint Paul","Cincinnati","Pittsburgh","Greensboro","Anchorage","Plano","Lincoln","Orlando","Irvine","Newark","Durham","Chula Vista","Toledo","Fort Wayne","St. Petersburg","Laredo","Jersey City"],state:["Alabama","Alaska","Arizona","Arkansas","California","Colorado","Connecticut","Delaware","Florida","Georgia","Hawaii","Idaho","Illinois","Indiana","Iowa","Kansas","Kentucky","Louisiana","Maine","Maryland","Massachusetts","Michigan","Minnesota","Mississippi","Missouri","Montana","Nebraska","Nevada","New Hampshire","New Jersey","New Mexico","New York","North Carolina","North Dakota","Ohio","Oklahoma","Oregon","Pennsylvania","Rhode Island","South Carolina","South Dakota","Tennessee","Texas","Utah","Vermont","Virginia","Washington","West Virginia","Wisconsin","Wyoming"],stateAbbr:["AL","AK","AZ","AR","CA","CO","CT","DE","FL","GA","HI","ID","IL","IN","IA","KS","KY","LA","ME","MD","MA","MI","MN","MS","MO","MT","NE","NV","NH","NJ","NM","NY","NC","ND","OH","OK","OR","PA","RI","SC","SD","TN","TX","UT","VT","VA","WA","WV","WI","WY"],country:["United States","Canada","United Kingdom","Australia","Germany","France","Spain","Italy","Japan","China","India","Brazil","Mexico","Russia","South Korea"],countryCode:["US","CA","GB","AU","DE","FR","ES","IT","JP","CN","IN","BR","MX","RU","KR"],zipCode:["#####","#####-####"],buildingNumber:["###","####","#","##"],direction:["North","East","South","West","Northeast","Northwest","Southeast","Southwest"],streetSuffix:["Street","Avenue","Road","Boulevard","Drive","Court","Circle","Lane","Way","Place","Terrace","Parkway","Commons","Trail","Square","Run","Crossing"]},company:{name:["TechCorp","GlobalSoft","DataSystems","CloudNet","Innovate Inc","Digital Solutions","NextGen Tech","FutureTech","SmartSystems","CoreTech","PrimeSoft","AlphaTech"],suffix:["Inc","LLC","Corp","Group","Ltd","Co","Technologies","Solutions","Systems"],industry:["Technology","Finance","Healthcare","Education","Retail","Manufacturing","Telecommunications","Energy","Real Estate","Transportation","Media","Hospitality"],buzzwords:["synergize","leverage","innovate","disrupt","optimize","streamline","transform","revolutionize","empower","enable","facilitate","orchestrate","integrate"],adjective:["revolutionary","cutting-edge","innovative","next-generation","advanced","leading","premier","world-class","enterprise","scalable","robust","seamless"],descriptor:["global","digital","cloud-based","AI-powered","data-driven","user-centric","agile","secure","efficient","intelligent","automated","integrated"],noun:["solution","platform","system","service","technology","framework","infrastructure","application","network","portal","ecosystem","architecture","engine"]},internet:{domainSuffix:["com","net","org","io","co","app","dev","tech","ai","cloud"],freeEmail:["gmail.com","yahoo.com","hotmail.com","outlook.com","icloud.com","proton.me"]},phone:{formats:["###-###-####","(###) ###-####","1-###-###-####","+1-###-###-####","###.###.####"]},food:{dish:["Hamburger","Cheeseburger","Pizza","Hot Dog","Fried Chicken","BBQ Ribs","Mac and Cheese","Grilled Cheese","BLT Sandwich","Caesar Salad","Cobb Salad","Chicken Wings","Nachos","Tacos","Burrito","Quesadilla","Fish and Chips","Clam Chowder","Lobster Roll","Cheesesteak","Pulled Pork Sandwich","Buffalo Wings","Meatloaf","Pot Roast","Fried Catfish","Jambalaya","Gumbo","Po' Boy","Corn Dog","Chili","Baked Beans","Cornbread","Biscuits and Gravy"],ingredient:["Flour","Sugar","Salt","Pepper","Butter","Eggs","Milk","Cheese","Tomato","Onion","Garlic","Olive Oil","Chicken","Beef","Pork","Fish","Rice","Pasta","Bread","Potato","Carrot","Celery","Bell Pepper","Mushroom","Spinach","Broccoli","Lettuce","Avocado","Lemon","Lime","Basil","Oregano","Thyme","Rosemary","Parsley","Cilantro"],cuisine:["American","Italian","Mexican","Chinese","Japanese","Thai","Indian","French","Greek","Spanish","Mediterranean","Vietnamese","Korean","Turkish","Lebanese","Brazilian","Argentinian","Peruvian","Caribbean","Moroccan","Ethiopian"],dessert:["Apple Pie","Chocolate Cake","Ice Cream","Brownies","Cookies","Cheesecake","Donuts","Cupcakes","Tiramisu","Panna Cotta","Cr\xE8me Br\xFBl\xE9e","Macarons","Churros","Flan","Bread Pudding","Pecan Pie","Key Lime Pie","Banana Split","Sundae","Milkshake"],fruit:["Apple","Banana","Orange","Strawberry","Grape","Watermelon","Pineapple","Mango","Peach","Pear","Cherry","Blueberry","Raspberry","Blackberry","Kiwi","Plum","Apricot","Cantaloupe","Honeydew","Papaya","Guava","Lychee","Dragon Fruit"],vegetable:["Carrot","Broccoli","Cauliflower","Spinach","Kale","Lettuce","Cabbage","Cucumber","Tomato","Bell Pepper","Zucchini","Eggplant","Asparagus","Green Beans","Peas","Corn","Potato","Sweet Potato","Onion","Garlic","Celery","Radish","Beet"],meat:["Beef","Chicken","Pork","Lamb","Turkey","Duck","Veal","Venison","Bison","Bacon","Sausage","Ham","Salami","Prosciutto","Ribeye","Sirloin","Tenderloin"],spice:["Black Pepper","Cumin","Paprika","Cinnamon","Nutmeg","Ginger","Turmeric","Curry","Chili Powder","Cayenne","Oregano","Basil","Thyme","Rosemary","Sage","Coriander","Cardamom","Cloves","Allspice","Bay Leaf","Mustard Seed","Fennel","Star Anise"]},animal:{dog:["Labrador Retriever","German Shepherd","Golden Retriever","French Bulldog","Bulldog","Poodle","Beagle","Rottweiler","German Shorthaired Pointer","Dachshund","Pembroke Welsh Corgi","Australian Shepherd","Yorkshire Terrier","Cavalier King Charles Spaniel","Doberman Pinscher","Boxer","Miniature Schnauzer","Great Dane","Siberian Husky","Bernese Mountain Dog","Pomeranian","Boston Terrier","Havanese","Shetland Sheepdog","Brittany","Cocker Spaniel"],cat:["Persian","Maine Coon","Ragdoll","Bengal","Siamese","British Shorthair","Abyssinian","Birman","Oriental Shorthair","Sphynx","Devon Rex","American Shorthair","Scottish Fold","Exotic Shorthair","Russian Blue","Norwegian Forest Cat","Siberian","Burmese","Manx","Cornish Rex","Himalayan","Turkish Angora","Balinese","Tonkinese"],bird:["Parakeet","Cockatiel","Lovebird","Canary","Finch","Parrot","Macaw","Cockatoo","African Grey","Conure","Budgie","Dove","Pigeon","Robin","Cardinal","Blue Jay","Sparrow","Crow","Raven","Hawk","Eagle","Owl","Hummingbird","Woodpecker"],fish:["Goldfish","Betta","Guppy","Molly","Platy","Swordtail","Tetra","Angelfish","Discus","Gourami","Barb","Danio","Koi","Oscar","Cichlid","Clownfish","Tang","Damselfish","Wrasse","Goby","Blenny","Pufferfish","Lionfish"],horse:["Arabian","Thoroughbred","Quarter Horse","Appaloosa","Paint","Tennessee Walker","Morgan","Andalusian","Friesian","Clydesdale","Percheron","Belgian","Mustang","Shetland Pony","Welsh Pony","Palomino","Buckskin","Pinto","Warmblood"],rabbit:["Holland Lop","Netherland Dwarf","Mini Rex","Flemish Giant","English Lop","French Lop","Angora","Dutch","Lionhead","Rex","Polish","Himalayan"],insect:["Butterfly","Bee","Ant","Beetle","Ladybug","Dragonfly","Grasshopper","Cricket","Moth","Firefly","Praying Mantis","Walking Stick","Caterpillar","Wasp"],type:["Dog","Cat","Bird","Fish","Rabbit","Hamster","Guinea Pig","Mouse","Rat","Ferret","Chinchilla","Hedgehog","Turtle","Lizard","Snake","Frog"]},sport:{sport:["Football","Basketball","Baseball","Soccer","Tennis","Golf","Hockey","Boxing","Wrestling","Swimming","Track and Field","Volleyball","Cricket","Rugby","Lacrosse","Badminton","Table Tennis","Bowling","Skiing","Snowboarding","Surfing","Skateboarding"],team:["Lakers","Warriors","Bulls","Celtics","Yankees","Red Sox","Cowboys","Patriots","49ers","Packers","Steelers","Maple Leafs","Bruins","Canadiens","Blackhawks"],athlete:["Michael Jordan","LeBron James","Tom Brady","Serena Williams","Tiger Woods","Muhammad Ali","Babe Ruth","Wayne Gretzky","Usain Bolt","Michael Phelps"]},music:{genre:["Rock","Pop","Hip Hop","Jazz","Blues","Country","Electronic","Classical","R&B","Soul","Funk","Reggae","Metal","Punk","Indie","Alternative","Folk","Disco","House","Techno","Dubstep","Trap","Gospel","Opera"],artist:["The Beatles","Elvis Presley","Michael Jackson","Madonna","Prince","Bob Dylan","Led Zeppelin","Pink Floyd","Queen","David Bowie","The Rolling Stones","Nirvana","Bruce Springsteen","Stevie Wonder","Aretha Franklin","Ray Charles","Johnny Cash"],song:["Bohemian Rhapsody","Imagine","Hey Jude","Billie Jean","Like a Rolling Stone","Smells Like Teen Spirit","Hotel California","Sweet Child O' Mine","Stairway to Heaven","Purple Haze","What's Going On","Respect","I Want to Hold Your Hand"],instrument:["Guitar","Piano","Drums","Bass","Violin","Cello","Saxophone","Trumpet","Flute","Clarinet","Trombone","Harp","Banjo","Mandolin","Ukulele","Harmonica","Accordion","Xylophone","Synthesizer","Keyboard"]},commerce:{product:["Chair","Table","Lamp","Sofa","Bed","Desk","Computer","Phone","Tablet","Watch","Shoes","Shirt","Pants","Jacket","Hat","Gloves","Bag","Wallet","Sunglasses","Bicycle","Car","Motorcycle","Camera","Headphones","Speaker"],productAdjective:["Small","Medium","Large","Ergonomic","Rustic","Modern","Sleek","Lightweight","Durable","Handmade","Recycled","Refined","Gorgeous","Incredible","Practical","Fantastic","Awesome","Generic","Unbranded","Licensed","Intelligent","Tasty"],productMaterial:["Steel","Wood","Concrete","Plastic","Cotton","Granite","Rubber","Metal","Soft","Fresh","Frozen","Aluminum","Leather","Silk","Wool","Linen"],department:["Electronics","Clothing","Home & Garden","Sports","Automotive","Books","Toys","Health & Beauty","Grocery","Jewelry","Tools","Music","Movies","Baby","Pet Supplies"],color:["Red","Blue","Green","Yellow","Black","White","Gray","Silver","Gold","Purple","Pink","Orange","Brown","Navy","Teal","Maroon","Olive"]},book:{title:["To Kill a Mockingbird","1984","Pride and Prejudice","The Great Gatsby","Moby Dick","War and Peace","The Odyssey","The Catcher in the Rye","The Lord of the Rings","Harry Potter and the Sorcerer's Stone","The Hobbit","Brave New World","Crime and Punishment","The Brothers Karamazov","One Hundred Years of Solitude"],author:["Ernest Hemingway","F. Scott Fitzgerald","Jane Austen","Charles Dickens","Mark Twain","Leo Tolstoy","Fyodor Dostoevsky","George Orwell","J.R.R. Tolkien","J.K. Rowling","Stephen King","Agatha Christie","William Shakespeare","Edgar Allan Poe","Harper Lee"],publisher:["Penguin Random House","HarperCollins","Simon & Schuster","Macmillan","Hachette","Scholastic","Oxford University Press","Cambridge University Press","Bloomsbury","Vintage"],genre:["Fiction","Non-Fiction","Mystery","Thriller","Romance","Science Fiction","Fantasy","Horror","Historical Fiction","Biography","Self-Help","Poetry","Drama","Adventure","Young Adult"],series:["Harry Potter","The Lord of the Rings","A Song of Ice and Fire","The Hunger Games","Twilight","The Chronicles of Narnia","Percy Jackson","Discworld","Dune","Foundation"],review:["A masterpiece of modern literature!","Gripping from start to finish.","Couldn't put it down!","A must-read for everyone.","Beautifully written and deeply moving.","An unforgettable story.","Brilliant and thought-provoking.","One of the best books I've ever read."]},vehicle:{manufacturer:["Toyota","Ford","Chevrolet","Honda","Nissan","BMW","Mercedes-Benz","Audi","Volkswagen","Tesla","Volvo","Porsche","Jeep","Mazda","Subaru"],model:["Accord","Camry","Civic","Corolla","CR-V","F-150","RAV4","Model 3","Model Y","3 Series","C-Class","A4","Golf","Mustang","Wrangler"],type:["Sedan","SUV","Truck","Coupe","Convertible","Hatchback","Wagon","Van","Minivan","Crossover","Sports Car","Electric","Hybrid"],fuel:["Gasoline","Diesel","Electric","Hybrid","Plug-in Hybrid","Hydrogen","Ethanol","Biodiesel"],bicycle:["Mountain Bike","Road Bike","BMX","Cruiser","Hybrid","Electric Bike","Folding Bike","Gravel Bike"]},word:{adjective:["beautiful","happy","sad","quick","slow","big","small","tall","short","long","wide","narrow","thick","thin","heavy","light","hard","soft","hot","cold"],adverb:["quickly","slowly","carefully","easily","hardly","loudly","quietly","suddenly","finally","really","very","completely","absolutely","perfectly","badly","well"],conjunction:["and","but","or","nor","for","yet","so","although","because","since","unless","while","when","if"],interjection:["wow","oh","ah","hey","oops","ouch","yay","hooray","hello","goodbye","yes","no"],noun:["table","chair","book","pen","computer","phone","door","window","car","house","tree","flower","dog","cat","bird","fish","water","fire","sun","moon"],preposition:["in","on","at","by","for","with","from","to","of","about","under","over","above","below","between","through"],verb:["run","walk","jump","swim","fly","eat","drink","sleep","work","play","read","write","speak","listen","watch","think","know","make","take","give"]},hacker:{abbreviation:["TCP","HTTP","RAM","GB","CSS","SSL","SQL","CLI","UI","UX","FTP","API","DNS","IP","LAN","WAN","VPN","SSH","JSON","REST"],adjective:["auxiliary","primary","back-end","digital","open-source","virtual","cross-platform","redundant","online","wireless","mobile","neural","optical","cloud","quantum"],noun:["driver","protocol","bandwidth","panel","microchip","program","port","card","interface","system","sensor","firewall","pixel","application","server","database","network"],verb:["bypass","hack","override","compress","copy","navigate","index","connect","generate","calculate","synthesize","transmit","program","parse","compile","encrypt","decrypt"],ingverb:["bypassing","hacking","overriding","compressing","copying","navigating","indexing","connecting","generating","calculating","synthesizing","transmitting","programming","parsing","compiling","encrypting"],phrase:["We need to bypass the digital firewall!","Try to hack the TCP protocol!","The SSL port is down, override the wireless system!","You can't compress the bandwidth without indexing the neural network!"]},system:{fileName:["document","report","presentation","spreadsheet","image","video","audio","backup","archive","data","config","settings","log","cache"],fileType:["audio","image","text","video","application","document","spreadsheet","presentation","archive","code"]},science:{chemicalElement:["Hydrogen","Helium","Lithium","Carbon","Nitrogen","Oxygen","Fluorine","Neon","Sodium","Magnesium","Aluminum","Silicon","Phosphorus","Sulfur","Chlorine","Iron","Copper","Zinc","Silver","Gold"],unit:["meter","kilogram","second","ampere","kelvin","mole","candela","newton","pascal","joule","watt","volt","ohm","hertz","celsius"],constant:["Speed of Light","Gravitational Constant","Planck Constant","Boltzmann Constant","Avogadro Constant","Elementary Charge","Gas Constant"],field:["Physics","Chemistry","Biology","Astronomy","Geology","Ecology","Genetics","Neuroscience","Biochemistry","Microbiology","Botany","Zoology"]}},$k=new Map,xj=new Map,_k=class{static AVAILABLE_BASE_LOCALES=["af","ar","az","cs","da","de","en","eo","es","fa","fi","fr","he","hi","it","ja","ko","nl","no","pl","pt","sv","tl","tr","uk","zh","zu"];static AVAILABLE_LOCALE_VARIANTS=["af_ZA","de_AT","de_CH","de_DE","en_AU","en_CA","en_GB","en_GH","en_HK","en_IE","en_IN","en_NG","en_US","en_ZA","es_ES","es_MX","fr_BE","fr_CA","fr_CH","fr_FR","fr_LU","fr_SN","pt_BR","pt_MZ","pt_PT","zh_CN","zh_TW","zu_ZA"];static getAvailableLocales(){return[...this.AVAILABLE_BASE_LOCALES,...this.AVAILABLE_LOCALE_VARIANTS]}static getAvailableBaseLocales(){return this.AVAILABLE_BASE_LOCALES}static getAvailableLocaleVariants(){return this.AVAILABLE_LOCALE_VARIANTS}static async load(k){let j=cj(k).normalized;if(j==="en"){if(!$k.has("en"))$k.set("en",L1);return L1}if($k.has(j))return $k.get(j);if(xj.has(j))return xj.get(j);let d=this.loadLocaleWithFallback(j);xj.set(j,d);try{let O=await d;return $k.set(j,O),O}finally{xj.delete(j)}}static loadSync(k){let j=cj(k).normalized;if(j==="en"){if(!$k.has("en"))$k.set("en",L1);return L1}if($k.has(j))return $k.get(j);throw Error(`Locale '${k}' is not loaded. Please use async loading with faker.setLocale('${k}') or preload it.`)}static isCached(k){let j=cj(k).normalized;return $k.has(j)}static async preload(k){await Promise.all(k.map((j)=>this.load(j)))}static clearCache(){$k.clear(),xj.clear()}static async loadLocaleWithFallback(k){let j=ZU(k);for(let d=0;d<j.length;d++){let O=j[d],$=d===0&&j.length>1,Z=!$;try{if($){let X=await this.loadLocaleModule(O),E=j[1];try{let F=await this.loadLocaleModule(E);return eZ(F,X)}catch{return X}}else return await this.loadLocaleModule(O)}catch(X){if(d===j.length-1)throw X;continue}}throw Error(`Failed to load locale '${k}' with fallback chain: ${j.join(" \u2192 ")}`)}static async tryWorkspaceImport(k,j){if(!yj())return null;try{let d=await import(`../../${j.packageName}/dist/index.js`);return d[j.normalized]||d[j.language]||d.default}catch{try{let d=QP.cwd(),O=UP(d,"packages",j.packageName,"dist","index.js");if(!PP(O))return null;let $=await import(`file://${O}`);return $[j.normalized]||$[j.language]||$.default}catch{return null}}}static async loadLocaleModule(k){let j=XU(k),d=cj(k);try{let O=await import(j);return O[d.normalized]||O[d.language]||O.default}catch(O){let $=O instanceof Error?O.message:String(O);if($.includes("Cannot find")||$.includes("not found")||$.includes("ModuleNotFound")){if(yj()&&j.startsWith("@mock-locale/")){let Z=await this.tryWorkspaceImport(k,d);if(Z)return Z}if(D8.autoInstallLocales)if(console.log(`
|
|
129
|
-
\uD83D\uDD0D Locale '${k}' not found. Auto-installing ${j}...`),k6(j)){if(yj()&&j.startsWith("@mock-locale/")){let Z=await this.tryWorkspaceImport(k,d);if(Z)return Z}try{let Z=await import(j);return Z[d.normalized]||Z[d.language]||Z.default}catch(Z){if(yj()&&j.startsWith("@mock-locale/")){let X=await this.tryWorkspaceImport(k,d);if(X)return X;throw Error(`Locale '${k}' workspace package is not properly built or linked. Please ensure the package is built with 'bun run build' in the ${j.replace("@mock-locale/","packages/")} directory.`)}throw Error(`Failed to load locale '${k}' after installation: ${Z instanceof Error?Z.message:String(Z)}`)}}else throw Error(`Failed to auto-install locale '${k}'. Please install manually with: bun add ${j}`);throw Error(`Locale '${k}' is not installed. Install it with: bun add ${j}
|
|
130
|
-
Or install all locales with: bun add @mock-locale/{af,ar,az,cs,da,de,en,eo,es,fa,fi,fr,he,hi,it,ja,ko,nl,no,pl,pt,sv,tl,tr,uk,zh,zu}
|
|
131
|
-
Or enable auto-install in your mock.config.ts: { autoInstallLocales: true }`)}throw Error(`Failed to load locale '${k}': ${$}`)}}},$6=new A8,Z6={email:(_)=>{return/^[^\s@]+@[^\s@][^\s.@]*\.[^\s@]+$/.test(_)},phone:(_)=>{let k=/^\+?[1-9]\d{0,15}$/,j=_.replace(/[\s\-()]/g,"");return j.length>=7&&k.test(j)},name:(_)=>{return/^[a-z\s\-']+$/i.test(_)&&_.length>=2&&_.length<=50},age:(_)=>{return Number.isInteger(_)&&_>=0&&_<=150},url:(_)=>{try{let k=new URL(_);return _.startsWith("http://")||_.startsWith("https://")}catch{return!1}},regex:(_)=>(k)=>{return _.test(k)},length:(_,k)=>(j)=>{return j.length>=_&&j.length<=k},range:(_,k)=>(j)=>{return j>=_&&j<=k}},X6={phoneByCountry:{field:"phone",dependsOn:"country",mapping:{"United States":"+1-###-###-####","United Kingdom":"+44 #### ### ###",Germany:"+49 ### ########",France:"+33 # ## ## ## ##",Spain:"+34 ### ## ## ##",Italy:"+39 ### ### ###",Japan:"+81 ##-####-####",China:"+86 ### #### ####",Australia:"+61 ### ### ###",Canada:"+1-###-###-####"}},postalCodeByCountry:{field:"postalCode",dependsOn:"country",mapping:{"United States":"#####","United Kingdom":"AA## #AA",Germany:"#####",France:"#####",Spain:"#####",Italy:"#####",Japan:"###-####",China:"######",Australia:"####",Canada:"A#A #A#"}},firstNameByGender:{field:"firstName",dependsOn:"gender",mapping:{male:["John","Michael","David","James","Robert","William","Richard","Thomas","Christopher","Daniel"],female:["Mary","Patricia","Jennifer","Linda","Elizabeth","Barbara","Susan","Jessica","Sarah","Karen"]}}},E6={commonFirstNames:{items:[{item:"John",weight:100},{item:"Michael",weight:85},{item:"David",weight:80},{item:"James",weight:75},{item:"Robert",weight:70},{item:"William",weight:65},{item:"Richard",weight:60},{item:"Thomas",weight:55},{item:"Christopher",weight:50},{item:"Daniel",weight:45}]},ageDistribution:{items:[{item:25,weight:80},{item:30,weight:90},{item:35,weight:95},{item:40,weight:100},{item:45,weight:85},{item:50,weight:70},{item:55,weight:55},{item:60,weight:40},{item:65,weight:25},{item:70,weight:15}]},countryDistribution:{items:[{item:"United States",weight:100},{item:"China",weight:95},{item:"India",weight:90},{item:"Brazil",weight:60},{item:"Russia",weight:55},{item:"Japan",weight:50},{item:"Germany",weight:45},{item:"United Kingdom",weight:40},{item:"France",weight:35},{item:"Italy",weight:30}]}},G6=[".","_","-",""],F6=["lorem","ipsum","dolor","sit","amet","consectetur","adipiscing","elit","sed","do","eiusmod","tempor","incididunt","ut","labore","et","dolore","magna","aliqua","enim","ad","minim","veniam","quis","nostrud","exercitation","ullamco","laboris","nisi","aliquip","ex","ea","commodo","consequat","duis","aute","irure","in","reprehenderit","voluptate","velit","esse","cillum","fugiat","nulla","pariatur","excepteur","sint","occaecat","cupidatat","non","proident","sunt","culpa","qui","officia","deserunt","mollit","anim","id","est","laborum"],z6=["Toyota","Ford","Chevrolet","Honda","Nissan","BMW","Mercedes-Benz","Audi","Volkswagen","Hyundai","Kia","Mazda","Subaru","Lexus","Tesla","Volvo","Porsche","Jeep","Ram","GMC","Dodge","Chrysler","Buick","Cadillac","Acura","Infiniti","Genesis","Land Rover","Jaguar","Mini"],S6=["Accord","Camry","Civic","Corolla","CR-V","F-150","RAV4","Silverado","Tacoma","Altima","Sentra","Rogue","Model 3","Model Y","Model S","X5","X3","3 Series","5 Series","C-Class","E-Class","A4","Q5","Golf","Jetta","Passat","Tiguan","Escape","Explorer","Mustang","Ranger","Malibu","Equinox","Traverse","Wrangler","Grand Cherokee","Cherokee","Compass"],Y6=["Sedan","SUV","Truck","Coupe","Convertible","Hatchback","Wagon","Van","Minivan","Crossover","Sports Car","Luxury","Electric","Hybrid","Diesel","Compact"],L6=["Gasoline","Diesel","Electric","Hybrid","Plug-in Hybrid","Hydrogen","Ethanol","Biodiesel","CNG","LPG"],P6=["Black","White","Silver","Gray","Red","Blue","Green","Yellow","Orange","Brown","Gold","Purple","Pink","Beige","Tan","Navy","Maroon","Teal","Burgundy","Charcoal"],R8="abcdefghijklmnopqrstuvwxyz".split(""),w8=new U0,U6=w8}),cU={};q8(cU,{validateData:()=>u1,selectWeightedItem:()=>l1,isInWorkspace:()=>yj,installPackage:()=>k6,globalProviderRegistry:()=>$6,getConfig:()=>$U,generateRealisticData:()=>GU,faker:()=>w8,detectPackageManager:()=>_6,defaultConfig:()=>G0,default:()=>U6,config:()=>D8,applyRelationships:()=>tk,applyConstraints:()=>EU,WordModule:()=>i1,WeightedSelections:()=>E6,VehicleModule:()=>x1,ValidationRules:()=>Z6,SystemModule:()=>N1,StringModule:()=>$0,SportModule:()=>b1,ScienceModule:()=>H1,Random:()=>Z0,PhoneModule:()=>q1,PersonModule:()=>f1,NumberModule:()=>O0,MusicModule:()=>h1,LoremModule:()=>d0,LocaleLoader:()=>_k,InternetModule:()=>C1,ImageModule:()=>j0,HelpersModule:()=>k0,HackerModule:()=>M1,GitModule:()=>_0,FoodModule:()=>w1,FinanceModule:()=>eO,Faker:()=>U0,DateModule:()=>aO,DatabaseModule:()=>tO,DataRelationships:()=>X6,DataProviderRegistry:()=>A8,CompanyModule:()=>R1,CommerceModule:()=>D1,ColorModule:()=>I1,BookModule:()=>J1,AnimalModule:()=>n1,AddressModule:()=>K1});var Hn=r(async()=>{await BU()});function Tk(_){if(!FO)try{FO=(hO(),mz(K6)).getModel}catch{FO=()=>{return}}return FO(_)}function Q6(_){if(_.database instanceof M8)B1=_.database;else B1=new M8(_.database||":memory:",{create:!0});F0.clear()}function J_(){if(!B1)B1=new M8(":memory:",{create:!0});return B1}function yU(_){let k=new Set,j=_.belongsToMany;if(!j)return k;if(Array.isArray(j)){for(let d of j)if(typeof d==="string")k.add(d.toLowerCase());else if(d&&typeof d==="object"&&d.model)k.add(d.model.toLowerCase())}else if(typeof j==="object")for(let d of Object.keys(j))k.add(d);return k}class kk{_attributes;_original;_definition;_hasSaved=!1;_relations={};constructor(_,k={}){this._definition=_,this._attributes={...k},this._original=null;let j=yU(_);if(j.size===0)return;let d=this;return new Proxy(this,{get(O,$,Z){if(typeof $==="string"&&j.has($)&&!($ in O))return()=>{let X=V6(_,$);if(!X||X.type!=="belongsToMany")throw Error(`[orm] relation '${$}' did not resolve to a belongsToMany on '${_.name}'`);let E=Tk(X.relatedModelName),F=E?.getDefinition?.()||E?.definition;if(!F)throw Error(`[orm] related model '${X.relatedModelName}' is not registered`);return new T6(d,_,X,F)};return Reflect.get(O,$,Z)}})}getOriginalAttributes(){if(this._original===null)this._original={...this._attributes};return this._original}get(_){let k=this._definition.get?.[_];if(k)try{let j=k(this._attributes);if(j!==void 0)return j}catch{}return this._attributes[_]}getAttribute(_){return this._attributes[_]}getAttributes(){return{...this._attributes}}set(_,k){if(this._original===null)this._original={...this._attributes};this._attributes[_]=k}only(_){let k={};for(let j of _)k[j]=this._attributes[j];return k}except(_){let k=new Set(_.map((d)=>d)),j={};for(let d of Object.keys(this._attributes))if(!k.has(d))j[d]=this._attributes[d];return j}getRelation(_){return this._relations[_]}setRelation(_,k){this._relations[_]=k}getLoadedRelations(){return{...this._relations}}get attributes(){return{...this._attributes}}get id(){let _=this._definition.primaryKey||"id";return this._attributes[_]}isDirty(_){if(this._original===null)return!1;if(_)return this._attributes[_]!==this._original[_];return Object.keys(this._attributes).some((k)=>this._attributes[k]!==this._original[k])}isClean(_){return!this.isDirty(_)}getOriginal(_){return this.getOriginalAttributes()[_]}getChanges(){if(this._original===null)return{};let _={};for(let k of Object.keys(this._attributes))if(this._attributes[k]!==this._original[k])_[k]=this._attributes[k];return _}fill(_){let k=this._definition.attributes;for(let[j,d]of Object.entries(_)){let O=k[j];if(O?.fillable&&!O?.guarded)this._attributes[j]=d}return this}forceFill(_){return Object.assign(this._attributes,_),this}save(){let _=J_(),k=this._definition.primaryKey||"id",j=this._definition.hooks,d=this._definition.set||{};for(let[O,$]of Object.entries(d))if(this.isDirty(O))this._attributes[O]=$(this._attributes);if(this._attributes[k]){j?.beforeUpdate?.(this,this.getChanges());let O=this.getChanges(),$=Object.keys(O);if($.length>0){let Z=$.map((E)=>`${E} = ?`).join(", "),X=[...Object.values(O),this._attributes[k]];if(this._definition.traits?.useTimestamps){let E=new Date().toISOString();_.run(`UPDATE ${this._definition.table} SET ${Z}, updated_at = ? WHERE ${k} = ?`,[...Object.values(O),E,this._attributes[k]])}else _.run(`UPDATE ${this._definition.table} SET ${Z} WHERE ${k} = ?`,X)}j?.afterUpdate?.(this)}else{let O=this._definition.attributes,$={};for(let[F,G]of Object.entries(O))if(G.fillable&&this._attributes[F]!==void 0)$[F]=this._attributes[F];if(this._definition.traits?.useTimestamps){let F=new Date().toISOString();$.created_at=F,$.updated_at=F}if(this._definition.traits?.useUuid&&!$.uuid)$.uuid=crypto.randomUUID();j?.beforeCreate?.($);let Z=Object.keys($),X=Z.map(()=>"?").join(", "),E=_.run(`INSERT INTO ${this._definition.table} (${Z.join(", ")}) VALUES (${X})`,Object.values($));for(let[F,G]of Object.entries($))this._attributes[F]=G;this._attributes[k]=E.lastInsertRowid,j?.afterCreate?.(this)}return this._original={...this._attributes},this._hasSaved=!0,this}update(_){return this.fill(_),this.save()}fresh(){let _=J_(),k=this._definition.primaryKey||"id",j=this._attributes[k];if(j==null)return null;let d=_.query(`SELECT * FROM ${this._definition.table} WHERE ${k} = ?`).get(j);if(!d)return null;return new kk(this._definition,d)}delete(){let _=J_(),k=this._definition.primaryKey||"id",j=this._attributes[k],d=this._definition.hooks;if(!j)throw Error("Cannot delete a model without a primary key");if(d?.beforeDelete?.(this),this._definition.traits?.useSoftDeletes)_.run(`UPDATE ${this._definition.table} SET deleted_at = ? WHERE ${k} = ?`,[new Date().toISOString(),j]);else _.run(`DELETE FROM ${this._definition.table} WHERE ${k} = ?`,[j]);return d?.afterDelete?.(this),!0}refresh(){let _=J_(),k=this._definition.primaryKey||"id",j=this._attributes[k];if(!j)throw Error("Cannot refresh a model without a primary key");let d=_.query(`SELECT * FROM ${this._definition.table} WHERE ${k} = ?`).get(j);if(!d)return null;return this._attributes=d,this._original=null,this}replicate(){let _=this._definition.primaryKey||"id",k={...this._attributes};return delete k[_],delete k.uuid,delete k.created_at,delete k.updated_at,new kk(this._definition,k)}toArray(){let _={...this._attributes};for(let[k,j]of Object.entries(this._relations))if(Array.isArray(j))_[k]=j.map((d)=>d.toArray());else if(j)_[k]=j.toArray();else _[k]=null;return _}toJSON(){let _=new Set;for(let[j,d]of Object.entries(this._definition.attributes))if(d.hidden)_.add(j);let k={};for(let[j,d]of Object.entries(this._attributes))if(!_.has(j))k[j]=d;for(let[j,d]of Object.entries(this._relations))if(Array.isArray(d))k[j]=d.map((O)=>O.toJSON());else if(d)k[j]=d.toJSON();else k[j]=null;return k}}function CO(_){let k=C8.get(_);if(k!==void 0)return k;return k=_.replace(/([A-Z])/g,"_$1").toLowerCase().replace(/^_/,""),C8.set(_,k),k}function P1(_){let k=h8.get(_);if(k!==void 0)return k;let j=CO(_);if(j.endsWith("y")&&!j.endsWith("ay")&&!j.endsWith("ey")&&!j.endsWith("oy")&&!j.endsWith("uy"))k=j.slice(0,-1)+"ies";else if(j.endsWith("s")||j.endsWith("x")||j.endsWith("ch")||j.endsWith("sh"))k=`${j}es`;else k=`${j}s`;return h8.set(_,k),k}function V6(_,k){let{name:j,table:d}=_,O=_.primaryKey||"id";function $(Y){if(!Y)return null;if(Array.isArray(Y)){for(let S of Y){let z=typeof S==="string"?S:S?.model||"";if(z&&z.toLowerCase()===k.toLowerCase())return z}return null}if(typeof Y==="object"){for(let[S,z]of Object.entries(Y))if(S===k||S.toLowerCase()===k.toLowerCase())return typeof z==="string"?z:z?.model||z?.target||S}return null}function Z(){let Y=_.belongsToMany;if(!Y)return null;if(Array.isArray(Y)){for(let S of Y)if(typeof S==="string"){if(S.toLowerCase()===k.toLowerCase())return{entry:S}}else if(S&&typeof S==="object"&&S.model){if(S.model.toLowerCase()===k.toLowerCase())return{entry:S}}return null}if(typeof Y==="object"){for(let[S,z]of Object.entries(Y))if(S===k||S.toLowerCase()===k.toLowerCase())return{entry:z}}return null}let X=$(_.hasMany);if(X){let S=Tk(X)?.getTable?.()||P1(X),z=CO(j)+"_id";return{type:"hasMany",relatedModelName:X,relatedTable:S,foreignKey:z,localKey:O}}let E=$(_.hasOne);if(E){let S=Tk(E)?.getTable?.()||P1(E),z=CO(j)+"_id";return{type:"hasOne",relatedModelName:E,relatedTable:S,foreignKey:z,localKey:O}}let F=$(_.belongsTo);if(F){let Y=Tk(F),S=Y?.getTable?.()||P1(F),z=Y?.getDefinition?.()?.primaryKey||"id",U=CO(F)+"_id";return{type:"belongsTo",relatedModelName:F,relatedTable:S,foreignKey:U,localKey:z}}let G=Z();if(G){let Y=typeof G.entry==="object",S=Y?G.entry.model:G.entry,U=Tk(S)?.getTable?.()||P1(S),Q=Y?G.entry:null,I,T;if(Q?.table)I=Q.table;else if(Q?.through){T=Q.through;let f=Tk(Q.through);if(!f)throw Error(`[orm] belongsToMany relation '${k}' on '${j}' references unknown through model '${Q.through}'. Make sure '${Q.through}' is registered.`);I=f.getTable?.()||f.getDefinition?.()?.table||P1(Q.through)}else{let f=d.endsWith("s")?d.slice(0,-1):d,N=U.endsWith("s")?U.slice(0,-1):U;I=[f,N].sort().join("_")}let W=Q?.foreignKey||`${d.endsWith("s")?d.slice(0,-1):d}_id`,J=Q?.relatedKey||`${U.endsWith("s")?U.slice(0,-1):U}_id`,C=[];if(Q?.pivot?.columns)for(let f of Object.keys(Q.pivot.columns))C.push(f);if(T){let f=Tk(T),N=f?.getDefinition?.()||f?.definition,y=N?.attributes??{},B=N?.primaryKey??"id";for(let A of Object.keys(y)){if(A===W||A===J||A===B)continue;if(!C.includes(A))C.push(A)}}return{type:"belongsToMany",relatedModelName:S,relatedTable:U,foreignKey:W,localKey:O,pivotTable:I,pivotFkParent:W,pivotFkRelated:J,pivotColumns:C,pivotModelName:T,pivotTimestamps:Boolean(Q?.pivot?.timestamps)}}return null}class T6{_parent;_parentDef;_resolved;_relatedDef;_wheres=[];_pivotWheres=[];_orderBy=[];_limit;_offset;constructor(_,k,j,d){this._parent=_,this._parentDef=k,this._resolved=j,this._relatedDef=d}get parentId(){let _=this._parentDef.primaryKey||"id";return this._parent.get(_)}get pivotTable(){return this._resolved.pivotTable}get fkParent(){return this._resolved.pivotFkParent}get fkRelated(){return this._resolved.pivotFkRelated}get relatedTable(){return this._resolved.relatedTable}get relatedPk(){return this._relatedDef.primaryKey||"id"}where(_,k,j){if(j===void 0)this._wheres.push({sql:`${this.relatedTable}.${_} = ?`,params:[k]});else this._wheres.push({sql:`${this.relatedTable}.${_} ${String(k)} ?`,params:[j]});return this}wherePivot(_,k,j){if(j===void 0)this._pivotWheres.push({sql:`${this.pivotTable}.${_} = ?`,params:[k]});else this._pivotWheres.push({sql:`${this.pivotTable}.${_} ${String(k)} ?`,params:[j]});return this}wherePivotIn(_,k){if(!k.length)return this;let j=k.map(()=>"?").join(", ");return this._pivotWheres.push({sql:`${this.pivotTable}.${_} IN (${j})`,params:[...k]}),this}wherePivotNotIn(_,k){if(!k.length)return this;let j=k.map(()=>"?").join(", ");return this._pivotWheres.push({sql:`${this.pivotTable}.${_} NOT IN (${j})`,params:[...k]}),this}wherePivotNull(_){return this._pivotWheres.push({sql:`${this.pivotTable}.${_} IS NULL`,params:[]}),this}wherePivotNotNull(_){return this._pivotWheres.push({sql:`${this.pivotTable}.${_} IS NOT NULL`,params:[]}),this}orderBy(_,k="asc"){return this._orderBy.push(`${_} ${k.toUpperCase()}`),this}limit(_){return this._limit=_,this}offset(_){return this._offset=_,this}buildSelect(){let _=[],k=`SELECT ${this.relatedTable}.*, ${this.pivotTable}.* FROM ${this.relatedTable}`;k+=` INNER JOIN ${this.pivotTable} ON ${this.pivotTable}.${this.fkRelated} = ${this.relatedTable}.${this.relatedPk}`,k+=` WHERE ${this.pivotTable}.${this.fkParent} = ?`,_.push(this.parentId);for(let j of this._pivotWheres)k+=` AND ${j.sql}`,_.push(...j.params);for(let j of this._wheres)k+=` AND ${j.sql}`,_.push(...j.params);if(this._orderBy.length>0)k+=` ORDER BY ${this._orderBy.join(", ")}`;if(this._limit!==void 0)k+=` LIMIT ${this._limit}`;if(this._offset!==void 0)k+=` OFFSET ${this._offset}`;return{sql:k,params:_}}hydrateRows(_){let k=new Set(Object.keys(this._relatedDef.attributes??{}));k.add(this.relatedPk),k.add("created_at"),k.add("updated_at"),k.add("deleted_at");let j=this.fkParent,d=this.fkRelated;return _.map((O)=>{let $={},Z={};for(let[E,F]of Object.entries(O)){if(E===j||E===d)continue;if(k.has(E))$[E]=F;else Z[E]=F}$[this.relatedPk]=O[this.relatedPk];let X=new kk(this._relatedDef,$);return X.pivot=Z,X})}get(){let _=J_(),{sql:k,params:j}=this.buildSelect(),d=_.query(k).all(...j);return this.hydrateRows(d)}first(){return this._limit=1,this.get()[0]}count(){let _=J_(),k=`SELECT COUNT(*) as count FROM ${this.pivotTable} WHERE ${this.fkParent} = ?`,j=[this.parentId];for(let d of this._pivotWheres)k+=` AND ${d.sql}`,j.push(...d.params);return _.query(k).get(...j).count}exists(){return this.count()>0}now(){return new Date().toISOString()}attach(_,k={}){let j=J_(),d=Array.isArray(_)?_:[_];if(d.length===0)return 0;let O=this._resolved.pivotTimestamps?this.now():null,$=0;for(let Z of d){let X={[this.fkParent]:this.parentId,[this.fkRelated]:Z,...k};if(O){if(X.created_at===void 0)X.created_at=O;if(X.updated_at===void 0)X.updated_at=O}let E=Object.keys(X),F=E.map(()=>"?").join(", "),G=`INSERT INTO ${this.pivotTable} (${E.join(", ")}) VALUES (${F})`,Y=E.map((S)=>X[S]);j.run(G,Y),$++}return $}detach(_){let k=J_(),j=`DELETE FROM ${this.pivotTable} WHERE ${this.fkParent} = ?`,d=[this.parentId];if(_!==void 0&&_!==null){let O=Array.isArray(_)?_:[_];if(O.length===0)return 0;let $=O.map(()=>"?").join(", ");j+=` AND ${this.fkRelated} IN (${$})`,d.push(...O)}return k.run(j,d).changes}updateExistingPivot(_,k){let j=J_(),d={...k};if(this._resolved.pivotTimestamps&&d.updated_at===void 0)d.updated_at=this.now();let O=Object.keys(d);if(O.length===0)return 0;let $=O.map((E)=>`${E} = ?`).join(", "),Z=`UPDATE ${this.pivotTable} SET ${$} WHERE ${this.fkParent} = ? AND ${this.fkRelated} = ?`,X=[...O.map((E)=>d[E]),this.parentId,_];return j.run(Z,X).changes}sync(_){let k=J_(),j=new Map;for(let F of _)if(F!=null&&typeof F==="object"&&"id"in F){let{id:G,...Y}=F;j.set(G,Y)}else j.set(F,{});let d=k.query(`SELECT * FROM ${this.pivotTable} WHERE ${this.fkParent} = ?`).all(this.parentId),O=new Set(d.map((F)=>F[this.fkRelated])),$=[],Z=[],X=[],E=[...O].filter((F)=>!j.has(F));if(E.length>0)this.detach(E),Z.push(...E);for(let[F,G]of j)if(!O.has(F))this.attach(F,G),$.push(F);else if(Object.keys(G).length>0)this.updateExistingPivot(F,G),X.push(F);return{attached:$,detached:Z,updated:X}}toggle(_){let k=J_(),j=Array.isArray(_)?_:[_];if(j.length===0)return{attached:[],detached:[]};let d=j.map(()=>"?").join(", "),O=k.query(`SELECT ${this.fkRelated} FROM ${this.pivotTable} WHERE ${this.fkParent} = ? AND ${this.fkRelated} IN (${d})`).all(this.parentId,...j),$=new Set(O.map((E)=>E[this.fkRelated])),Z=j.filter((E)=>!$.has(E)),X=j.filter((E)=>$.has(E));if(Z.length>0)this.attach(Z);if(X.length>0)this.detach(X);return{attached:Z,detached:X}}}class k_{_definition;_wheres=[];_orderBy=[];_limit;_offset;_select=["*"];_withRelations=[];constructor(_){this._definition=_}where(_,k,j){if(j===void 0)this._wheres.push({column:_,operator:"=",value:k,boolean:"and"});else this._wheres.push({column:_,operator:k,value:j,boolean:"and"});return this}orWhere(_,k,j){if(j===void 0)this._wheres.push({column:_,operator:"=",value:k,boolean:"or"});else this._wheres.push({column:_,operator:k,value:j,boolean:"or"});return this}whereIn(_,k){return this._wheres.push({column:_,operator:"in",value:k,boolean:"and"}),this}orWhereIn(_,k){return this._wheres.push({column:_,operator:"in",value:k,boolean:"or"}),this}whereNotIn(_,k){return this._wheres.push({column:_,operator:"not in",value:k,boolean:"and"}),this}orWhereNotIn(_,k){return this._wheres.push({column:_,operator:"not in",value:k,boolean:"or"}),this}whereNull(_){return this._wheres.push({column:_,operator:"=",value:null,boolean:"and"}),this}orWhereNull(_){return this._wheres.push({column:_,operator:"=",value:null,boolean:"or"}),this}whereNotNull(_){return this._wheres.push({column:_,operator:"!=",value:null,boolean:"and"}),this}orWhereNotNull(_){return this._wheres.push({column:_,operator:"!=",value:null,boolean:"or"}),this}whereLike(_,k){return this._wheres.push({column:_,operator:"like",value:k,boolean:"and"}),this}orWhereLike(_,k){return this._wheres.push({column:_,operator:"like",value:k,boolean:"or"}),this}whereNotLike(_,k){return this._wheres.push({column:_,operator:"not like",value:k,boolean:"and"}),this}orWhereNotLike(_,k){return this._wheres.push({column:_,operator:"not like",value:k,boolean:"or"}),this}whereRaw(_,...k){return this._wheres.push({raw:_,rawParams:k,boolean:"and"}),this}orWhereRaw(_,...k){return this._wheres.push({raw:_,rawParams:k,boolean:"or"}),this}whereGroup(_){return this._addGroup("and",_)}orWhereGroup(_){return this._addGroup("or",_)}_addGroup(_,k){let j=new k_(this._definition);if(k(j),j._wheres.length===0)return this;let d=[],O=j.buildWhereClauses(d);if(!O)return this;return this._wheres.push({raw:`(${O})`,rawParams:d,boolean:_}),this}whereBetween(_,k){return this._wheres.push({column:_,operator:">=",value:k[0],boolean:"and"}),this._wheres.push({column:_,operator:"<=",value:k[1],boolean:"and"}),this}whereNotBetween(_,k){return this._wheres.push({column:_,operator:"<",value:k[0],boolean:"and"}),this._wheres.push({column:_,operator:">",value:k[1],boolean:"or"}),this}when(_,k){if(_)return k(this);return this}orderBy(_,k="asc"){return this._orderBy.push({column:_,direction:k}),this}orderByDesc(_){return this.orderBy(_,"desc")}orderByAsc(_){return this.orderBy(_,"asc")}limit(_){return this._limit=_,this}take(_){return this.limit(_)}offset(_){return this._offset=_,this}skip(_){return this.offset(_)}select(..._){return this._select=_,this}with(..._){return this._withRelations=_,this}getWithRelations(){return this._withRelations}buildWhereClauses(_){let k=[];for(let j=0;j<this._wheres.length;j++){let d=this._wheres[j],O;if(d.raw){if(O=d.raw,d.rawParams&&d.rawParams.length>0)_.push(...d.rawParams)}else if(d.value===null)O=d.operator==="="?`${d.column} IS NULL`:`${d.column} IS NOT NULL`;else if(d.operator==="in"||d.operator==="not in"){let $=d.value;O=`${d.column} ${d.operator.toUpperCase()} (${$.map(()=>"?").join(", ")})`,_.push(...$)}else O=`${d.column} ${d.operator} ?`,_.push(d.value);k.push(j===0?O:`${d.boolean.toUpperCase()} ${O}`)}return k.join(" ")}buildQuery(){let _=[],k=`SELECT ${this._select.join(", ")} FROM ${this._definition.table}`;if(this._wheres.length>0)k+=` WHERE ${this.buildWhereClauses(_)}`;if(this._orderBy.length>0)k+=` ORDER BY ${this._orderBy.map((j)=>`${j.column} ${j.direction.toUpperCase()}`).join(", ")}`;if(this._limit!==void 0)k+=` LIMIT ${this._limit}`;if(this._offset!==void 0)k+=` OFFSET ${this._offset}`;return{sql:k,params:_}}toSql(){return this.buildQuery()}eagerLoadRelations(_){if(_.length===0||this._withRelations.length===0)return;let k=J_(),j=this._definition.primaryKey||"id";for(let d of this._withRelations){let O=`${this._definition.name}:${d}`,$=f8.get(O);if($===void 0)$=V6(this._definition,d),f8.set(O,$);if(!$)continue;if($.type==="hasMany"||$.type==="hasOne"){let Z=_.map((Y)=>Y.get(j)).filter((Y)=>Y!=null);if(Z.length===0)continue;let X=Z.map(()=>"?").join(", "),E=k.query(`SELECT * FROM ${$.relatedTable} WHERE ${$.foreignKey} IN (${X})`).all(...Z),F=Tk($.relatedModelName),G=F?.getDefinition?.()||F?.definition||this._definition;if($.type==="hasMany"){let Y=new Map;for(let S of E){let z=S[$.foreignKey];if(!Y.has(z))Y.set(z,[]);Y.get(z).push(S)}for(let S of _){let z=Y.get(S.get(j))||[];S.setRelation(d,z.map((U)=>new kk(G,U)))}}else{let Y=new Map;for(let S of E)Y.set(S[$.foreignKey],S);for(let S of _){let z=Y.get(S.get(j));S.setRelation(d,z?new kk(G,z):null)}}}if($.type==="belongsTo"){let Z=_.map((z)=>z._attributes[$.foreignKey]).filter((z)=>z!=null),X=[...new Set(Z)];if(X.length===0)continue;let E=X.map(()=>"?").join(", "),F=k.query(`SELECT * FROM ${$.relatedTable} WHERE ${$.localKey} IN (${E})`).all(...X),G=Tk($.relatedModelName),Y=G?.getDefinition?.()||G?.definition||this._definition,S=new Map;for(let z of F)S.set(z[$.localKey],z);for(let z of _){let U=z._attributes[$.foreignKey],Q=S.get(U);z.setRelation(d,Q?new kk(Y,Q):null)}}if($.type==="belongsToMany"){let Z=_.map((T)=>T.get(j)).filter((T)=>T!=null);if(Z.length===0)continue;if(!$.pivotTable||!$.pivotFkParent||!$.pivotFkRelated)continue;let X=Z.map(()=>"?").join(", "),E=k.query(`SELECT * FROM ${$.pivotTable} WHERE ${$.pivotFkParent} IN (${X})`).all(...Z);if(E.length===0){for(let T of _)T.setRelation(d,[]);continue}let F=[...new Set(E.map((T)=>T[$.pivotFkRelated]))].filter((T)=>T!=null),G=Tk($.relatedModelName),Y=G?.getDefinition?.()||G?.definition||this._definition,S=Y?.primaryKey||"id",z=[];if(F.length>0){let T=F.map(()=>"?").join(", ");z=k.query(`SELECT * FROM ${$.relatedTable} WHERE ${S} IN (${T})`).all(...F)}let U=new Map;for(let T of z)U.set(T[S],T);let Q=new Map;for(let T of E){let W=T[$.pivotFkParent];if(!Q.has(W))Q.set(W,[]);Q.get(W).push(T)}let I=new Set([$.pivotFkParent,$.pivotFkRelated]);for(let T of _){let W=T.get(j),C=(Q.get(W)||[]).map((f)=>{let N=U.get(f[$.pivotFkRelated]);if(!N)return null;let y=new kk(Y,N),B={};for(let[A,g]of Object.entries(f))if(!I.has(A))B[A]=g;return y.pivot=B,y}).filter((f)=>f!==null);T.setRelation(d,C)}}}}get(){let _=J_(),{sql:k,params:j}=this.buildQuery(),O=_.query(k).all(...j).map(($)=>new kk(this._definition,$));if(this._withRelations.length>0)this.eagerLoadRelations(O);return O}first(){return this._limit=1,this.get()[0]}firstOrFail(){let _=this.first();if(!_)throw Error(`No ${this._definition.name} found`);return _}last(){let _=this._definition.primaryKey||"id";return this._orderBy=[{column:_,direction:"desc"}],this._limit=1,this.get()[0]}count(){let _=J_(),k=[],j=`SELECT COUNT(*) as count FROM ${this._definition.table}`;if(this._wheres.length>0)j+=` WHERE ${this.buildWhereClauses(k)}`;return _.query(j).get(...k).count}exists(){return this.count()>0}doesntExist(){return this.count()===0}sole(){this._limit=2;let _=this.get();if(_.length===0)throw Error(`No ${this._definition.name} found`);if(_.length>1)throw Error(`Expected one ${this._definition.name}, found multiple`);return _[0]}increment(_,k=1){let j=J_(),d=[k],O=`UPDATE ${this._definition.table} SET ${_} = ${_} + ?`;if(this._definition.traits?.useTimestamps)O+=", updated_at = ?",d.push(new Date().toISOString());if(this._wheres.length>0){let $=this.buildWhereClauses(d);O+=` WHERE ${$}`}return j.run(O,d).changes}decrement(_,k=1){return this.increment(_,-k)}chunk(_,k){let j=0;while(!0){let d=new k_(this._definition);d._wheres=[...this._wheres],d._orderBy=[...this._orderBy],d._select=[...this._select],d._withRelations=[...this._withRelations],d._limit=_,d._offset=j*_;let O=d.get();if(O.length===0)break;if(k(O)===!1)break;if(O.length<_)break;j++}}paginate(_=1,k=15){let j=this.count(),d=Math.ceil(j/k);this._limit=k,this._offset=(_-1)*k;let O=this.get();return{data:O,total:j,page:_,perPage:k,lastPage:d,hasMorePages:_<d,isEmpty:O.length===0,from:O.length>0?(_-1)*k+1:null,to:O.length>0?(_-1)*k+O.length:null}}pluck(_){let k=J_(),j=[],d=`SELECT ${_} FROM ${this._definition.table}`;if(this._wheres.length>0)d+=` WHERE ${this.buildWhereClauses(j)}`;if(this._orderBy.length>0)d+=` ORDER BY ${this._orderBy.map(($)=>`${$.column} ${$.direction.toUpperCase()}`).join(", ")}`;if(this._limit!==void 0)d+=` LIMIT ${this._limit}`;if(this._offset!==void 0)d+=` OFFSET ${this._offset}`;return k.query(d).all(...j).map(($)=>$[_])}aggregate(_,k){let j=J_(),d=[],O=`SELECT ${_}(${k}) as v FROM ${this._definition.table}`;if(this._wheres.length>0)O+=` WHERE ${this.buildWhereClauses(d)}`;return j.query(O).get(...d)?.v??null}max(_){return this.aggregate("MAX",_)}min(_){return this.aggregate("MIN",_)}avg(_){return this.aggregate("AVG",_)||0}sum(_){return this.aggregate("SUM",_)||0}delete(){let _=J_(),k=[],j=`DELETE FROM ${this._definition.table}`;if(this._wheres.length>0)j+=` WHERE ${this.buildWhereClauses(k)}`;return _.run(j,k).changes}update(_){let k=J_(),j=Object.entries(_),d=j.map(([Z])=>`${Z} = ?`).join(", "),O=j.map(([,Z])=>Z);if(this._definition.traits?.useTimestamps)O.push(new Date().toISOString());let $=`UPDATE ${this._definition.table} SET ${d}${this._definition.traits?.useTimestamps?", updated_at = ?":""}`;if(this._wheres.length>0)$+=` WHERE ${this.buildWhereClauses(O)}`;return k.run($,O).changes}}function m8(_){let k={query:()=>new k_(_),where(j,d,O){return new k_(_).where(j,d,O)},orWhere(j,d,O){return new k_(_).orWhere(j,d,O)},whereIn(j,d){return new k_(_).whereIn(j,d)},whereNotIn(j,d){return new k_(_).whereNotIn(j,d)},whereNull(j){return new k_(_).whereNull(j)},whereNotNull(j){return new k_(_).whereNotNull(j)},whereLike(j,d){return new k_(_).whereLike(j,d)},orderBy(j,d="asc"){return new k_(_).orderBy(j,d)},orderByDesc(j){return new k_(_).orderByDesc(j)},select(...j){return new k_(_).select(...j)},with(...j){return new k_(_).with(...j)},limit:(j)=>new k_(_).limit(j),take:(j)=>new k_(_).take(j),skip:(j)=>new k_(_).skip(j),find(j){let d=J_(),O=_.primaryKey||"id",$=`SELECT * FROM ${_.table} WHERE ${O} = ?`,Z=F0.get($);if(!Z)Z=d.prepare($),F0.set($,Z);let X=Z.get(j);return X?new kk(_,X):void 0},findOrFail(j){let d=k.find(j);if(!d)throw Error(`${_.name} with id ${j} not found`);return d},findMany(j){let d=J_(),O=_.primaryKey||"id";return d.query(`SELECT * FROM ${_.table} WHERE ${O} IN (${j.map(()=>"?").join(", ")})`).all(...j).map((Z)=>new kk(_,Z))},all:()=>new k_(_).get(),first:()=>new k_(_).first(),firstOrFail:()=>new k_(_).firstOrFail(),last:()=>new k_(_).last(),count:()=>new k_(_).count(),exists:()=>new k_(_).exists(),doesntExist:()=>new k_(_).doesntExist(),paginate:(j,d)=>new k_(_).paginate(j,d),whereBetween(j,d){return new k_(_).whereBetween(j,d)},whereNotBetween(j,d){return new k_(_).whereNotBetween(j,d)},create(j){let d=new kk(_,j);return d.save(),d},createMany(j){return j.map((d)=>this.create(d))},updateOrCreate(j,d){let O=new k_(_);for(let[Z,X]of Object.entries(j))O=O.where(Z,X);let $=O.first();if($)return $.update(d),$;return this.create({...j,...d})},firstOrCreate(j,d){let O=new k_(_);for(let[Z,X]of Object.entries(j))O=O.where(Z,X);return O.first()||this.create({...j,...d})},destroy(j){let d=J_(),O=_.primaryKey||"id";return d.run(`DELETE FROM ${_.table} WHERE ${O} = ?`,[j]).changes>0},remove(j){return this.destroy(j)},truncate(){J_().run(`DELETE FROM ${_.table}`)},getDefinition:()=>_,getTable:()=>_.table,make(j={}){return new kk(_,j)},latest:(j="created_at")=>new k_(_).orderByDesc(j),oldest:(j="created_at")=>new k_(_).orderBy(j,"asc"),max:(j)=>new k_(_).max(j),min:(j)=>new k_(_).min(j),avg:(j)=>new k_(_).avg(j),sum:(j)=>new k_(_).sum(j),pluck(j){return new k_(_).pluck(j)}};return new Proxy(k,{get(j,d){if(typeof d==="string"&&d.startsWith("where")&&d.length>5){let O=d.slice(5),$=O.charAt(0).toLowerCase()+O.slice(1);if($ in _.attributes||$==="id"||$===_.primaryKey)return(Z)=>new k_(_).where($,Z)}return Reflect.get(j,d)}})}var FO=null,B1=null,C8,h8,f8,F0,W6=r(()=>{C8=new Map,h8=new Map,f8=new Map,F0=new Map}),K6={};q8(K6,{registerBrowserModels:()=>sU,hasModel:()=>gU,getModelRegistry:()=>mU,getModel:()=>vU,getAllModels:()=>AU,defineModel:()=>pU,clearModelRegistry:()=>uU});function vU(_){return Fj.get(_)}function AU(){return[...Fj.values()]}function mU(){return Object.fromEntries(Fj)}function gU(_){return Fj.has(_)}function uU(){Fj.clear()}function lU(){return typeof window<"u"&&typeof document<"u"}function pU(_){let k;if(lU())k=sz(_);else{let j=m8(_);k=Object.assign(j,{definition:_,getDefinition:()=>_,getTable:()=>_.table,getName:()=>_.name})}return Fj.set(_.name,k),k}function sU(_){if(typeof window>"u")return;window.StacksBrowser={...window.StacksBrowser,..._}}var Fj,hO=r(()=>{r5(),W6(),Fj=new Map});var g8=()=>{};var oU,n6=r(()=>{g8(),oU={simpleEntity:(_,k="id")=>({name:_,pkPattern:`${_.toUpperCase()}#\${${k}}`,skPattern:"METADATA",keyFields:[k]}),oneToMany:(_,k,j="id",d="id")=>({parent:{name:_,pkPattern:`${_.toUpperCase()}#\${${j}}`,skPattern:"METADATA",keyFields:[j]},child:{name:k,pkPattern:`${_.toUpperCase()}#\${${j}}`,skPattern:`${k.toUpperCase()}#\${${d}}`,keyFields:[j,d]}}),manyToMany:(_,k,j="id",d="relatedId")=>({entity:{name:_,pkPattern:`${_.toUpperCase()}#\${${j}}`,skPattern:"METADATA",keyFields:[j]},relation:{name:k,pkPattern:`${_.toUpperCase()}#\${${j}}`,skPattern:`${k.toUpperCase()}#\${${d}}`,keyFields:[j,d],indexes:[{name:"GSI1",pkPattern:`${_.toUpperCase()}#\${${d}}`,skPattern:`${k.toUpperCase()}#\${${j}}`}]}}),hierarchical:(_,k="rootId",j="path")=>({name:_,pkPattern:`ROOT#\${${k}}`,skPattern:`PATH#\${${j}}`,keyFields:[k,j]})}});var rU=r(()=>{g8(),n6()});async function J6(_){let k=_.cwd??kQ.cwd(),j=_.modelsDir.startsWith("/")?_.modelsDir:`${k}/${_.modelsDir}`,d={},O=tU(j);for(let $ of O){let Z=`${j}/${$}`;if(aU(Z).isDirectory())continue;let E=_Q(Z);if(![".ts",".mts",".cts",".js",".mjs",".cjs"].includes(E))continue;let F=`?t=${Date.now()}-${Math.random().toString(36).slice(2)}`,G=await import(`${Z}${F}`),Y=G.default??G,S=Y.definition??Y.getDefinition?.()??Y,z=eU($,E),U=S.name??z;d[U]={...S,name:U}}return d}var jQ=()=>{};function dQ(_){let k={},j={},d={},O={},$={};for(let Z of Object.keys(_)){let X=_[Z],E=X.definition??X.getDefinition?.()??X,F=E.table||`${String(E.name).toLowerCase()}s`;k[Z]=F,j[F]=Z,d[F]=E.primaryKey??"id";let G=(z)=>{if(!z)return{};if(Array.isArray(z)){let U={};for(let Q of z)U[Q]=Q;return U}return z},Y=(z)=>{if(!z)return{};if(Array.isArray(z)){let U={};for(let Q of z)if(typeof Q==="string")U[Q]=Q;else if(Q&&typeof Q==="object"&&typeof Q.model==="string")U[Q.model]=Q;return U}return z},S=(z)=>{if(!z)return{};return z};if(O[F]={hasOne:G(E.hasOne),hasMany:G(E.hasMany),belongsTo:G(E.belongsTo),belongsToMany:Y(E.belongsToMany),hasOneThrough:S(E.hasOneThrough),hasManyThrough:S(E.hasManyThrough),morphOne:G(E.morphOne),morphMany:G(E.morphMany),morphTo:E.morphTo,morphToMany:G(E.morphToMany),morphedByMany:G(E.morphedByMany)},E.scopes&&typeof E.scopes==="object"){$[F]={};for(let z of Object.keys(E.scopes)){let U=E.scopes[z];if(typeof U==="function")$[F][z]=U}}}return{modelToTable:k,tableToModel:j,primaryKeys:d,relations:O,scopes:$,models:_}}function zO(_){return _.replace(/([A-Z]+)([A-Z][a-z])/g,"$1_$2").replace(/([a-z\d])([A-Z])/g,"$1_$2").replace(/(\d)([A-Z])/gi,"$1_$2").toLowerCase()}function ZQ(_){let k=_;while(k!==g5(k)){if(I6(u8(k,"package.json")))return k;k=g5(k)}return D6.cwd()}function XQ(){let _=ZQ(D6.cwd()),k=u8(_,"database","migrations");if(!I6(k))OQ(k,{recursive:!0}),console.log(`-- Created SQL directory: ${k}`);return k}function Nk(_,k){if(!_)return!1;let j=XQ();c1++;let O=`${l8?String(c1).padStart(10,"0"):String(Math.floor(Date.now()/1000)+c1)}-${k}.sql`,$=u8(j,O);return $Q($,_),console.log(`-- Migration file created: ${O}`),ik++,!0}function u5(_){if(_.endsWith("_id"))return"bigint";if(_.endsWith("_at"))return"datetime";if(_.startsWith("is_")||_.startsWith("has_"))return"boolean";return}function l5(_){if(typeof _==="string"||typeof _==="number"||typeof _==="boolean"||typeof _==="bigint"||_ instanceof Date)return _;return}function EQ(_){if(_&&typeof _==="object"&&"name"in _){let k=_;if(k.name==="enum"||k.getRules&&Array.isArray(k.getRules())){if(k.enumValues&&Array.isArray(k.enumValues))return k.enumValues.map((j)=>String(j));if(k._values&&Array.isArray(k._values))return k._values.map((j)=>String(j));if(k.values&&Array.isArray(k.values))return k.values.map((j)=>String(j))}}if(_&&typeof _==="object"){let k=_,j=k.allowedValues||k.enumValues||k._values||k.values;if(Array.isArray(j)&&j.length>0)return j.map((d)=>String(d))}return}function GQ(_){if(!_?.rules||!Array.isArray(_.rules))return;for(let k of _.rules)if(k?.name==="max"||k?.name==="maxLength"){if(k.params&&typeof k.params.max==="number")return k.params.max;if(Array.isArray(k.args)&&typeof k.args[0]==="number")return k.args[0];if(typeof k.value==="number")return k.value;if(typeof k.expectedValue==="number")return k.expectedValue}return}function FQ(_){if(!_||typeof _!=="object")return;let k=_;if(k.name)switch(String(k.name).toLowerCase()){case"string":case"text":{let d=GQ(k);return d&&d>255?"text":"string"}case"integer":case"int":return"integer";case"bigint":return"bigint";case"float":return"float";case"number":return"integer";case"double":return"double";case"decimal":return"decimal";case"boolean":case"bool":return"boolean";case"date":return"date";case"datetime":case"timestamp":return"datetime";case"json":return"json";case"enum":return"enum"}if(k.type){let j=String(k.type).toLowerCase();if(j==="string"||j==="text")return"string";if(j==="integer"||j==="int")return"integer";if(j==="bigint")return"bigint";if(j==="float")return"float";if(j==="number")return"integer";if(j==="boolean")return"boolean";if(j==="date")return"date";if(j==="datetime")return"datetime";if(j==="json")return"json"}return}function zQ(_){if(!_)return[];if(Array.isArray(_))return _;if(typeof _==="object")return Object.values(_);return[]}function R6(_,k){let j=dQ(_),d=[];for(let Z of Object.keys(_)){let X=_[Z],E=X.table||`${String(X.name).toLowerCase()}s`,F=X.primaryKey??"id",G=X.autoIncrement!==!1,Y=X.attributes??{},S=[],z=[];if(!Y[F])S.push({name:zO(F),type:"bigint",isPrimaryKey:!0,isUnique:!1,isNullable:!1,hasDefault:!1});for(let J of Object.keys(Y)){let C=Y[J],f=zO(J),N=!0,y,B,A=J===F;if(y=FQ(C.validation?.rule),!y||y==="enum"){let j_=EQ(C.validation?.rule);if(j_&&j_.length>0)y="enum",B=j_}if(!y)y=u5(f);if(!y){let j_=l5(C.default);if(typeof j_==="string")y=j_.length>255?"text":"string";else if(typeof j_==="number")y=Number.isInteger(j_)?"integer":"float";else if(typeof j_==="boolean")y="boolean";else if(typeof j_==="bigint")y="bigint";else if(j_ instanceof Date)y="datetime"}if(!y)y=A?"bigint":"string";let g={name:f,type:y,isPrimaryKey:A,isUnique:Boolean(C.unique),isNullable:!0,hasDefault:typeof C.default<"u",defaultValue:l5(C.default),enumValues:B};if(f.endsWith("_id")&&C.foreignKey!==!1)if(typeof C.foreignKey==="object"&&C.foreignKey!==null){let j_=C.foreignKey;if(g.references={table:j_.table,column:j_.column??"id",onDelete:j_.onDelete,onUpdate:j_.onUpdate},j_.nullable!==void 0)g.isNullable=j_.nullable}else{let a_=f.replace(/_id$/,"").replace(/(^|_)([a-z])/g,(gk,T_,x)=>x.toUpperCase()),Ik=j.modelToTable[a_];if(Ik){let gk=j.primaryKeys[Ik]??"id";g.references={table:Ik,column:gk}}}S.push(g)}let U=zQ(X.belongsTo);for(let J of U){let C=`${zO(J)}_id`;if(S.some((y)=>y.name===C))continue;let f=j.modelToTable[J];if(!f)continue;let N=j.primaryKeys[f]??"id";S.push({name:C,type:"bigint",isPrimaryKey:!1,isUnique:!1,isNullable:!0,hasDefault:!1,references:{table:f,column:N}})}let Q=X.traits;if(Q?.useTimestamps??Q?.timestampable??!1){if(!S.some((J)=>J.name==="created_at"))S.push({name:"created_at",type:"datetime",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!0,defaultValue:"CURRENT_TIMESTAMP"});if(!S.some((J)=>J.name==="updated_at"))S.push({name:"updated_at",type:"datetime",isPrimaryKey:!1,isUnique:!1,isNullable:!0,hasDefault:!1})}if(Q?.useSoftDeletes??Q?.softDeletable??!1){if(!S.some((J)=>J.name==="deleted_at"))S.push({name:"deleted_at",type:"datetime",isPrimaryKey:!1,isUnique:!1,isNullable:!0,hasDefault:!1})}if(Q?.useUuid??!1){if(!S.some((J)=>J.name==="uuid"))S.push({name:"uuid",type:"string",isPrimaryKey:!1,isUnique:!0,isNullable:!0,hasDefault:!1})}for(let J of X.indexes??[])z.push({name:J.name,columns:J.columns.map((C)=>zO(C)),type:J.unique?"unique":"index",where:J.where});for(let J of S)if(J.isUnique&&!J.isPrimaryKey)z.push({name:`${E}_${J.name}_unique`,columns:[J.name],type:"unique"});d.push({table:E,columns:S,indexes:z})}let O=new Set(d.map((Z)=>Z.table));function $(Z){if(!O.has(Z.table))O.add(Z.table),d.push(Z)}for(let Z of Object.keys(_)){let X=_[Z],E=X?.traits??{},F=X.table||`${String(X.name).toLowerCase()}s`,G=F.replace(/s$/,"");if(E.likeable){let Y=typeof E.likeable==="object"?E.likeable:{},S=Y.table||`${F}_likes`,z=Y.foreignKey||`${G}_id`;$({table:S,columns:[{name:"id",type:"bigint",isPrimaryKey:!0,isUnique:!1,isNullable:!1,hasDefault:!1},{name:"user_id",type:"bigint",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!1,references:{table:"users",column:"id"}},{name:z,type:"bigint",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!1,references:{table:F,column:"id"}},{name:"created_at",type:"datetime",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!0,defaultValue:"CURRENT_TIMESTAMP"},{name:"updated_at",type:"datetime",isPrimaryKey:!1,isUnique:!1,isNullable:!0,hasDefault:!1}],indexes:[{name:`${S}_user_target_unique`,columns:["user_id",z],type:"unique"}]})}if(E.taggable)$({table:"taggable",columns:[{name:"id",type:"bigint",isPrimaryKey:!0,isUnique:!1,isNullable:!1,hasDefault:!1},{name:"name",type:"string",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!1},{name:"slug",type:"string",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!1},{name:"description",type:"text",isPrimaryKey:!1,isUnique:!1,isNullable:!0,hasDefault:!1},{name:"order",type:"integer",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!0,defaultValue:0},{name:"is_active",type:"boolean",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!0,defaultValue:!0},{name:"taggable_id",type:"bigint",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!1},{name:"taggable_type",type:"string",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!1},{name:"created_at",type:"datetime",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!0,defaultValue:"CURRENT_TIMESTAMP"},{name:"updated_at",type:"datetime",isPrimaryKey:!1,isUnique:!1,isNullable:!0,hasDefault:!1}],indexes:[{name:"taggable_target_index",columns:["taggable_id","taggable_type"],type:"index"}]});if(E.categorizable)$({table:"categorizable",columns:[{name:"id",type:"bigint",isPrimaryKey:!0,isUnique:!1,isNullable:!1,hasDefault:!1},{name:"name",type:"string",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!1},{name:"slug",type:"string",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!1},{name:"description",type:"text",isPrimaryKey:!1,isUnique:!1,isNullable:!0,hasDefault:!1},{name:"created_at",type:"datetime",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!0,defaultValue:"CURRENT_TIMESTAMP"},{name:"updated_at",type:"datetime",isPrimaryKey:!1,isUnique:!1,isNullable:!0,hasDefault:!1}],indexes:[{name:"categorizable_slug_unique",columns:["slug"],type:"unique"}]}),$({table:"categorizable_models",columns:[{name:"id",type:"bigint",isPrimaryKey:!0,isUnique:!1,isNullable:!1,hasDefault:!1},{name:"category_id",type:"bigint",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!1,references:{table:"categorizable",column:"id"}},{name:"categorizable_id",type:"bigint",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!1},{name:"categorizable_type",type:"string",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!1},{name:"created_at",type:"datetime",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!0,defaultValue:"CURRENT_TIMESTAMP"}],indexes:[{name:"categorizable_models_target_index",columns:["categorizable_id","categorizable_type"],type:"index"}]})}for(let Z of Object.keys(_)){let X=_[Z],E=X?.belongsToMany;if(!E||typeof E!=="object"||Array.isArray(E))continue;let F=X.table||`${String(X.name).toLowerCase()}s`,G=F.replace(/s$/,"");for(let[Y,S]of Object.entries(E)){let z=S;if(!z||typeof z!=="object")continue;if(z.through)continue;let U=z.pivot;if(!U||!U.columns&&!U.timestamps&&!U.uniques)continue;let Q=z.model,T=_[Q]?.table||`${String(Q).toLowerCase()}s`,W=T.replace(/s$/,""),J=z.table||[G,W].sort().join("_"),C=z.foreignKey||`${G}_id`,f=z.relatedKey||`${W}_id`,N=[{name:"id",type:"bigint",isPrimaryKey:!0,isUnique:!1,isNullable:!1,hasDefault:!1},{name:C,type:"bigint",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!1,references:{table:F,column:"id"}},{name:f,type:"bigint",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!1,references:{table:T,column:"id"}}];if(U.columns)for(let[A,g]of Object.entries(U.columns)){let j_=g,a_=u5(A)??"string";N.push({name:A,type:a_,isPrimaryKey:!1,isUnique:!1,isNullable:j_?.nullable??!1,hasDefault:j_?.default!==void 0,defaultValue:j_?.default})}if(U.timestamps)N.push({name:"created_at",type:"datetime",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!0,defaultValue:"CURRENT_TIMESTAMP"}),N.push({name:"updated_at",type:"datetime",isPrimaryKey:!1,isUnique:!1,isNullable:!0,hasDefault:!1});let y=[],B=U.uniques&&U.uniques.length>0?U.uniques:[[C,f]];for(let A=0;A<B.length;A++){let g=B[A];y.push({name:`${J}_${g.join("_")}_unique${A>0?`_${A}`:""}`,columns:[...g],type:"unique"})}$({table:J,columns:N,indexes:y})}}return{dialect:k.dialect,tables:d}}function w6(_){c1=0,ik=0,ok=0,l8=!0;let k=[],j=gj(_.dialect);for(let O of _.tables){let $=[],Z=new Set;for(let F of O.columns)if(F.type==="enum"&&F.enumValues&&F.enumValues.length>0){let G=`${F.name}_type`;if(!Z.has(G)){let Y=j.createEnumType(G,F.enumValues);if(Y)$.push(Y);Z.add(G)}}let X=j.createTable(O);$.push(X),k.push(...$);let E=$.join(`
|
|
132
|
-
|
|
133
|
-
`);Nk(E,`create-${O.table}-table`)}for(let O of _.tables)for(let $ of O.columns)if($.references){let Z=j.addForeignKey(O.table,$.name,$.references.table,$.references.column,$.references.onDelete,$.references.onUpdate);k.push(Z),Nk(Z,`alter-${O.table}-${$.name}`)}for(let O of _.tables)for(let $ of O.indexes){let Z=j.createIndex(O.table,$);k.push(Z),Nk(Z,`create-${$.name}-index-in-${O.table}`)}if(ik+ok===0)console.log("-- Nothing to migrate");else{let O=[];if(ik>0)O.push(`${ik} created`);if(ok>0)O.push(`${ok} updated`);console.log(`-- Migration files: ${O.join(", ")}`)}return k}function SQ(_){let k=lz("crypto");function j(O){if(O==null||typeof O!=="object"||O instanceof Date)return O;if(Array.isArray(O))return O.map((Z)=>j(Z));let $={};for(let Z of Object.keys(O).sort())$[Z]=j(O[Z]);return $}let d=JSON.stringify(j(_));return k.createHash("sha256").update(d).digest("hex")}function p5(_){let k={};for(let j of _)k[j.table]=j;return k}function SO(_){let k={};for(let j of _)k[j.name]=j;return k}function YQ(_,k){if(_.type!==k.type)return!0;if(_.isNullable!==k.isNullable)return!0;if(_.hasDefault!==k.hasDefault)return!0;if(_.defaultValue!==k.defaultValue)return!0;if(_.isUnique!==k.isUnique)return!0;if(_.type==="enum"&&k.type==="enum"){let j=(_.enumValues||[]).sort().join(","),d=(k.enumValues||[]).sort().join(",");if(j!==d)return!0}return!1}function s5(_){let k={};for(let j of _){let d=`${j.type}:${j.name}:${j.columns.join(",")}`;k[d]=j}return k}function LQ(_,k){if(!_||_.dialect!==k.dialect)return w6(k);c1=0,ik=0,ok=0,l8=!1;let j=[],d=gj(k.dialect),O=p5(_.tables),$=p5(k.tables);for(let E of Object.keys(O))if(!$[E]){let F=d.dropTable(E);j.push(F),Nk(F,`drop-${E}-table`),console.log(`-- Detected dropped table: ${E}`)}for(let E of Object.keys($))if(!O[E]){let F=$[E],G=[],Y=new Set;for(let U of F.columns)if(U.type==="enum"&&U.enumValues&&U.enumValues.length>0){let Q=`${U.name}_type`;if(!Y.has(Q)){let I=d.createEnumType(Q,U.enumValues);if(I)G.push(I);Y.add(Q)}}let S=d.createTable(F);G.push(S),j.push(...G);let z=G.join(`
|
|
134
|
-
|
|
135
|
-
`);Nk(z,`create-${F.table}-table`)}for(let E of Object.keys($))if(!O[E]){let F=$[E];for(let G of F.indexes){let Y=d.createIndex(F.table,G);j.push(Y),Nk(Y,`create-${G.name}-index-in-${F.table}`)}}for(let E of Object.keys($))if(!O[E]){let F=$[E];for(let G of F.columns)if(G.references){let Y=d.addForeignKey(F.table,G.name,G.references.table,G.references.column,G.references.onDelete,G.references.onUpdate);j.push(Y),Nk(Y,`alter-${F.table}-${G.name}`)}}let Z=new Set;for(let E of Object.keys($)){let F=O[E],G=$[E];if(!F)continue;let Y=SO(F.columns),S=SO(G.columns);for(let z of Object.keys(S))if(!Y[z]){let U=S[z];if(U.type==="enum"&&U.enumValues&&U.enumValues.length>0){let Q=`${U.name}_type`;if(!Z.has(Q)){let I=d.createEnumType(Q,U.enumValues);if(I)j.push(I),Nk(I,`create-${Q}-enum`);Z.add(Q)}}}}for(let E of Object.keys($)){let F=O[E],G=$[E];if(!F)continue;let Y=SO(F.columns),S=SO(G.columns),z=s5(F.indexes),U=s5(G.indexes),Q=[],I=!1;for(let T of Object.keys(z))if(!U[T]){let W=z[T],J=d.dropIndex(G.table,W.name);Q.push(J),j.push(J),console.log(`-- Detected dropped index: ${W.name} from ${G.table}`),I=!0}for(let T of Object.keys(Y))if(!S[T]){let W=d.dropColumn(G.table,T);Q.push(W),j.push(W),console.log(`-- Detected dropped column: ${G.table}.${T}`),I=!0}for(let T of Object.keys(S))if(Y[T]&&S[T]){let W=Y[T],J=S[T];if(YQ(W,J)){let C=d.modifyColumn(G.table,J);Q.push(C),j.push(C),console.log(`-- Detected column type change: ${G.table}.${T} (${W.type} -> ${J.type})`),I=!0}}for(let T of Object.keys(S))if(!Y[T]){let W=S[T],J=d.addColumn(G.table,W);if(Q.push(J),j.push(J),console.log(`-- Detected new column: ${G.table}.${W.name}`),I=!0,W.references){let C=d.addForeignKey(G.table,W.name,W.references.table,W.references.column,W.references.onDelete,W.references.onUpdate);Q.push(C),j.push(C)}}for(let T of Object.keys(U))if(!z[T]){let W=U[T],J=d.createIndex(G.table,W);Q.push(J),j.push(J),console.log(`-- Detected new index: ${W.name} in ${G.table}`),I=!0}if(I){let T=Q.join(`
|
|
136
|
-
|
|
137
|
-
`);Nk(T,`alter-${G.table}-table`)}}if(ik+ok===0)console.log("-- Nothing to migrate");else{let E=[];if(ik>0)E.push(`${ik} created`);if(ok>0)E.push(`${ok} updated`);console.log(`-- Migration files: ${E.join(", ")}`)}if(j.length===0)return["-- No changes detected"];return j}var c1=0,ik=0,ok=0,l8=!0,PQ=r(()=>{P0()});var i_=r(async()=>{hO(),hO(),LP(),r5(),L0(),hO(),await Wk(),P0(),g8(),n6(),rU(),jS(),jQ(),PQ(),W6()});await i_();import{log as Qj}from"@stacksjs/logging";import{db as UQ,sql as QQ}from"@stacksjs/database";var lj=UQ;function p8(_,k){if(typeof _!=="number"||!Number.isFinite(_)||_<=0)throw Error(`[orm/taggable] ${k} requires a positive numeric id (received ${String(_)})`)}function M6(_){return{async tags(k){return p8(k,"tags"),await lj.selectFrom("taggable").where("taggable_id","=",k).where("taggable_type","=",_).selectAll().execute()},async tagCount(k){p8(k,"tagCount");let j=await lj.selectFrom("taggable").select(QQ`count(*) as count`).where("taggable_id","=",k).where("taggable_type","=",_).executeTakeFirst();return Number(j?.count)||0},async addTag(k,j){if(p8(k,"addTag"),!j||typeof j.name!=="string"||j.name.trim().length===0)throw Error("[orm/taggable] addTag requires a non-empty tag.name");return await lj.insertInto("taggable").values({...j,taggable_id:k,taggable_type:_,slug:j.name.toLowerCase().replace(/[^a-z0-9]+/g,"-"),order:0,is_active:!0,created_at:new Date().toISOString(),updated_at:new Date().toISOString()}).returningAll().executeTakeFirst()},async activeTags(k){return await lj.selectFrom("taggable").where("taggable_id","=",k).where("taggable_type","=",_).where("is_active","=",!0).selectAll().execute()},async inactiveTags(k){return await lj.selectFrom("taggable").where("taggable_id","=",k).where("taggable_type","=",_).where("is_active","=",!1).selectAll().execute()},async removeTag(k,j){await lj.deleteFrom("taggable").where("taggable_id","=",k).where("taggable_type","=",_).where("id","=",j).execute()}}}import{db as VQ}from"@stacksjs/database";var ek=VQ;function C6(_){async function k(j){return(await ek.selectFrom("categorizable_models").where("categorizable_id","=",j).where("categorizable_type","=",_).selectAll().execute()).map((O)=>O.category_id)}return{async categories(j){let d=await k(j);if(d.length===0)return[];return await ek.selectFrom("categorizable").where("id","in",d).selectAll().execute()},async categoryCount(j){return(await k(j)).length},async addCategory(j,d){let O=await ek.selectFrom("categorizable").where("name","=",d.name).selectAll().executeTakeFirst();if(!O)O=await ek.insertInto("categorizable").values({name:d.name,description:d.description,slug:d.name.toLowerCase().replace(/[^a-z0-9]+/g,"-"),is_active:!0,created_at:new Date().toISOString(),updated_at:new Date().toISOString()}).returningAll().executeTakeFirst();return await ek.insertInto("categorizable_models").values({categorizable_id:j,categorizable_type:_,category_id:O.id,created_at:new Date().toISOString(),updated_at:new Date().toISOString()}).returningAll().executeTakeFirst()},async activeCategories(j){let d=await k(j);if(d.length===0)return[];return await ek.selectFrom("categorizable").where("id","in",d).where("is_active","=",!0).selectAll().execute()},async inactiveCategories(j){let d=await k(j);if(d.length===0)return[];return await ek.selectFrom("categorizable").where("id","in",d).where("is_active","=",!1).selectAll().execute()},async removeCategory(j,d){await ek.deleteFrom("categorizable_models").where("categorizable_id","=",j).where("categorizable_type","=",_).where("category_id","=",d).execute()}}}import{db as TQ,sql as WQ}from"@stacksjs/database";var pj=TQ;function h6(_,k){if(typeof _!=="number"||!Number.isFinite(_)||_<=0)throw Error(`[orm/commentable] ${k} requires a positive numeric id (received ${String(_)})`)}function f6(_){return{async comments(k){return h6(k,"comments"),await pj.selectFrom("comments").where("commentables_id","=",k).where("commentables_type","=",_).selectAll().execute()},async commentCount(k){let j=await pj.selectFrom("comments").select(WQ`count(*) as count`).where("commentables_id","=",k).where("commentables_type","=",_).executeTakeFirst();return Number(j?.count)||0},async addComment(k,j){if(h6(k,"addComment"),!j||typeof j.title!=="string"||j.title.trim().length===0)throw Error("[orm/commentable] addComment requires a non-empty comment.title");if(typeof j.body!=="string"||j.body.trim().length===0)throw Error("[orm/commentable] addComment requires a non-empty comment.body");return await pj.insertInto("comments").values({...j,commentables_id:k,commentables_type:_,status:"pending",created_at:new Date().toISOString(),updated_at:new Date().toISOString()}).returningAll().executeTakeFirst()},async approvedComments(k){return await pj.selectFrom("comments").where("commentables_id","=",k).where("commentables_type","=",_).where("status","=","approved").selectAll().execute()},async pendingComments(k){return await pj.selectFrom("comments").where("commentables_id","=",k).where("commentables_type","=",_).where("status","=","pending").selectAll().execute()},async rejectedComments(k){return await pj.selectFrom("comments").where("commentables_id","=",k).where("commentables_type","=",_).where("status","=","rejected").selectAll().execute()}}}import{db as fV}from"@stacksjs/database";var N$=fV;function dz(_){return{async createStripeUser(k,j){let{manageCustomer:d}=await import("@stacksjs/payments");return await d.createStripeCustomer(k,j)},async updateStripeUser(k,j){let{manageCustomer:d}=await import("@stacksjs/payments");return await d.updateStripeCustomer(k,j)},async deleteStripeUser(k){let{manageCustomer:j}=await import("@stacksjs/payments");return await j.deleteStripeUser(k)},async createOrGetStripeUser(k,j){let{manageCustomer:d}=await import("@stacksjs/payments");return await d.createOrGetStripeUser(k,j)},async retrieveStripeUser(k){let{manageCustomer:j}=await import("@stacksjs/payments");return await j.retrieveStripeUser(k)},async defaultPaymentMethod(k){let{managePaymentMethod:j}=await import("@stacksjs/payments");return await j.retrieveDefaultPaymentMethod(k)},async setDefaultPaymentMethod(k,j){let{managePaymentMethod:d}=await import("@stacksjs/payments");return await d.setDefaultPaymentMethod(k,j)},async addPaymentMethod(k,j){let{managePaymentMethod:d}=await import("@stacksjs/payments");return await d.addPaymentMethod(k,j)},async paymentMethods(k,j){let{managePaymentMethod:d}=await import("@stacksjs/payments");return await d.listPaymentMethods(k,j)},async newSubscription(k,j,d,O={}){let{manageSubscription:$}=await import("@stacksjs/payments"),Z=await $.create(k,j,d,O),E=Z.latest_invoice?.payment_intent;return{subscription:Z,paymentIntent:E}},async updateSubscription(k,j,d,O={}){let{manageSubscription:$}=await import("@stacksjs/payments"),Z=await $.update(k,j,d,O),E=Z.latest_invoice?.payment_intent;return{subscription:Z,paymentIntent:E}},async cancelSubscription(k,j,d={}){let{manageSubscription:O}=await import("@stacksjs/payments");return{subscription:await O.cancel(j,d)}},async activeSubscription(k){let{manageSubscription:j}=await import("@stacksjs/payments"),d=await N$.selectFrom("subscriptions").where("user_id","=",k.id).where("provider_status","=","active").selectAll().executeTakeFirst();if(d){let O=await j.retrieve(k,d?.provider_id||"");return{subscription:d,providerSubscription:O}}return},async checkout(k,j,d={}){let{manageCheckout:O,manageCustomer:$}=await import("@stacksjs/payments"),Z={};if(d.enableTax)Z.automatic_tax={enabled:!0},delete d.enableTax;if(d.allowPromotions)Z.allow_promotion_codes=!0,delete d.allowPromotions;let F={...{mode:"payment",customer:(await $.createOrGetStripeUser(k,{})).id,line_items:j.map((G)=>({price:G.priceId,quantity:G.quantity||1}))},...Z,...d};return await O.create(k,F)},async createSetupIntent(k,j={}){let{manageSetupIntent:d}=await import("@stacksjs/payments");return await d.create(k,j)},async subscriptionHistory(k){let{manageInvoice:j}=await import("@stacksjs/payments");return await j.list(k)},async transactionHistory(k){let{manageTransaction:j}=await import("@stacksjs/payments");return await j.list(k)},async connectAccount(k,j={}){let d=j.accountColumn||"stripe_account_id",O=(k._attributes??k)[d];if(!O)return null;let $=await wd();try{return await $.accounts.retrieve(O)}catch{return null}},async createConnectAccount(k,j={}){let d=j.accountColumn||"stripe_account_id",O=k._attributes??k,$=O[d],Z=await wd();if(!$){let X=await Z.accounts.create({type:j.type??"express",email:j.email??O.email,country:j.country??"US",capabilities:j.capabilities??{card_payments:{requested:!0},transfers:{requested:!0}}});$=X.id;let E=j.modelTable||_;return await N$.updateTable(E).set({[d]:$}).where("id","=",Number(O.id)).execute(),X}return await Z.accounts.retrieve($)},async connectOnboardLink(k,j){let d=j.accountColumn||"stripe_account_id",$=(k._attributes??k)[d];if(!$)throw Error("connectOnboardLink: model has no Stripe Connect account; call createConnectAccount first");return{url:(await(await wd()).accountLinks.create({account:$,refresh_url:j.refreshUrl,return_url:j.returnUrl,type:j.type??"account_onboarding"})).url,accountId:$}},async syncConnectStatus(k,j={}){let d=j.accountColumn||"stripe_account_id",O=j.chargesColumn||"charges_enabled",$=j.payoutsColumn||"payouts_enabled",Z=k._attributes??k,X=Z[d];if(!X)return{chargesEnabled:!1,payoutsEnabled:!1};let F=await(await wd()).accounts.retrieve(X),G=!!F.charges_enabled,Y=!!F.payouts_enabled,S=j.modelTable||_;return await N$.updateTable(S).set({[O]:G,[$]:Y}).where("id","=",Number(Z.id)).execute(),{chargesEnabled:G,payoutsEnabled:Y}},async chargeWithSplit(k,j){let d=await wd(),O=j.accountColumn||"stripe_account_id",$=k._attributes??k,Z=j.connectAccountId||$[O],X={amount:j.amountCents,currency:j.currency||"usd",automatic_payment_methods:{enabled:!0},metadata:j.metadata};if(Z){if(X.transfer_data={destination:Z},j.platformFeeCents)X.application_fee_amount=j.platformFeeCents}return await d.paymentIntents.create(X)}}}async function wd(){let _=globalThis.process?.env?.STRIPE_SECRET_KEY;if(!_)throw Error("Stripe Connect: STRIPE_SECRET_KEY not configured");return new(await Promise.resolve().then(() => (jz(),kz))).default(_,{apiVersion:"2024-06-20"})}import{db as qV,sql as HV}from"@stacksjs/database";var Uj=qV;function Oz(_,k){let j=k?.table||`${_}_likes`,d=k?.foreignKey||`${_.replace(/s$/,"")}_id`;return{async likes(O){return await Uj.selectFrom(j).where(d,"=",O).selectAll().execute()},async likeCount(O){let $=await Uj.selectFrom(j).select(HV`count(*) as count`).where(d,"=",O).executeTakeFirst();return Number($?.count)||0},async like(O,$){if(typeof O!=="number"||!Number.isFinite(O)||O<=0)throw Error(`[orm/likeable] like requires a positive numeric id (received ${String(O)})`);if(typeof $!=="number"||!Number.isFinite($)||$<=0)throw Error(`[orm/likeable] like requires a positive numeric userId (received ${String($)})`);let Z=new Date().toISOString();try{return await Uj.insertInto(j).values({[d]:O,user_id:$,created_at:Z,updated_at:Z}).returningAll().executeTakeFirst()}catch(X){let E=X;if(!(E.code==="SQLITE_CONSTRAINT_UNIQUE"||E.code==="SQLITE_CONSTRAINT"||E.code==="23505"||E.errno===1062||/unique|duplicate/i.test(E.message??"")))throw X;let G=await Uj.selectFrom(j).where(d,"=",O).where("user_id","=",$).selectAll().executeTakeFirst();if(G)return G;throw X}},async unlike(O,$){await Uj.deleteFrom(j).where(d,"=",O).where("user_id","=",$).execute()},async isLiked(O,$){return!!await Uj.selectFrom(j).where(d,"=",O).where("user_id","=",$).selectAll().executeTakeFirst()},async likedBy(O){return(await Uj.selectFrom(j).select([d]).where("user_id","=",O).execute()).map((Z)=>Number(Z[d])).filter(Boolean)}}}function $z(){return{async generateTwoFactorForModel(_){let{generateTwoFactorSecret:k}=await import("@stacksjs/auth"),j=k();await _.update({two_factor_secret:j})},async verifyTwoFactorCode(_,k){let{verifyTwoFactorCode:j}=await import("@stacksjs/auth"),d=_.get("two_factor_secret");if(typeof d==="string")return j(k,d);return!1}}}import{log as Z1}from"@stacksjs/logging";var j9="deleted_at";function Zz(_,k="id"){return{async softDelete(j){let d=new Date().toISOString(),O=_.where(k,j);if(typeof O?.update==="function")return await O.update({[j9]:d}),!0;return!1},async restore(j){let d=_.where(k,j);if(typeof d?.update==="function")return await d.update({[j9]:null}),!0;return!1},async forceDelete(j){let d=_.where(k,j);if(typeof d?.delete==="function")return await d.delete(),!0;return!1},withTrashed(){return typeof _.query==="function"?_.query():_},onlyTrashed(){let j=typeof _.query==="function"?_.query():_;if(typeof j?.whereNotNull==="function")return j.whereNotNull(j9);return j?.where?.(j9,"!=",null)??j}}}function Xz(_){if(_===!0||_==null)return{};if(typeof _==="object"&&!Array.isArray(_)){let k=_;if(Array.isArray(k.cascade)){let j=k.cascade.filter((d)=>typeof d==="string");return j.length?{cascade:j}:{}}return{}}return{}}function bV(_,k){let j=_.hasMany??[],d=_.hasOne??[],O=j.some((G)=>x$(G,k,!0)),$=d.some((G)=>x$(G,k,!1));if(!O&&!$)return Z1.warn(`[orm] soft-delete cascade: '${k}' is not a declared hasMany/hasOne relation \u2014 skipping`),null;let X=(O?j:d).find((G)=>x$(G,k,O))??null;if(!X)return null;let F=globalThis[X];if(!F)return Z1.warn(`[orm] soft-delete cascade: model '${X}' is not yet on globalThis \u2014 skipping cascade for '${k}'`),null;return{className:X,model:F}}function x$(_,k,j){let d=_.toLowerCase();if(k===d)return!0;if(j&&k===`${d}s`)return!0;if(j&&d.endsWith("y")&&k===`${d.slice(0,-1)}ies`)return!0;return!1}async function NV(_,k,j,d,O){try{let $=j.where;if(typeof $!=="function"){Z1.warn(`[orm] cascade ${O}: child model has no .where()`);return}if(O==="softDelete"){let Z=j.softDelete;if(typeof Z==="function"){let E=$.call(j,d,k),F=typeof E?.get==="function"?await E.get():Array.isArray(E)?E:[],G=j.primaryKey||"id";for(let Y of F){let S=Y?.[G];if(S!=null)await Z.call(j,S)}return}let X=$.call(j,d,k);if(typeof X?.delete==="function"){Z1.debug(`[orm] cascade soft-delete: child has no softDeletes trait, hard-deleting from ${String(j.table??"?")}`),await X.delete();return}}else{let Z=j.restore;if(typeof Z!=="function"){Z1.debug("[orm] cascade restore: child has no restore() \u2014 nothing to do");return}let X=j.withTrashed,F=(typeof X==="function"?X.call(j):j).where?.(d,k),G=typeof F?.get==="function"?await F.get():[],Y=j.primaryKey||"id";for(let S of G){let z=S?.[Y];if(z!=null)await Z.call(j,z)}}}catch($){Z1.warn(`[orm] soft-delete cascade ${O} on ${_}#${String(k)} failed`,{error:$})}}async function i$(_,k,j,d){let O=k.cascade;if(!O||O.length===0)return;let $=`${_.name.toLowerCase()}_id`;for(let Z of O){let X=bV(_,Z);if(!X)continue;await NV(X.className,j,X.model,$,d)}}var xV={string:{get:(_)=>_!=null?String(_):null,set:(_)=>_!=null?String(_):null},number:{get:(_)=>_!=null?Number(_):null,set:(_)=>_!=null?Number(_):null},integer:{get:(_)=>_!=null?Math.trunc(Number(_)):null,set:(_)=>_!=null?Math.trunc(Number(_)):null},float:{get:(_)=>_!=null?Number.parseFloat(String(_)):null,set:(_)=>_!=null?Number.parseFloat(String(_)):null},boolean:{get:(_)=>_===1||_==="1"||_===!0||_==="true",set:(_)=>_===!0||_===1||_==="1"||_==="true"?1:0},json:{get:(_)=>{if(_==null)return null;if(typeof _==="string")try{return JSON.parse(_)}catch{return _}return _},set:(_)=>{if(_==null)return null;return typeof _==="string"?_:JSON.stringify(_)}},datetime:{get:(_)=>_?new Date(_):null,set:(_)=>_ instanceof Date?_.toISOString():_},date:{get:(_)=>_?new Date(_):null,set:(_)=>_ instanceof Date?_.toISOString().split("T")[0]:_},array:{get:(_)=>{if(_==null)return[];if(Array.isArray(_))return _;if(typeof _==="string")try{return JSON.parse(_)}catch{return[]}return[]},set:(_)=>{if(_==null)return null;return Array.isArray(_)?JSON.stringify(_):_}}};function zz(_){return typeof _==="string"?xV[_]:_}function Ez(_,k,j){if(!_||typeof _!=="object")return _;let d={..._};for(let[O,$]of Object.entries(k))if(O in d){let Z=zz($);d[O]=Z[j](d[O])}return d}var d9=new Set(["_attributes","_original","_definition","_hasSaved","_relations"]),Gz=Symbol.for("stacks.modelInstanceProxy");function mk(_,k){if(!_||typeof _!=="object")return _;if(_[Gz])return _;let j=_._attributes;if(!j||typeof j!=="object")return _;if(k&&Object.keys(k).length>0){for(let[d,O]of Object.entries(k))if(Object.prototype.hasOwnProperty.call(j,d))j[d]=zz(O).get(j[d])}return new Proxy(_,{get(d,O,$){if(O===Gz)return!0;if(typeof O==="string"&&!d9.has(O)){let X=d._attributes;if(X&&Object.prototype.hasOwnProperty.call(X,O))return X[O];let E=d._relations;if(E&&Object.prototype.hasOwnProperty.call(E,O)){let F=E[O];if(Array.isArray(F))return F.map((G)=>mk(G,k));return mk(F,k)}}let Z=Reflect.get(d,O,d);return typeof Z==="function"?Z.bind(d):Z},set(d,O,$,Z){if(typeof O==="string"&&!d9.has(O)){let{_attributes:X,set:E}=d;if(X&&Object.prototype.hasOwnProperty.call(X,O)){if(typeof E==="function")E.call(d,O,$);else X[O]=$;return!0}if(X&&!(O in d)){if(typeof E==="function")E.call(d,O,$);else X[O]=$;return!0}}return Reflect.set(d,O,$,Z)},has(d,O){if(typeof O==="string"&&!d9.has(O)){let $=d._attributes;if($&&Object.prototype.hasOwnProperty.call($,O))return!0;let Z=d._relations;if(Z&&Object.prototype.hasOwnProperty.call(Z,O))return!0}return Reflect.has(d,O)},deleteProperty(d,O){if(typeof O==="string"&&!d9.has(O)){let $=d._attributes;if($&&Object.prototype.hasOwnProperty.call($,O))return delete $[O],!0}return Reflect.deleteProperty(d,O)},ownKeys(d){let O=d._attributes;return O?Object.keys(O):[]},getOwnPropertyDescriptor(d,O){if(typeof O==="string"){let $=d._attributes;if($&&Object.prototype.hasOwnProperty.call($,O))return{configurable:!0,enumerable:!0,value:$[O],writable:!0}}return Object.getOwnPropertyDescriptor(d,O)}})}var iV=new Set(["get","first","last","firstOrFail","find","findOrFail","all","paginate"]),Fz=Symbol.for("stacks.queryBuilderProxy");function Sz(_,k){if(!_||typeof _!=="object")return _;if(_[Fz])return _;return new Proxy(_,{get(j,d,O){if(d===Fz)return!0;let $=Reflect.get(j,d,O);if(typeof $!=="function")return $;return function(...Z){let X=$.apply(j,Z),E=(F)=>{if(iV.has(String(d))){if(Array.isArray(F))return F.map((G)=>mk(G,k));if(F&&Array.isArray(F.data))return{...F,data:F.data.map((G)=>mk(G,k))};return mk(F,k)}if(F&&typeof F==="object"&&typeof F.get==="function")return Sz(F,k);return F};if(X&&typeof X.then==="function")return X.then(E);return E(X)}}})}function BV(_,k){let j=["find","first","last","all","firstOrFail","findOrFail","findMany"];for(let $ of j){let Z=_[$];if(typeof Z!=="function")continue;_[$]=function(...X){let E=Z.apply(this,X),F=(G)=>Array.isArray(G)?G.map((Y)=>mk(Y,k)):mk(G,k);if(E&&typeof E.then==="function")return E.then(F);return F(E)}}let d=["create","firstOrCreate","updateOrCreate","make"];for(let $ of d){let Z=_[$];if(typeof Z!=="function")continue;_[$]=function(...X){let E=Z.apply(this,X),F=(G)=>Array.isArray(G)?G.map((Y)=>mk(Y,k)):mk(G,k);if(E&&typeof E.then==="function")return E.then(F);return F(E)}}let O=["query","where","orWhere","whereIn","whereNotIn","whereNull","whereNotNull","whereLike","whereBetween","whereNotBetween","orderBy","orderByDesc","select","with","limit","take","skip","latest","oldest"];for(let $ of O){let Z=_[$];if(typeof Z!=="function")continue;_[$]=function(...X){let E=Z.apply(this,X);return Sz(E,k)}}}class Yz extends Error{model;id;constructor(_,k){super(k!=null?`[ORM] ${_} not found for id=${String(k)}`:`[ORM] No matching ${_} row`);this.name="ModelNotFoundError",this.model=_,this.id=k}}async function cV(_,k){let j=_.set;if(!j||typeof j!=="object")return k;let d={...k};for(let[O,$]of Object.entries(j)){if(typeof $!=="function"||!(O in d))continue;try{d[O]=await $(d)}catch(Z){Qj.error(`[orm] ${_.name}.set.${O} threw \u2014 skipping setter`,Z)}}return d}function yV(_,k){let j=k.primaryKey||"id";function d(X){let E=_.where;if(typeof E!=="function")throw Error(`[ORM] ${k.name}.${X} needs a working where(): the underlying query builder did not expose one`);return E}function O(X){let E=_.find;if(typeof E!=="function")throw Error(`[ORM] ${k.name}.${X} needs a working find(): the underlying query builder did not expose one`);return E}function $(X){let E=_.create;if(typeof E!=="function")throw Error(`[ORM] ${k.name}.${X} cannot create: the underlying query builder did not expose create()`);return E}if(typeof _.update!=="function")_.update=async function(X,E){if(X==null)throw Error(`[ORM] ${k.name}.update requires an id as the first argument`);if(!E||typeof E!=="object"||Array.isArray(E))throw Error(`[ORM] ${k.name}.update requires a data object as the second argument`);if(Object.keys(E).length===0){Qj.debug(`[orm] ${k.name}.update called with empty data \u2014 short-circuiting and returning current row`);let Y=_.find;return typeof Y==="function"?await Y.call(_,X):null}let F=await cV(k,E);await d("update").call(_,j,X).update(F);let G=_.find;return typeof G==="function"?await G.call(_,X):null};if(typeof _.delete!=="function")_.delete=async function(X){if(X==null)throw Error(`[ORM] ${k.name}.delete requires an id as the first argument`);if(!await O("delete").call(_,X))return!1;return await d("delete").call(_,j,X).delete(),!0};if(typeof _.findOrFail!=="function")_.findOrFail=async function(X){let E=await O("findOrFail").call(_,X);if(E==null)throw new Yz(k.name,X);return E};if(typeof _.exists!=="function")_.exists=async function(X){if(X==null)return!1;let E=d("exists").call(_,j,X);if(typeof E.count==="function"){let G=await E.count();return Number(G)>0}let F=_.find;return typeof F==="function"?await F.call(_,X)!=null:!1};if(typeof _.firstOrCreate!=="function")_.firstOrCreate=async function(X,E={}){if(!X||typeof X!=="object"||Array.isArray(X))throw Error(`[ORM] ${k.name}.firstOrCreate requires a where-attrs object`);let F=d("firstOrCreate").call(_,X),G=typeof F.first==="function"?await F.first():await F;if(G)return G;return await $("firstOrCreate").call(_,{...X,...E})};if(typeof _.updateOrCreate!=="function")_.updateOrCreate=async function(X,E){if(!X||typeof X!=="object"||Array.isArray(X))throw Error(`[ORM] ${k.name}.updateOrCreate requires a where-attrs object`);if(!E||typeof E!=="object"||Array.isArray(E))throw Error(`[ORM] ${k.name}.updateOrCreate requires a values object`);let F=d("updateOrCreate").call(_,X),G=typeof F.first==="function"?await F.first():await F;if(G){let Y=G[j];await d("updateOrCreate").call(_,j,Y).update(E);let S=_.find;return typeof S==="function"?await S.call(_,Y):{...G,...E}}return await $("updateOrCreate").call(_,{...X,...E})};if(typeof _.count!=="function")_.count=async function(){let X=_;if(typeof X.query==="function"){let G=X.query();if(typeof G?.count==="function"){let Y=await G.count();return Number(Y)||0}}let{all:E,get:F}=_;if(typeof E==="function")return(await E.call(_)||[]).length;if(typeof F==="function")return(await F.call(_)||[]).length;return 0};if(typeof _.pluck!=="function")_.pluck=async function(X){if(!X||typeof X!=="string")throw Error(`[ORM] ${k.name}.pluck requires a column name`);let E=_.all;return((typeof E==="function"?await E.call(_):[])||[]).map((G)=>G?.[X])};if(typeof _.whereIn!=="function")_.whereIn=async function(X,E){if(!X||typeof X!=="string")throw Error(`[ORM] ${k.name}.whereIn requires a column name`);if(!Array.isArray(E))throw Error(`[ORM] ${k.name}.whereIn requires an array of values`);if(E.length===0)return[];let F=_.where;if(typeof F!=="function")return[];let G=F.call(_,X,"in",E);if(G&&typeof G.get==="function")return await G.get();return await G};let Z=[["latest","desc"],["oldest","asc"]];for(let[X,E]of Z)if(typeof _[X]!=="function")_[X]=async function(F="created_at"){let G=_,Y=typeof G.query==="function"?G.query():G;if(typeof Y?.orderBy==="function"){let Q=Y.orderBy(F,E);if(typeof Q.first==="function")return await Q.first();if(typeof Q.get==="function")return(await Q.get())?.[0]??null}let S=_.all;if(typeof S!=="function")return null;return[...await S.call(_)||[]].sort((Q,I)=>{let T=Q?.[F],W=I?.[F];if(T===W)return 0;return(T>W?1:-1)*(E==="desc"?-1:1)})[0]??null}}async function B$(_,k){if(!_||typeof _!=="object")return;let j=_._attributes??_;for(let d of k){if(!(d in j))continue;let O=j[d];if(!F1(O))continue;j[d]=await F9(O)}}function vV(_,k){if(k.length===0)return;let j=async(Z)=>{if(Array.isArray(Z)){for(let X of Z)await B$(X,k);return Z}if(Z&&typeof Z==="object"&&Array.isArray(Z.data)){for(let X of Z.data)await B$(X,k);return Z}if(Z)await B$(Z,k);return Z},d=["find","first","last","all","firstOrFail","findOrFail","findMany"];for(let Z of d){let X=_[Z];if(typeof X!=="function")continue;_[Z]=async function(...E){let F=await X.apply(this,E);return await j(F)}}let O=["create","firstOrCreate","updateOrCreate","make"];for(let Z of O){let X=_[Z];if(typeof X!=="function")continue;_[Z]=async function(...E){let F=await X.apply(this,E);return await j(F)}}let $=_.update;if(typeof $==="function")_.update=async function(Z,X){let E=await $.call(this,Z,X);return await j(E)}}function AV(_,k){if(k.length===0)return;let j=async($)=>{if(!$||typeof $!=="object"||Array.isArray($))return $;let Z={...$};for(let X of k)if(X in Z)Z[X]=await G9(Z[X]);return Z},d=["create","firstOrCreate","updateOrCreate"];for(let $ of d){let Z=_[$];if(typeof Z!=="function")continue;_[$]=async function(...X){if(X[0]=await j(X[0]),X[1])X[1]=await j(X[1]);return await Z.apply(this,X)}}let O=_.update;if(typeof O==="function")_.update=async function($,Z){let X=await j(Z);return await O.call(this,$,X)}}function mV(_,k){let j=["create","firstOrCreate","updateOrCreate"];for(let O of j){let $=_[O];if(typeof $==="function")_[O]=async function(...Z){if(Qj.debug(`[orm] ${O.charAt(0).toUpperCase()+O.slice(1)} ${String(_.name||"unknown")}`,Z[0]),Z[0]&&typeof Z[0]==="object"&&!Array.isArray(Z[0]))Z[0]=Ez(Z[0],k,"set");return await $.apply(this,Z)}}let d=_.update;if(typeof d==="function")_.update=async function(O,$){let Z=$&&typeof $==="object"&&!Array.isArray($)?Ez($,k,"set"):$;return await d.call(this,O,Z)}}function th(_){Qj.debug(`[orm] Defining model: ${_.name} (table: ${_.table})`);let k=gV(_),j=k?{..._,hooks:{..._.hooks,...k}}:_,d=m8(j);if(BV(d,_.casts),yV(d,j),_.casts&&Object.keys(_.casts).length>0)mV(d,_.casts);let O=z9(_);if(O.length>0)AV(d,O),vV(d,O);let $=_.traits?.useSoftDeletes;if($)lV(d,j,$);if(_.traits?.useAudit)t$(d,_.name,_.primaryKey||"id");let Z=uV(_);return Object.assign(d,Z,{..._,getDefinition:()=>_,_isStacksModel:!0})}function gV(_){let k=_.traits?.observe;if(!k)return;let j=_.name.toLowerCase(),d=(X,E)=>{return import("@stacksjs/events").then(({dispatch:F})=>F(X,E)).catch((F)=>{if(F&&typeof F==="object"&&"code"in F&&F.code==="MODULE_NOT_FOUND")return;console.error(`[ORM] Event '${X}' handler error:`,F)})},O=async(X,E)=>{try{let{dispatchAsync:F}=await import("@stacksjs/events"),G=await F(X,E);if(Array.isArray(G)&&G.some((Y)=>Y===!1))return!1}catch(F){if(F&&typeof F==="object"&&"code"in F&&F.code==="MODULE_NOT_FOUND")return!0;console.error(`[ORM] Before-event '${X}' handler error:`,F)}return!0},$=k===!0?["create","update","delete"]:Array.isArray(k)?k:[],Z={};if($.includes("create"))Z.beforeCreate=async(X)=>{if(Qj.debug(`[orm] Create ${j}`,X),!await O(`${j}:creating`,X))throw Error(`[ORM] ${j}:creating event cancelled the operation`)},Z.afterCreate=(X)=>d(`${j}:created`,X);if($.includes("update"))Z.beforeUpdate=async(X)=>{if(Qj.debug(`[orm] Update ${j}#${X?.id??"unknown"}`,X),!await O(`${j}:updating`,X))throw Error(`[ORM] ${j}:updating event cancelled the operation`)},Z.afterUpdate=(X)=>d(`${j}:updated`,X);if($.includes("delete"))Z.beforeDelete=async(X)=>{if(Qj.debug(`[orm] Delete ${j}#${X?.id??"unknown"}`),!await O(`${j}:deleting`,X))throw Error(`[ORM] ${j}:deleting event cancelled the operation`)},Z.afterDelete=(X)=>d(`${j}:deleted`,X);return Z}function uV(_){let k={},j=_.table,d=_.traits;if(!d)return k;if(d.taggable)k._taggable=M6(j);if(d.categorizable)k._categorizable=C6(j);if(d.commentable)k._commentable=f6(j);if(d.billable)k._billable=dz(j);if(d.likeable){let $=typeof d.likeable==="object"?d.likeable:void 0;k._likeable=Oz(j,$)}let O=d.useAuth||d.authenticatable;if(typeof O==="object"&&O&&"useTwoFactor"in O&&O.useTwoFactor)k._twoFactor=$z();return k}function lV(_,k,j){let d=Zz(_,k.primaryKey||"id"),O=Xz(j),$=k,Z=(O.cascade?.length??0)>0,X=Z?async(F)=>{let G=await d.softDelete(F);if(G)await i$($,O,F,"softDelete");return G}:d.softDelete,E=Z?async(F)=>{let G=await d.restore(F);if(G)await i$($,O,F,"restore");return G}:d.restore;_.softDelete=X,_.restore=E,_.forceDelete=d.forceDelete,_.withTrashed=d.withTrashed,_.onlyTrashed=d.onlyTrashed,_.delete=X}function pV(_){if(_==null)return _;if(Array.isArray(_))return _.map(pV);if(typeof _!=="object")return _;if(typeof _.toJSON==="function")return _.toJSON();if(_._attributes&&typeof _._attributes==="object")return _._attributes;return _}function sV(){try{let _=process.env.DB_DATABASE_PATH||"database/stacks.sqlite";if((process.env.DB_CONNECTION||"sqlite")==="sqlite")Q6({database:_})}catch{}}sV();async function O9(_,k=[""]){let{path:j}=await import("@stacksjs/path"),d=j.userModelsPath(`${_}.ts`);try{if(await Bun.file(d).exists())return(await import(d)).default}catch{}for(let O of k){let $=O?`${O}/`:"",Z=j.frameworkPath(`defaults/app/Models/${$}${_}.ts`);try{if(await Bun.file(Z).exists())return(await import(Z)).default}catch{}}return null}var oV=await O9("User"),rV=await O9("Job"),tV=await O9("FailedJob"),aV=[["Team",[""]],["Subscriber",[""]],["SubscriberEmail",[""]],["Subscription",[""]],["Post",["Content"]],["Page",["Content"]],["Author",["Content"]],["Comment",[""]],["Tag",[""]],["Activity",[""]],["Deployment",[""]],["Release",[""]],["Notification",[""]],["Log",[""]],["Request",[""]],["Error",[""]],["Websocket",["realtime"]],["Campaign",[""]],["CampaignSend",[""]],["EmailList",[""]],["EmailListSubscriber",[""]],["SocialPost",[""]],["PaymentMethod",[""]],["PaymentProduct",[""]],["PaymentTransaction",[""]],["Order",["commerce"]],["OrderItem",["commerce"]],["Cart",["commerce"]],["CartItem",["commerce"]],["Customer",["commerce"]],["Product",["commerce"]],["ProductVariant",["commerce"]],["ProductUnit",["commerce"]],["Manufacturer",["commerce"]],["Category",["commerce"]],["Coupon",["commerce"]],["GiftCard",["commerce"]],["LicenseKey",["commerce"]],["Review",["commerce"]],["Receipt",["commerce"]],["PrintDevice",["commerce"]],["ShippingMethod",["commerce"]],["ShippingRate",["commerce"]],["ShippingZone",["commerce"]],["DeliveryRoute",["commerce"]],["DigitalDelivery",["commerce"]],["Driver",["commerce"]],["TaxRate",["commerce"]],["WaitlistProduct",["commerce"]],["WaitlistRestaurant",["commerce"]],["LoyaltyPoint",["commerce"]],["LoyaltyReward",["commerce"]],["Payment",["commerce"]],["Transaction",["commerce"]]],m={};for(let[_,k]of aV){let j=await O9(_,k);if(j)m[_]=j}var{Activity:kf,Author:jf,Campaign:df,Cart:Of,CartItem:$f,Category:Zf,Comment:Xf,Coupon:Ef,Customer:Gf,DeliveryRoute:Ff,Deployment:zf,DigitalDelivery:Sf,Driver:Yf,CampaignSend:Lf,EmailList:Pf,EmailListSubscriber:Uf,Error:Qf,GiftCard:Vf,LicenseKey:Tf,Log:Wf,LoyaltyPoint:Kf,LoyaltyReward:nf,Manufacturer:Jf,Notification:If,Order:Df,OrderItem:Rf,Page:wf,Payment:Mf,PaymentMethod:Cf,PaymentProduct:hf,PaymentTransaction:ff,Post:qf,PrintDevice:Hf,Product:bf,ProductUnit:Nf,ProductVariant:xf,Receipt:Bf,Release:cf,Request:yf,Review:vf,ShippingMethod:Af,ShippingRate:mf,ShippingZone:gf,SocialPost:uf,Subscriber:lf,SubscriberEmail:pf,Subscription:sf,Tag:of,TaxRate:rf,Team:tf,Transaction:af,WaitlistProduct:ef,WaitlistRestaurant:_q,Websocket:kq}=m,eV={User:oV,Job:rV,FailedJob:tV,...m},X1=globalThis;for(let[_,k]of Object.entries(eV))if(k&&X1[_]===void 0)X1[_]=k;async function _T(_){if(!_)return[];try{if(typeof _.all==="function"){let k=await _.all();return Array.isArray(k)?k:[]}if(typeof _.get==="function"){let k=await _.get();return Array.isArray(k)?k:[]}}catch{}return[]}function kT(_,k,j=""){if(!_)return j;try{if(typeof _.get==="function"){let O=_.get(k);if(O!==void 0&&O!==null)return O}}catch{}let d=_?.[k];return d!==void 0&&d!==null?d:j}if(X1.safeAll===void 0)X1.safeAll=_T;if(X1.safeGet===void 0)X1.safeGet=kT;export{hT as transactional,MT as transactionBuilder,wT as transaction,aT as toTimestamp,pV as toAttrs,Cz as setAuditUser,CT as savepoint,nz as prunable,iT as modelTableName,zT as massPrunable,pT as mapEntity,F1 as isEncrypted,BT as hasRelations,Uk as getTableName,bz as getRelations,cT as getRelationType,yT as getRelationCount,ST as getPrunableConfig,vT as getPivotTables,Hz as getPivotTableName,Y1 as getModelName,mT as getHiddenAttributes,gT as getGuardedAttributes,uT as getFillableAttributes,rT as formatDate,Q9 as findUserModel,U9 as findCoreModel,AT as fetchOtherModelRelations,sT as extractImports,lT as extractFields,tT as extractDate,oT as extractAttributesFromModel,G9 as encryptValue,th as defineModel,F9 as decryptValue,IT as db,r$ as createAuditMethods,z9 as collectEncryptedAttributes,WT as batchLoad,kq as Websocket,_q as WaitlistRestaurant,ef as WaitlistProduct,oV as User,af as Transaction,tf as Team,rf as TaxRate,of as Tag,sf as Subscription,pf as SubscriberEmail,lf as Subscriber,qz as SubqueryBuilder,uf as SocialPost,gf as ShippingZone,mf as ShippingRate,Af as ShippingMethod,vf as Review,yf as Request,cf as Release,Bf as Receipt,xf as ProductVariant,Nf as ProductUnit,bf as Product,Hf as PrintDevice,qf as Post,ff as PaymentTransaction,hf as PaymentProduct,Cf as PaymentMethod,Mf as Payment,wf as Page,Rf as OrderItem,Df as Order,If as Notification,Yz as ModelNotFoundError,Jf as Manufacturer,nf as LoyaltyReward,Kf as LoyaltyPoint,Wf as Log,Tf as LicenseKey,rV as Job,Vf as GiftCard,tV as FailedJob,Qf as ErrorModel,Uf as EmailListSubscriber,Pf as EmailList,Yf as Driver,Sf as DigitalDelivery,zf as Deployment,Ff as DeliveryRoute,Gf as Customer,Ef as Coupon,Xf as Comment,Zf as Category,$f as CartItem,Of as Cart,Lf as CampaignSend,df as Campaign,jf as Author,kf as Activity};
|
|
10
|
+
`+N+`
|
|
11
|
+
`+R})}let M=Math.floor((typeof O==="number"?O:Date.now())/1000)-L.timestamp;if(T>0&&M>T)throw new o.StripeSignatureVerificationError(z,B,{message:"Timestamp outside the tolerance zone"});return!0}function G(B,z){if(typeof B!=="string")return null;return B.split(",").reduce((L,H)=>{let T=H.split("=");if(T[0]==="t")L.timestamp=parseInt(T[1],10);if(T[0]===z)L.signatures.push(T[1]);return L},{timestamp:-1,signatures:[]})}let V=null;function U(){if(!V)V=$.createDefaultCryptoProvider();return V}function W(B){if(!B)throw new o.StripeError({message:"Options are required"});let z=Math.floor(B.timestamp)||Math.floor(Date.now()/1000),L=B.scheme||J.EXPECTED_SCHEME,H=B.cryptoProvider||U(),T=`${z}.${B.payload}`;return{...B,timestamp:z,scheme:L,cryptoProvider:H,payloadString:T,generateHeaderString:(q)=>{return`t=${z},${L}=${q}`}}}return Z.signature=J,Z}V1.createWebhooks=kU});var L1=K((U1)=>{Object.defineProperty(U1,"__esModule",{value:!0});U1.ApiMajorVersion=U1.ApiVersion=void 0;U1.ApiVersion="2026-03-25.dahlia";U1.ApiMajorVersion="dahlia"});var w1=K((K1)=>{Object.defineProperty(K1,"__esModule",{value:!0});K1.resourceNamespace=void 0;function NU($,Z){for(let J in Z){if(!Object.prototype.hasOwnProperty.call(Z,J))continue;let Q=J[0].toLowerCase()+J.substring(1),X=new Z[J]($);this[Q]=X}}function xU($,Z){return function(J){return new NU(J,Z)}}K1.resourceNamespace=xU});var q1=K((D1)=>{Object.defineProperty(D1,"__esModule",{value:!0});D1.AccountLinks=void 0;var T1=w(),IU=T1.StripeResource.method;D1.AccountLinks=T1.StripeResource.extend({create:IU({method:"POST",fullPath:"/v2/core/account_links"})})});var A1=K((C1)=>{Object.defineProperty(C1,"__esModule",{value:!0});C1.AccountTokens=void 0;var F1=w(),E1=F1.StripeResource.method;C1.AccountTokens=F1.StripeResource.extend({create:E1({method:"POST",fullPath:"/v2/core/account_tokens",requestSchema:{kind:"object",fields:{identity:{kind:"object",fields:{individual:{kind:"object",fields:{relationship:{kind:"object",fields:{percent_ownership:{kind:"decimal_string"}}}}}}}}}}),retrieve:E1({method:"GET",fullPath:"/v2/core/account_tokens/{id}"})})});var P1=K((x1)=>{Object.defineProperty(x1,"__esModule",{value:!0});x1.Accounts=void 0;var N1=w(),Q0=N1.StripeResource.method;x1.Accounts=N1.StripeResource.extend({retrieve:Q0({method:"GET",fullPath:"/v1/financial_connections/accounts/{account}"}),list:Q0({method:"GET",fullPath:"/v1/financial_connections/accounts",methodType:"list"}),disconnect:Q0({method:"POST",fullPath:"/v1/financial_connections/accounts/{account}/disconnect"}),listOwners:Q0({method:"GET",fullPath:"/v1/financial_connections/accounts/{account}/owners",methodType:"list"}),refresh:Q0({method:"POST",fullPath:"/v1/financial_connections/accounts/{account}/refresh"}),subscribe:Q0({method:"POST",fullPath:"/v1/financial_connections/accounts/{account}/subscribe"}),unsubscribe:Q0({method:"POST",fullPath:"/v1/financial_connections/accounts/{account}/unsubscribe"})})});var y1=K((R1)=>{Object.defineProperty(R1,"__esModule",{value:!0});R1.Persons=void 0;var S1=w(),u0=S1.StripeResource.method;R1.Persons=S1.StripeResource.extend({create:u0({method:"POST",fullPath:"/v2/core/accounts/{account_id}/persons",requestSchema:{kind:"object",fields:{relationship:{kind:"object",fields:{percent_ownership:{kind:"decimal_string"}}}}},responseSchema:{kind:"object",fields:{relationship:{kind:"object",fields:{percent_ownership:{kind:"decimal_string"}}}}}}),retrieve:u0({method:"GET",fullPath:"/v2/core/accounts/{account_id}/persons/{id}",responseSchema:{kind:"object",fields:{relationship:{kind:"object",fields:{percent_ownership:{kind:"decimal_string"}}}}}}),update:u0({method:"POST",fullPath:"/v2/core/accounts/{account_id}/persons/{id}",requestSchema:{kind:"object",fields:{relationship:{kind:"object",fields:{percent_ownership:{kind:"decimal_string"}}}}},responseSchema:{kind:"object",fields:{relationship:{kind:"object",fields:{percent_ownership:{kind:"decimal_string"}}}}}}),list:u0({method:"GET",fullPath:"/v2/core/accounts/{account_id}/persons",methodType:"list",responseSchema:{kind:"object",fields:{data:{kind:"array",element:{kind:"object",fields:{relationship:{kind:"object",fields:{percent_ownership:{kind:"decimal_string"}}}}}}}}}),del:u0({method:"DELETE",fullPath:"/v2/core/accounts/{account_id}/persons/{id}"})})});var _1=K((f1)=>{Object.defineProperty(f1,"__esModule",{value:!0});f1.PersonTokens=void 0;var j1=w(),b1=j1.StripeResource.method;f1.PersonTokens=j1.StripeResource.extend({create:b1({method:"POST",fullPath:"/v2/core/accounts/{account_id}/person_tokens",requestSchema:{kind:"object",fields:{relationship:{kind:"object",fields:{percent_ownership:{kind:"decimal_string"}}}}}}),retrieve:b1({method:"GET",fullPath:"/v2/core/accounts/{account_id}/person_tokens/{id}"})})});var m1=K((g1)=>{Object.defineProperty(g1,"__esModule",{value:!0});g1.Accounts=void 0;var i$=w(),PU=y1(),SU=_1(),c0=i$.StripeResource.method;g1.Accounts=i$.StripeResource.extend({constructor:function(...$){i$.StripeResource.apply(this,$),this.persons=new PU.Persons(...$),this.personTokens=new SU.PersonTokens(...$)},create:c0({method:"POST",fullPath:"/v2/core/accounts",requestSchema:{kind:"object",fields:{identity:{kind:"object",fields:{individual:{kind:"object",fields:{relationship:{kind:"object",fields:{percent_ownership:{kind:"decimal_string"}}}}}}}}},responseSchema:{kind:"object",fields:{identity:{kind:"object",fields:{individual:{kind:"object",fields:{relationship:{kind:"object",fields:{percent_ownership:{kind:"decimal_string"}}}}}}}}}}),retrieve:c0({method:"GET",fullPath:"/v2/core/accounts/{id}",responseSchema:{kind:"object",fields:{identity:{kind:"object",fields:{individual:{kind:"object",fields:{relationship:{kind:"object",fields:{percent_ownership:{kind:"decimal_string"}}}}}}}}}}),update:c0({method:"POST",fullPath:"/v2/core/accounts/{id}",requestSchema:{kind:"object",fields:{identity:{kind:"object",fields:{individual:{kind:"object",fields:{relationship:{kind:"object",fields:{percent_ownership:{kind:"decimal_string"}}}}}}}}},responseSchema:{kind:"object",fields:{identity:{kind:"object",fields:{individual:{kind:"object",fields:{relationship:{kind:"object",fields:{percent_ownership:{kind:"decimal_string"}}}}}}}}}}),list:c0({method:"GET",fullPath:"/v2/core/accounts",methodType:"list",responseSchema:{kind:"object",fields:{data:{kind:"array",element:{kind:"object",fields:{identity:{kind:"object",fields:{individual:{kind:"object",fields:{relationship:{kind:"object",fields:{percent_ownership:{kind:"decimal_string"}}}}}}}}}}}}}),close:c0({method:"POST",fullPath:"/v2/core/accounts/{id}/close",responseSchema:{kind:"object",fields:{identity:{kind:"object",fields:{individual:{kind:"object",fields:{relationship:{kind:"object",fields:{percent_ownership:{kind:"decimal_string"}}}}}}}}}})})});var p1=K((n1)=>{Object.defineProperty(n1,"__esModule",{value:!0});n1.ActiveEntitlements=void 0;var c1=w(),u1=c1.StripeResource.method;n1.ActiveEntitlements=c1.StripeResource.extend({retrieve:u1({method:"GET",fullPath:"/v1/entitlements/active_entitlements/{id}"}),list:u1({method:"GET",fullPath:"/v1/entitlements/active_entitlements",methodType:"list"})})});var o1=K((i1)=>{Object.defineProperty(i1,"__esModule",{value:!0});i1.Alerts=void 0;var d1=w(),D0=d1.StripeResource.method;i1.Alerts=d1.StripeResource.extend({create:D0({method:"POST",fullPath:"/v1/billing/alerts"}),retrieve:D0({method:"GET",fullPath:"/v1/billing/alerts/{id}"}),list:D0({method:"GET",fullPath:"/v1/billing/alerts",methodType:"list"}),activate:D0({method:"POST",fullPath:"/v1/billing/alerts/{id}/activate"}),archive:D0({method:"POST",fullPath:"/v1/billing/alerts/{id}/archive"}),deactivate:D0({method:"POST",fullPath:"/v1/billing/alerts/{id}/deactivate"})})});var e1=K((r1)=>{Object.defineProperty(r1,"__esModule",{value:!0});r1.Associations=void 0;var s1=w(),RU=s1.StripeResource.method;r1.Associations=s1.StripeResource.extend({find:RU({method:"GET",fullPath:"/v1/tax/associations/find"})})});var Q4=K((Z4)=>{Object.defineProperty(Z4,"__esModule",{value:!0});Z4.Authorizations=void 0;var $4=w(),n0=$4.StripeResource.method;Z4.Authorizations=$4.StripeResource.extend({retrieve:n0({method:"GET",fullPath:"/v1/issuing/authorizations/{authorization}",responseSchema:{kind:"object",fields:{fleet:{kind:"nullable",inner:{kind:"object",fields:{reported_breakdown:{kind:"nullable",inner:{kind:"object",fields:{fuel:{kind:"nullable",inner:{kind:"object",fields:{gross_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},non_fuel:{kind:"nullable",inner:{kind:"object",fields:{gross_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},tax:{kind:"nullable",inner:{kind:"object",fields:{local_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},national_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}}}}}},fuel:{kind:"nullable",inner:{kind:"object",fields:{quantity_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_cost_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},transactions:{kind:"array",element:{kind:"object",fields:{purchase_details:{kind:"nullable",inner:{kind:"object",fields:{fleet:{kind:"nullable",inner:{kind:"object",fields:{reported_breakdown:{kind:"nullable",inner:{kind:"object",fields:{fuel:{kind:"nullable",inner:{kind:"object",fields:{gross_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},non_fuel:{kind:"nullable",inner:{kind:"object",fields:{gross_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},tax:{kind:"nullable",inner:{kind:"object",fields:{local_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},national_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}}}}}},fuel:{kind:"nullable",inner:{kind:"object",fields:{quantity_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_cost_decimal:{kind:"decimal_string"}}}}}}}}}}}}}),update:n0({method:"POST",fullPath:"/v1/issuing/authorizations/{authorization}",responseSchema:{kind:"object",fields:{fleet:{kind:"nullable",inner:{kind:"object",fields:{reported_breakdown:{kind:"nullable",inner:{kind:"object",fields:{fuel:{kind:"nullable",inner:{kind:"object",fields:{gross_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},non_fuel:{kind:"nullable",inner:{kind:"object",fields:{gross_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},tax:{kind:"nullable",inner:{kind:"object",fields:{local_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},national_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}}}}}},fuel:{kind:"nullable",inner:{kind:"object",fields:{quantity_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_cost_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},transactions:{kind:"array",element:{kind:"object",fields:{purchase_details:{kind:"nullable",inner:{kind:"object",fields:{fleet:{kind:"nullable",inner:{kind:"object",fields:{reported_breakdown:{kind:"nullable",inner:{kind:"object",fields:{fuel:{kind:"nullable",inner:{kind:"object",fields:{gross_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},non_fuel:{kind:"nullable",inner:{kind:"object",fields:{gross_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},tax:{kind:"nullable",inner:{kind:"object",fields:{local_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},national_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}}}}}},fuel:{kind:"nullable",inner:{kind:"object",fields:{quantity_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_cost_decimal:{kind:"decimal_string"}}}}}}}}}}}}}),list:n0({method:"GET",fullPath:"/v1/issuing/authorizations",methodType:"list",responseSchema:{kind:"object",fields:{data:{kind:"array",element:{kind:"object",fields:{fleet:{kind:"nullable",inner:{kind:"object",fields:{reported_breakdown:{kind:"nullable",inner:{kind:"object",fields:{fuel:{kind:"nullable",inner:{kind:"object",fields:{gross_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},non_fuel:{kind:"nullable",inner:{kind:"object",fields:{gross_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},tax:{kind:"nullable",inner:{kind:"object",fields:{local_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},national_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}}}}}},fuel:{kind:"nullable",inner:{kind:"object",fields:{quantity_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_cost_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},transactions:{kind:"array",element:{kind:"object",fields:{purchase_details:{kind:"nullable",inner:{kind:"object",fields:{fleet:{kind:"nullable",inner:{kind:"object",fields:{reported_breakdown:{kind:"nullable",inner:{kind:"object",fields:{fuel:{kind:"nullable",inner:{kind:"object",fields:{gross_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},non_fuel:{kind:"nullable",inner:{kind:"object",fields:{gross_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},tax:{kind:"nullable",inner:{kind:"object",fields:{local_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},national_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}}}}}},fuel:{kind:"nullable",inner:{kind:"object",fields:{quantity_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_cost_decimal:{kind:"decimal_string"}}}}}}}}}}}}}}}}),approve:n0({method:"POST",fullPath:"/v1/issuing/authorizations/{authorization}/approve",responseSchema:{kind:"object",fields:{fleet:{kind:"nullable",inner:{kind:"object",fields:{reported_breakdown:{kind:"nullable",inner:{kind:"object",fields:{fuel:{kind:"nullable",inner:{kind:"object",fields:{gross_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},non_fuel:{kind:"nullable",inner:{kind:"object",fields:{gross_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},tax:{kind:"nullable",inner:{kind:"object",fields:{local_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},national_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}}}}}},fuel:{kind:"nullable",inner:{kind:"object",fields:{quantity_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_cost_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},transactions:{kind:"array",element:{kind:"object",fields:{purchase_details:{kind:"nullable",inner:{kind:"object",fields:{fleet:{kind:"nullable",inner:{kind:"object",fields:{reported_breakdown:{kind:"nullable",inner:{kind:"object",fields:{fuel:{kind:"nullable",inner:{kind:"object",fields:{gross_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},non_fuel:{kind:"nullable",inner:{kind:"object",fields:{gross_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},tax:{kind:"nullable",inner:{kind:"object",fields:{local_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},national_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}}}}}},fuel:{kind:"nullable",inner:{kind:"object",fields:{quantity_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_cost_decimal:{kind:"decimal_string"}}}}}}}}}}}}}),decline:n0({method:"POST",fullPath:"/v1/issuing/authorizations/{authorization}/decline",responseSchema:{kind:"object",fields:{fleet:{kind:"nullable",inner:{kind:"object",fields:{reported_breakdown:{kind:"nullable",inner:{kind:"object",fields:{fuel:{kind:"nullable",inner:{kind:"object",fields:{gross_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},non_fuel:{kind:"nullable",inner:{kind:"object",fields:{gross_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},tax:{kind:"nullable",inner:{kind:"object",fields:{local_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},national_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}}}}}},fuel:{kind:"nullable",inner:{kind:"object",fields:{quantity_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_cost_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},transactions:{kind:"array",element:{kind:"object",fields:{purchase_details:{kind:"nullable",inner:{kind:"object",fields:{fleet:{kind:"nullable",inner:{kind:"object",fields:{reported_breakdown:{kind:"nullable",inner:{kind:"object",fields:{fuel:{kind:"nullable",inner:{kind:"object",fields:{gross_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},non_fuel:{kind:"nullable",inner:{kind:"object",fields:{gross_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},tax:{kind:"nullable",inner:{kind:"object",fields:{local_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},national_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}}}}}},fuel:{kind:"nullable",inner:{kind:"object",fields:{quantity_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_cost_decimal:{kind:"decimal_string"}}}}}}}}}}}}})})});var V4=K((Y4)=>{Object.defineProperty(Y4,"__esModule",{value:!0});Y4.Authorizations=void 0;var X4=w(),X0=X4.StripeResource.method;Y4.Authorizations=X4.StripeResource.extend({create:X0({method:"POST",fullPath:"/v1/test_helpers/issuing/authorizations",requestSchema:{kind:"object",fields:{fleet:{kind:"object",fields:{reported_breakdown:{kind:"object",fields:{fuel:{kind:"object",fields:{gross_amount_decimal:{kind:"decimal_string"}}},non_fuel:{kind:"object",fields:{gross_amount_decimal:{kind:"decimal_string"}}},tax:{kind:"object",fields:{local_amount_decimal:{kind:"decimal_string"},national_amount_decimal:{kind:"decimal_string"}}}}}}},fuel:{kind:"object",fields:{quantity_decimal:{kind:"decimal_string"},unit_cost_decimal:{kind:"decimal_string"}}}}},responseSchema:{kind:"object",fields:{fleet:{kind:"nullable",inner:{kind:"object",fields:{reported_breakdown:{kind:"nullable",inner:{kind:"object",fields:{fuel:{kind:"nullable",inner:{kind:"object",fields:{gross_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},non_fuel:{kind:"nullable",inner:{kind:"object",fields:{gross_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},tax:{kind:"nullable",inner:{kind:"object",fields:{local_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},national_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}}}}}},fuel:{kind:"nullable",inner:{kind:"object",fields:{quantity_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_cost_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},transactions:{kind:"array",element:{kind:"object",fields:{purchase_details:{kind:"nullable",inner:{kind:"object",fields:{fleet:{kind:"nullable",inner:{kind:"object",fields:{reported_breakdown:{kind:"nullable",inner:{kind:"object",fields:{fuel:{kind:"nullable",inner:{kind:"object",fields:{gross_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},non_fuel:{kind:"nullable",inner:{kind:"object",fields:{gross_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},tax:{kind:"nullable",inner:{kind:"object",fields:{local_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},national_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}}}}}},fuel:{kind:"nullable",inner:{kind:"object",fields:{quantity_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_cost_decimal:{kind:"decimal_string"}}}}}}}}}}}}}),capture:X0({method:"POST",fullPath:"/v1/test_helpers/issuing/authorizations/{authorization}/capture",requestSchema:{kind:"object",fields:{purchase_details:{kind:"object",fields:{fleet:{kind:"object",fields:{reported_breakdown:{kind:"object",fields:{fuel:{kind:"object",fields:{gross_amount_decimal:{kind:"decimal_string"}}},non_fuel:{kind:"object",fields:{gross_amount_decimal:{kind:"decimal_string"}}},tax:{kind:"object",fields:{local_amount_decimal:{kind:"decimal_string"},national_amount_decimal:{kind:"decimal_string"}}}}}}},fuel:{kind:"object",fields:{quantity_decimal:{kind:"decimal_string"},unit_cost_decimal:{kind:"decimal_string"}}},receipt:{kind:"array",element:{kind:"object",fields:{quantity:{kind:"decimal_string"}}}}}}}},responseSchema:{kind:"object",fields:{fleet:{kind:"nullable",inner:{kind:"object",fields:{reported_breakdown:{kind:"nullable",inner:{kind:"object",fields:{fuel:{kind:"nullable",inner:{kind:"object",fields:{gross_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},non_fuel:{kind:"nullable",inner:{kind:"object",fields:{gross_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},tax:{kind:"nullable",inner:{kind:"object",fields:{local_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},national_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}}}}}},fuel:{kind:"nullable",inner:{kind:"object",fields:{quantity_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_cost_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},transactions:{kind:"array",element:{kind:"object",fields:{purchase_details:{kind:"nullable",inner:{kind:"object",fields:{fleet:{kind:"nullable",inner:{kind:"object",fields:{reported_breakdown:{kind:"nullable",inner:{kind:"object",fields:{fuel:{kind:"nullable",inner:{kind:"object",fields:{gross_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},non_fuel:{kind:"nullable",inner:{kind:"object",fields:{gross_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},tax:{kind:"nullable",inner:{kind:"object",fields:{local_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},national_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}}}}}},fuel:{kind:"nullable",inner:{kind:"object",fields:{quantity_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_cost_decimal:{kind:"decimal_string"}}}}}}}}}}}}}),expire:X0({method:"POST",fullPath:"/v1/test_helpers/issuing/authorizations/{authorization}/expire",responseSchema:{kind:"object",fields:{fleet:{kind:"nullable",inner:{kind:"object",fields:{reported_breakdown:{kind:"nullable",inner:{kind:"object",fields:{fuel:{kind:"nullable",inner:{kind:"object",fields:{gross_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},non_fuel:{kind:"nullable",inner:{kind:"object",fields:{gross_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},tax:{kind:"nullable",inner:{kind:"object",fields:{local_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},national_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}}}}}},fuel:{kind:"nullable",inner:{kind:"object",fields:{quantity_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_cost_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},transactions:{kind:"array",element:{kind:"object",fields:{purchase_details:{kind:"nullable",inner:{kind:"object",fields:{fleet:{kind:"nullable",inner:{kind:"object",fields:{reported_breakdown:{kind:"nullable",inner:{kind:"object",fields:{fuel:{kind:"nullable",inner:{kind:"object",fields:{gross_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},non_fuel:{kind:"nullable",inner:{kind:"object",fields:{gross_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},tax:{kind:"nullable",inner:{kind:"object",fields:{local_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},national_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}}}}}},fuel:{kind:"nullable",inner:{kind:"object",fields:{quantity_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_cost_decimal:{kind:"decimal_string"}}}}}}}}}}}}}),finalizeAmount:X0({method:"POST",fullPath:"/v1/test_helpers/issuing/authorizations/{authorization}/finalize_amount",requestSchema:{kind:"object",fields:{fleet:{kind:"object",fields:{reported_breakdown:{kind:"object",fields:{fuel:{kind:"object",fields:{gross_amount_decimal:{kind:"decimal_string"}}},non_fuel:{kind:"object",fields:{gross_amount_decimal:{kind:"decimal_string"}}},tax:{kind:"object",fields:{local_amount_decimal:{kind:"decimal_string"},national_amount_decimal:{kind:"decimal_string"}}}}}}},fuel:{kind:"object",fields:{quantity_decimal:{kind:"decimal_string"},unit_cost_decimal:{kind:"decimal_string"}}}}},responseSchema:{kind:"object",fields:{fleet:{kind:"nullable",inner:{kind:"object",fields:{reported_breakdown:{kind:"nullable",inner:{kind:"object",fields:{fuel:{kind:"nullable",inner:{kind:"object",fields:{gross_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},non_fuel:{kind:"nullable",inner:{kind:"object",fields:{gross_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},tax:{kind:"nullable",inner:{kind:"object",fields:{local_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},national_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}}}}}},fuel:{kind:"nullable",inner:{kind:"object",fields:{quantity_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_cost_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},transactions:{kind:"array",element:{kind:"object",fields:{purchase_details:{kind:"nullable",inner:{kind:"object",fields:{fleet:{kind:"nullable",inner:{kind:"object",fields:{reported_breakdown:{kind:"nullable",inner:{kind:"object",fields:{fuel:{kind:"nullable",inner:{kind:"object",fields:{gross_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},non_fuel:{kind:"nullable",inner:{kind:"object",fields:{gross_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},tax:{kind:"nullable",inner:{kind:"object",fields:{local_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},national_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}}}}}},fuel:{kind:"nullable",inner:{kind:"object",fields:{quantity_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_cost_decimal:{kind:"decimal_string"}}}}}}}}}}}}}),increment:X0({method:"POST",fullPath:"/v1/test_helpers/issuing/authorizations/{authorization}/increment",responseSchema:{kind:"object",fields:{fleet:{kind:"nullable",inner:{kind:"object",fields:{reported_breakdown:{kind:"nullable",inner:{kind:"object",fields:{fuel:{kind:"nullable",inner:{kind:"object",fields:{gross_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},non_fuel:{kind:"nullable",inner:{kind:"object",fields:{gross_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},tax:{kind:"nullable",inner:{kind:"object",fields:{local_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},national_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}}}}}},fuel:{kind:"nullable",inner:{kind:"object",fields:{quantity_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_cost_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},transactions:{kind:"array",element:{kind:"object",fields:{purchase_details:{kind:"nullable",inner:{kind:"object",fields:{fleet:{kind:"nullable",inner:{kind:"object",fields:{reported_breakdown:{kind:"nullable",inner:{kind:"object",fields:{fuel:{kind:"nullable",inner:{kind:"object",fields:{gross_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},non_fuel:{kind:"nullable",inner:{kind:"object",fields:{gross_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},tax:{kind:"nullable",inner:{kind:"object",fields:{local_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},national_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}}}}}},fuel:{kind:"nullable",inner:{kind:"object",fields:{quantity_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_cost_decimal:{kind:"decimal_string"}}}}}}}}}}}}}),respond:X0({method:"POST",fullPath:"/v1/test_helpers/issuing/authorizations/{authorization}/fraud_challenges/respond",responseSchema:{kind:"object",fields:{fleet:{kind:"nullable",inner:{kind:"object",fields:{reported_breakdown:{kind:"nullable",inner:{kind:"object",fields:{fuel:{kind:"nullable",inner:{kind:"object",fields:{gross_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},non_fuel:{kind:"nullable",inner:{kind:"object",fields:{gross_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},tax:{kind:"nullable",inner:{kind:"object",fields:{local_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},national_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}}}}}},fuel:{kind:"nullable",inner:{kind:"object",fields:{quantity_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_cost_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},transactions:{kind:"array",element:{kind:"object",fields:{purchase_details:{kind:"nullable",inner:{kind:"object",fields:{fleet:{kind:"nullable",inner:{kind:"object",fields:{reported_breakdown:{kind:"nullable",inner:{kind:"object",fields:{fuel:{kind:"nullable",inner:{kind:"object",fields:{gross_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},non_fuel:{kind:"nullable",inner:{kind:"object",fields:{gross_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},tax:{kind:"nullable",inner:{kind:"object",fields:{local_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},national_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}}}}}},fuel:{kind:"nullable",inner:{kind:"object",fields:{quantity_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_cost_decimal:{kind:"decimal_string"}}}}}}}}}}}}}),reverse:X0({method:"POST",fullPath:"/v1/test_helpers/issuing/authorizations/{authorization}/reverse",responseSchema:{kind:"object",fields:{fleet:{kind:"nullable",inner:{kind:"object",fields:{reported_breakdown:{kind:"nullable",inner:{kind:"object",fields:{fuel:{kind:"nullable",inner:{kind:"object",fields:{gross_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},non_fuel:{kind:"nullable",inner:{kind:"object",fields:{gross_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},tax:{kind:"nullable",inner:{kind:"object",fields:{local_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},national_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}}}}}},fuel:{kind:"nullable",inner:{kind:"object",fields:{quantity_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_cost_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},transactions:{kind:"array",element:{kind:"object",fields:{purchase_details:{kind:"nullable",inner:{kind:"object",fields:{fleet:{kind:"nullable",inner:{kind:"object",fields:{reported_breakdown:{kind:"nullable",inner:{kind:"object",fields:{fuel:{kind:"nullable",inner:{kind:"object",fields:{gross_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},non_fuel:{kind:"nullable",inner:{kind:"object",fields:{gross_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},tax:{kind:"nullable",inner:{kind:"object",fields:{local_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},national_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}}}}}},fuel:{kind:"nullable",inner:{kind:"object",fields:{quantity_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_cost_decimal:{kind:"decimal_string"}}}}}}}}}}}}})})});var z4=K((W4)=>{Object.defineProperty(W4,"__esModule",{value:!0});W4.Calculations=void 0;var B4=w(),a$=B4.StripeResource.method;W4.Calculations=B4.StripeResource.extend({create:a$({method:"POST",fullPath:"/v1/tax/calculations"}),retrieve:a$({method:"GET",fullPath:"/v1/tax/calculations/{calculation}"}),listLineItems:a$({method:"GET",fullPath:"/v1/tax/calculations/{calculation}/line_items",methodType:"list"})})});var w4=K((K4)=>{Object.defineProperty(K4,"__esModule",{value:!0});K4.Cardholders=void 0;var L4=w(),S8=L4.StripeResource.method;K4.Cardholders=L4.StripeResource.extend({create:S8({method:"POST",fullPath:"/v1/issuing/cardholders"}),retrieve:S8({method:"GET",fullPath:"/v1/issuing/cardholders/{cardholder}"}),update:S8({method:"POST",fullPath:"/v1/issuing/cardholders/{cardholder}"}),list:S8({method:"GET",fullPath:"/v1/issuing/cardholders",methodType:"list"})})});var q4=K((D4)=>{Object.defineProperty(D4,"__esModule",{value:!0});D4.Cards=void 0;var T4=w(),R8=T4.StripeResource.method;D4.Cards=T4.StripeResource.extend({create:R8({method:"POST",fullPath:"/v1/issuing/cards"}),retrieve:R8({method:"GET",fullPath:"/v1/issuing/cards/{card}"}),update:R8({method:"POST",fullPath:"/v1/issuing/cards/{card}"}),list:R8({method:"GET",fullPath:"/v1/issuing/cards",methodType:"list"})})});var k4=K((F4)=>{Object.defineProperty(F4,"__esModule",{value:!0});F4.Cards=void 0;var E4=w(),l0=E4.StripeResource.method;F4.Cards=E4.StripeResource.extend({deliverCard:l0({method:"POST",fullPath:"/v1/test_helpers/issuing/cards/{card}/shipping/deliver"}),failCard:l0({method:"POST",fullPath:"/v1/test_helpers/issuing/cards/{card}/shipping/fail"}),returnCard:l0({method:"POST",fullPath:"/v1/test_helpers/issuing/cards/{card}/shipping/return"}),shipCard:l0({method:"POST",fullPath:"/v1/test_helpers/issuing/cards/{card}/shipping/ship"}),submitCard:l0({method:"POST",fullPath:"/v1/test_helpers/issuing/cards/{card}/shipping/submit"})})});var I4=K((N4)=>{Object.defineProperty(N4,"__esModule",{value:!0});N4.Configurations=void 0;var A4=w(),v8=A4.StripeResource.method;N4.Configurations=A4.StripeResource.extend({create:v8({method:"POST",fullPath:"/v1/billing_portal/configurations"}),retrieve:v8({method:"GET",fullPath:"/v1/billing_portal/configurations/{configuration}"}),update:v8({method:"POST",fullPath:"/v1/billing_portal/configurations/{configuration}"}),list:v8({method:"GET",fullPath:"/v1/billing_portal/configurations",methodType:"list"})})});var v4=K((S4)=>{Object.defineProperty(S4,"__esModule",{value:!0});S4.Configurations=void 0;var P4=w(),p0=P4.StripeResource.method;S4.Configurations=P4.StripeResource.extend({create:p0({method:"POST",fullPath:"/v1/terminal/configurations"}),retrieve:p0({method:"GET",fullPath:"/v1/terminal/configurations/{configuration}"}),update:p0({method:"POST",fullPath:"/v1/terminal/configurations/{configuration}"}),list:p0({method:"GET",fullPath:"/v1/terminal/configurations",methodType:"list"}),del:p0({method:"DELETE",fullPath:"/v1/terminal/configurations/{configuration}"})})});var f4=K((b4)=>{Object.defineProperty(b4,"__esModule",{value:!0});b4.ConfirmationTokens=void 0;var y4=w(),vU=y4.StripeResource.method;b4.ConfirmationTokens=y4.StripeResource.extend({create:vU({method:"POST",fullPath:"/v1/test_helpers/confirmation_tokens"})})});var h4=K((_4)=>{Object.defineProperty(_4,"__esModule",{value:!0});_4.ConnectionTokens=void 0;var M4=w(),yU=M4.StripeResource.method;_4.ConnectionTokens=M4.StripeResource.extend({create:yU({method:"POST",fullPath:"/v1/terminal/connection_tokens"})})});var n4=K((u4)=>{Object.defineProperty(u4,"__esModule",{value:!0});u4.CreditBalanceSummary=void 0;var m4=w(),bU=m4.StripeResource.method;u4.CreditBalanceSummary=m4.StripeResource.extend({retrieve:bU({method:"GET",fullPath:"/v1/billing/credit_balance_summary"})})});var a4=K((d4)=>{Object.defineProperty(d4,"__esModule",{value:!0});d4.CreditBalanceTransactions=void 0;var p4=w(),l4=p4.StripeResource.method;d4.CreditBalanceTransactions=p4.StripeResource.extend({retrieve:l4({method:"GET",fullPath:"/v1/billing/credit_balance_transactions/{id}"}),list:l4({method:"GET",fullPath:"/v1/billing/credit_balance_transactions",methodType:"list"})})});var t4=K((s4)=>{Object.defineProperty(s4,"__esModule",{value:!0});s4.CreditGrants=void 0;var o4=w(),O0=o4.StripeResource.method;s4.CreditGrants=o4.StripeResource.extend({create:O0({method:"POST",fullPath:"/v1/billing/credit_grants"}),retrieve:O0({method:"GET",fullPath:"/v1/billing/credit_grants/{id}"}),update:O0({method:"POST",fullPath:"/v1/billing/credit_grants/{id}"}),list:O0({method:"GET",fullPath:"/v1/billing/credit_grants",methodType:"list"}),expire:O0({method:"POST",fullPath:"/v1/billing/credit_grants/{id}/expire"}),voidGrant:O0({method:"POST",fullPath:"/v1/billing/credit_grants/{id}/void"})})});var J6=K(($6)=>{Object.defineProperty($6,"__esModule",{value:!0});$6.CreditReversals=void 0;var e4=w(),o$=e4.StripeResource.method;$6.CreditReversals=e4.StripeResource.extend({create:o$({method:"POST",fullPath:"/v1/treasury/credit_reversals"}),retrieve:o$({method:"GET",fullPath:"/v1/treasury/credit_reversals/{credit_reversal}"}),list:o$({method:"GET",fullPath:"/v1/treasury/credit_reversals",methodType:"list"})})});var G6=K((X6)=>{Object.defineProperty(X6,"__esModule",{value:!0});X6.Customers=void 0;var Q6=w(),jU=Q6.StripeResource.method;X6.Customers=Q6.StripeResource.extend({fundCashBalance:jU({method:"POST",fullPath:"/v1/test_helpers/customers/{customer}/fund_cash_balance"})})});var U6=K((B6)=>{Object.defineProperty(B6,"__esModule",{value:!0});B6.DebitReversals=void 0;var V6=w(),s$=V6.StripeResource.method;B6.DebitReversals=V6.StripeResource.extend({create:s$({method:"POST",fullPath:"/v1/treasury/debit_reversals"}),retrieve:s$({method:"GET",fullPath:"/v1/treasury/debit_reversals/{debit_reversal}"}),list:s$({method:"GET",fullPath:"/v1/treasury/debit_reversals",methodType:"list"})})});var H6=K((L6)=>{Object.defineProperty(L6,"__esModule",{value:!0});L6.Disputes=void 0;var z6=w(),d0=z6.StripeResource.method;L6.Disputes=z6.StripeResource.extend({create:d0({method:"POST",fullPath:"/v1/issuing/disputes"}),retrieve:d0({method:"GET",fullPath:"/v1/issuing/disputes/{dispute}"}),update:d0({method:"POST",fullPath:"/v1/issuing/disputes/{dispute}"}),list:d0({method:"GET",fullPath:"/v1/issuing/disputes",methodType:"list"}),submit:d0({method:"POST",fullPath:"/v1/issuing/disputes/{dispute}/submit"})})});var q6=K((D6)=>{Object.defineProperty(D6,"__esModule",{value:!0});D6.EarlyFraudWarnings=void 0;var T6=w(),w6=T6.StripeResource.method;D6.EarlyFraudWarnings=T6.StripeResource.extend({retrieve:w6({method:"GET",fullPath:"/v1/radar/early_fraud_warnings/{early_fraud_warning}"}),list:w6({method:"GET",fullPath:"/v1/radar/early_fraud_warnings",methodType:"list"})})});var k6=K((F6)=>{Object.defineProperty(F6,"__esModule",{value:!0});F6.EventDestinations=void 0;var E6=w(),s=E6.StripeResource.method;F6.EventDestinations=E6.StripeResource.extend({create:s({method:"POST",fullPath:"/v2/core/event_destinations"}),retrieve:s({method:"GET",fullPath:"/v2/core/event_destinations/{id}"}),update:s({method:"POST",fullPath:"/v2/core/event_destinations/{id}"}),list:s({method:"GET",fullPath:"/v2/core/event_destinations",methodType:"list"}),del:s({method:"DELETE",fullPath:"/v2/core/event_destinations/{id}"}),disable:s({method:"POST",fullPath:"/v2/core/event_destinations/{id}/disable"}),enable:s({method:"POST",fullPath:"/v2/core/event_destinations/{id}/enable"}),ping:s({method:"POST",fullPath:"/v2/core/event_destinations/{id}/ping"})})});var I6=K((N6)=>{Object.defineProperty(N6,"__esModule",{value:!0});N6.Events=void 0;var A6=w(),r$=A6.StripeResource.method;N6.Events=A6.StripeResource.extend({retrieve(...$){return r$({method:"GET",fullPath:"/v2/core/events/{id}",transformResponseData:(J)=>{return this.addFetchRelatedObjectIfNeeded(J)}}).apply(this,$)},list(...$){return r$({method:"GET",fullPath:"/v2/core/events",methodType:"list",transformResponseData:(J)=>{return{...J,data:J.data.map(this.addFetchRelatedObjectIfNeeded.bind(this))}}}).apply(this,$)},addFetchRelatedObjectIfNeeded($){if(!$.related_object||!$.related_object.url)return $;return{...$,fetchRelatedObject:()=>r$({method:"GET",fullPath:$.related_object.url}).apply(this,[{stripeContext:$.context,headers:{"Stripe-Request-Trigger":`event=${$.id}`}}])}}})});var v6=K((S6)=>{Object.defineProperty(S6,"__esModule",{value:!0});S6.Features=void 0;var P6=w(),y8=P6.StripeResource.method;S6.Features=P6.StripeResource.extend({create:y8({method:"POST",fullPath:"/v1/entitlements/features"}),retrieve:y8({method:"GET",fullPath:"/v1/entitlements/features/{id}"}),update:y8({method:"POST",fullPath:"/v1/entitlements/features/{id}"}),list:y8({method:"GET",fullPath:"/v1/entitlements/features",methodType:"list"})})});var f6=K((b6)=>{Object.defineProperty(b6,"__esModule",{value:!0});b6.FinancialAccounts=void 0;var y6=w(),Y0=y6.StripeResource.method;b6.FinancialAccounts=y6.StripeResource.extend({create:Y0({method:"POST",fullPath:"/v1/treasury/financial_accounts"}),retrieve:Y0({method:"GET",fullPath:"/v1/treasury/financial_accounts/{financial_account}"}),update:Y0({method:"POST",fullPath:"/v1/treasury/financial_accounts/{financial_account}"}),list:Y0({method:"GET",fullPath:"/v1/treasury/financial_accounts",methodType:"list"}),close:Y0({method:"POST",fullPath:"/v1/treasury/financial_accounts/{financial_account}/close"}),retrieveFeatures:Y0({method:"GET",fullPath:"/v1/treasury/financial_accounts/{financial_account}/features"}),updateFeatures:Y0({method:"POST",fullPath:"/v1/treasury/financial_accounts/{financial_account}/features"})})});var h6=K((_6)=>{Object.defineProperty(_6,"__esModule",{value:!0});_6.InboundTransfers=void 0;var M6=w(),t$=M6.StripeResource.method;_6.InboundTransfers=M6.StripeResource.extend({fail:t$({method:"POST",fullPath:"/v1/test_helpers/treasury/inbound_transfers/{id}/fail"}),returnInboundTransfer:t$({method:"POST",fullPath:"/v1/test_helpers/treasury/inbound_transfers/{id}/return"}),succeed:t$({method:"POST",fullPath:"/v1/test_helpers/treasury/inbound_transfers/{id}/succeed"})})});var n6=K((u6)=>{Object.defineProperty(u6,"__esModule",{value:!0});u6.InboundTransfers=void 0;var m6=w(),b8=m6.StripeResource.method;u6.InboundTransfers=m6.StripeResource.extend({create:b8({method:"POST",fullPath:"/v1/treasury/inbound_transfers"}),retrieve:b8({method:"GET",fullPath:"/v1/treasury/inbound_transfers/{id}"}),list:b8({method:"GET",fullPath:"/v1/treasury/inbound_transfers",methodType:"list"}),cancel:b8({method:"POST",fullPath:"/v1/treasury/inbound_transfers/{inbound_transfer}/cancel"})})});var i6=K((p6)=>{Object.defineProperty(p6,"__esModule",{value:!0});p6.Locations=void 0;var l6=w(),i0=l6.StripeResource.method;p6.Locations=l6.StripeResource.extend({create:i0({method:"POST",fullPath:"/v1/terminal/locations"}),retrieve:i0({method:"GET",fullPath:"/v1/terminal/locations/{location}"}),update:i0({method:"POST",fullPath:"/v1/terminal/locations/{location}"}),list:i0({method:"GET",fullPath:"/v1/terminal/locations",methodType:"list"}),del:i0({method:"DELETE",fullPath:"/v1/terminal/locations/{location}"})})});var r6=K((o6)=>{Object.defineProperty(o6,"__esModule",{value:!0});o6.MeterEventAdjustments=void 0;var a6=w(),fU=a6.StripeResource.method;o6.MeterEventAdjustments=a6.StripeResource.extend({create:fU({method:"POST",fullPath:"/v1/billing/meter_event_adjustments"})})});var Z7=K((e6)=>{Object.defineProperty(e6,"__esModule",{value:!0});e6.MeterEventAdjustments=void 0;var t6=w(),MU=t6.StripeResource.method;e6.MeterEventAdjustments=t6.StripeResource.extend({create:MU({method:"POST",fullPath:"/v2/billing/meter_event_adjustments"})})});var Y7=K((Q7)=>{Object.defineProperty(Q7,"__esModule",{value:!0});Q7.MeterEventSession=void 0;var J7=w(),_U=J7.StripeResource.method;Q7.MeterEventSession=J7.StripeResource.extend({create:_U({method:"POST",fullPath:"/v2/billing/meter_event_session"})})});var W7=K((V7)=>{Object.defineProperty(V7,"__esModule",{value:!0});V7.MeterEventStream=void 0;var G7=w(),gU=G7.StripeResource.method;V7.MeterEventStream=G7.StripeResource.extend({create:gU({method:"POST",fullPath:"/v2/billing/meter_event_stream",host:"meter-events.stripe.com"})})});var K7=K((z7)=>{Object.defineProperty(z7,"__esModule",{value:!0});z7.MeterEvents=void 0;var U7=w(),hU=U7.StripeResource.method;z7.MeterEvents=U7.StripeResource.extend({create:hU({method:"POST",fullPath:"/v1/billing/meter_events"})})});var D7=K((w7)=>{Object.defineProperty(w7,"__esModule",{value:!0});w7.MeterEvents=void 0;var H7=w(),mU=H7.StripeResource.method;w7.MeterEvents=H7.StripeResource.extend({create:mU({method:"POST",fullPath:"/v2/billing/meter_events"})})});var F7=K((q7)=>{Object.defineProperty(q7,"__esModule",{value:!0});q7.Meters=void 0;var O7=w(),G0=O7.StripeResource.method;q7.Meters=O7.StripeResource.extend({create:G0({method:"POST",fullPath:"/v1/billing/meters"}),retrieve:G0({method:"GET",fullPath:"/v1/billing/meters/{id}"}),update:G0({method:"POST",fullPath:"/v1/billing/meters/{id}"}),list:G0({method:"GET",fullPath:"/v1/billing/meters",methodType:"list"}),deactivate:G0({method:"POST",fullPath:"/v1/billing/meters/{id}/deactivate"}),listEventSummaries:G0({method:"GET",fullPath:"/v1/billing/meters/{id}/event_summaries",methodType:"list"}),reactivate:G0({method:"POST",fullPath:"/v1/billing/meters/{id}/reactivate"})})});var N7=K((k7)=>{Object.defineProperty(k7,"__esModule",{value:!0});k7.OnboardingLinks=void 0;var C7=w(),uU=C7.StripeResource.method;k7.OnboardingLinks=C7.StripeResource.extend({create:uU({method:"POST",fullPath:"/v1/terminal/onboarding_links"})})});var S7=K((I7)=>{Object.defineProperty(I7,"__esModule",{value:!0});I7.Orders=void 0;var x7=w(),a0=x7.StripeResource.method;I7.Orders=x7.StripeResource.extend({create:a0({method:"POST",fullPath:"/v1/climate/orders",requestSchema:{kind:"object",fields:{metric_tons:{kind:"decimal_string"}}},responseSchema:{kind:"object",fields:{metric_tons:{kind:"decimal_string"}}}}),retrieve:a0({method:"GET",fullPath:"/v1/climate/orders/{order}",responseSchema:{kind:"object",fields:{metric_tons:{kind:"decimal_string"}}}}),update:a0({method:"POST",fullPath:"/v1/climate/orders/{order}",responseSchema:{kind:"object",fields:{metric_tons:{kind:"decimal_string"}}}}),list:a0({method:"GET",fullPath:"/v1/climate/orders",methodType:"list",responseSchema:{kind:"object",fields:{data:{kind:"array",element:{kind:"object",fields:{metric_tons:{kind:"decimal_string"}}}}}}}),cancel:a0({method:"POST",fullPath:"/v1/climate/orders/{order}/cancel",responseSchema:{kind:"object",fields:{metric_tons:{kind:"decimal_string"}}}})})});var b7=K((v7)=>{Object.defineProperty(v7,"__esModule",{value:!0});v7.OutboundPayments=void 0;var R7=w(),j8=R7.StripeResource.method;v7.OutboundPayments=R7.StripeResource.extend({update:j8({method:"POST",fullPath:"/v1/test_helpers/treasury/outbound_payments/{id}"}),fail:j8({method:"POST",fullPath:"/v1/test_helpers/treasury/outbound_payments/{id}/fail"}),post:j8({method:"POST",fullPath:"/v1/test_helpers/treasury/outbound_payments/{id}/post"}),returnOutboundPayment:j8({method:"POST",fullPath:"/v1/test_helpers/treasury/outbound_payments/{id}/return"})})});var _7=K((f7)=>{Object.defineProperty(f7,"__esModule",{value:!0});f7.OutboundPayments=void 0;var j7=w(),f8=j7.StripeResource.method;f7.OutboundPayments=j7.StripeResource.extend({create:f8({method:"POST",fullPath:"/v1/treasury/outbound_payments"}),retrieve:f8({method:"GET",fullPath:"/v1/treasury/outbound_payments/{id}"}),list:f8({method:"GET",fullPath:"/v1/treasury/outbound_payments",methodType:"list"}),cancel:f8({method:"POST",fullPath:"/v1/treasury/outbound_payments/{id}/cancel"})})});var u7=K((h7)=>{Object.defineProperty(h7,"__esModule",{value:!0});h7.OutboundTransfers=void 0;var g7=w(),M8=g7.StripeResource.method;h7.OutboundTransfers=g7.StripeResource.extend({update:M8({method:"POST",fullPath:"/v1/test_helpers/treasury/outbound_transfers/{outbound_transfer}"}),fail:M8({method:"POST",fullPath:"/v1/test_helpers/treasury/outbound_transfers/{outbound_transfer}/fail"}),post:M8({method:"POST",fullPath:"/v1/test_helpers/treasury/outbound_transfers/{outbound_transfer}/post"}),returnOutboundTransfer:M8({method:"POST",fullPath:"/v1/test_helpers/treasury/outbound_transfers/{outbound_transfer}/return"})})});var p7=K((n7)=>{Object.defineProperty(n7,"__esModule",{value:!0});n7.OutboundTransfers=void 0;var c7=w(),_8=c7.StripeResource.method;n7.OutboundTransfers=c7.StripeResource.extend({create:_8({method:"POST",fullPath:"/v1/treasury/outbound_transfers"}),retrieve:_8({method:"GET",fullPath:"/v1/treasury/outbound_transfers/{outbound_transfer}"}),list:_8({method:"GET",fullPath:"/v1/treasury/outbound_transfers",methodType:"list"}),cancel:_8({method:"POST",fullPath:"/v1/treasury/outbound_transfers/{outbound_transfer}/cancel"})})});var o7=K((i7)=>{Object.defineProperty(i7,"__esModule",{value:!0});i7.PaymentEvaluations=void 0;var d7=w(),cU=d7.StripeResource.method;i7.PaymentEvaluations=d7.StripeResource.extend({create:cU({method:"POST",fullPath:"/v1/radar/payment_evaluations"})})});var e7=K((r7)=>{Object.defineProperty(r7,"__esModule",{value:!0});r7.PersonalizationDesigns=void 0;var s7=w(),g8=s7.StripeResource.method;r7.PersonalizationDesigns=s7.StripeResource.extend({create:g8({method:"POST",fullPath:"/v1/issuing/personalization_designs"}),retrieve:g8({method:"GET",fullPath:"/v1/issuing/personalization_designs/{personalization_design}"}),update:g8({method:"POST",fullPath:"/v1/issuing/personalization_designs/{personalization_design}"}),list:g8({method:"GET",fullPath:"/v1/issuing/personalization_designs",methodType:"list"})})});var QJ=K((ZJ)=>{Object.defineProperty(ZJ,"__esModule",{value:!0});ZJ.PersonalizationDesigns=void 0;var $J=w(),e$=$J.StripeResource.method;ZJ.PersonalizationDesigns=$J.StripeResource.extend({activate:e$({method:"POST",fullPath:"/v1/test_helpers/issuing/personalization_designs/{personalization_design}/activate"}),deactivate:e$({method:"POST",fullPath:"/v1/test_helpers/issuing/personalization_designs/{personalization_design}/deactivate"}),reject:e$({method:"POST",fullPath:"/v1/test_helpers/issuing/personalization_designs/{personalization_design}/reject"})})});var BJ=K((GJ)=>{Object.defineProperty(GJ,"__esModule",{value:!0});GJ.PhysicalBundles=void 0;var YJ=w(),XJ=YJ.StripeResource.method;GJ.PhysicalBundles=YJ.StripeResource.extend({retrieve:XJ({method:"GET",fullPath:"/v1/issuing/physical_bundles/{physical_bundle}"}),list:XJ({method:"GET",fullPath:"/v1/issuing/physical_bundles",methodType:"list"})})});var KJ=K((zJ)=>{Object.defineProperty(zJ,"__esModule",{value:!0});zJ.Products=void 0;var UJ=w(),WJ=UJ.StripeResource.method;zJ.Products=UJ.StripeResource.extend({retrieve:WJ({method:"GET",fullPath:"/v1/climate/products/{product}",responseSchema:{kind:"object",fields:{metric_tons_available:{kind:"decimal_string"}}}}),list:WJ({method:"GET",fullPath:"/v1/climate/products",methodType:"list",responseSchema:{kind:"object",fields:{data:{kind:"array",element:{kind:"object",fields:{metric_tons_available:{kind:"decimal_string"}}}}}}})})});var DJ=K((wJ)=>{Object.defineProperty(wJ,"__esModule",{value:!0});wJ.Readers=void 0;var HJ=w(),f=HJ.StripeResource.method;wJ.Readers=HJ.StripeResource.extend({create:f({method:"POST",fullPath:"/v1/terminal/readers"}),retrieve:f({method:"GET",fullPath:"/v1/terminal/readers/{reader}"}),update:f({method:"POST",fullPath:"/v1/terminal/readers/{reader}"}),list:f({method:"GET",fullPath:"/v1/terminal/readers",methodType:"list"}),del:f({method:"DELETE",fullPath:"/v1/terminal/readers/{reader}"}),cancelAction:f({method:"POST",fullPath:"/v1/terminal/readers/{reader}/cancel_action"}),collectInputs:f({method:"POST",fullPath:"/v1/terminal/readers/{reader}/collect_inputs"}),collectPaymentMethod:f({method:"POST",fullPath:"/v1/terminal/readers/{reader}/collect_payment_method"}),confirmPaymentIntent:f({method:"POST",fullPath:"/v1/terminal/readers/{reader}/confirm_payment_intent"}),processPaymentIntent:f({method:"POST",fullPath:"/v1/terminal/readers/{reader}/process_payment_intent"}),processSetupIntent:f({method:"POST",fullPath:"/v1/terminal/readers/{reader}/process_setup_intent"}),refundPayment:f({method:"POST",fullPath:"/v1/terminal/readers/{reader}/refund_payment"}),setReaderDisplay:f({method:"POST",fullPath:"/v1/terminal/readers/{reader}/set_reader_display"})})});var FJ=K((qJ)=>{Object.defineProperty(qJ,"__esModule",{value:!0});qJ.Readers=void 0;var OJ=w(),$9=OJ.StripeResource.method;qJ.Readers=OJ.StripeResource.extend({presentPaymentMethod:$9({method:"POST",fullPath:"/v1/test_helpers/terminal/readers/{reader}/present_payment_method"}),succeedInputCollection:$9({method:"POST",fullPath:"/v1/test_helpers/terminal/readers/{reader}/succeed_input_collection"}),timeoutInputCollection:$9({method:"POST",fullPath:"/v1/test_helpers/terminal/readers/{reader}/timeout_input_collection"})})});var NJ=K((kJ)=>{Object.defineProperty(kJ,"__esModule",{value:!0});kJ.ReceivedCredits=void 0;var CJ=w(),nU=CJ.StripeResource.method;kJ.ReceivedCredits=CJ.StripeResource.extend({create:nU({method:"POST",fullPath:"/v1/test_helpers/treasury/received_credits"})})});var RJ=K((PJ)=>{Object.defineProperty(PJ,"__esModule",{value:!0});PJ.ReceivedCredits=void 0;var IJ=w(),xJ=IJ.StripeResource.method;PJ.ReceivedCredits=IJ.StripeResource.extend({retrieve:xJ({method:"GET",fullPath:"/v1/treasury/received_credits/{id}"}),list:xJ({method:"GET",fullPath:"/v1/treasury/received_credits",methodType:"list"})})});var jJ=K((yJ)=>{Object.defineProperty(yJ,"__esModule",{value:!0});yJ.ReceivedDebits=void 0;var vJ=w(),lU=vJ.StripeResource.method;yJ.ReceivedDebits=vJ.StripeResource.extend({create:lU({method:"POST",fullPath:"/v1/test_helpers/treasury/received_debits"})})});var hJ=K((_J)=>{Object.defineProperty(_J,"__esModule",{value:!0});_J.ReceivedDebits=void 0;var MJ=w(),fJ=MJ.StripeResource.method;_J.ReceivedDebits=MJ.StripeResource.extend({retrieve:fJ({method:"GET",fullPath:"/v1/treasury/received_debits/{id}"}),list:fJ({method:"GET",fullPath:"/v1/treasury/received_debits",methodType:"list"})})});var nJ=K((uJ)=>{Object.defineProperty(uJ,"__esModule",{value:!0});uJ.Refunds=void 0;var mJ=w(),pU=mJ.StripeResource.method;uJ.Refunds=mJ.StripeResource.extend({expire:pU({method:"POST",fullPath:"/v1/test_helpers/refunds/{refund}/expire"})})});var iJ=K((pJ)=>{Object.defineProperty(pJ,"__esModule",{value:!0});pJ.Registrations=void 0;var lJ=w(),h8=lJ.StripeResource.method;pJ.Registrations=lJ.StripeResource.extend({create:h8({method:"POST",fullPath:"/v1/tax/registrations"}),retrieve:h8({method:"GET",fullPath:"/v1/tax/registrations/{id}"}),update:h8({method:"POST",fullPath:"/v1/tax/registrations/{id}"}),list:h8({method:"GET",fullPath:"/v1/tax/registrations",methodType:"list"})})});var rJ=K((oJ)=>{Object.defineProperty(oJ,"__esModule",{value:!0});oJ.ReportRuns=void 0;var aJ=w(),Z9=aJ.StripeResource.method;oJ.ReportRuns=aJ.StripeResource.extend({create:Z9({method:"POST",fullPath:"/v1/reporting/report_runs"}),retrieve:Z9({method:"GET",fullPath:"/v1/reporting/report_runs/{report_run}"}),list:Z9({method:"GET",fullPath:"/v1/reporting/report_runs",methodType:"list"})})});var J5=K(($5)=>{Object.defineProperty($5,"__esModule",{value:!0});$5.ReportTypes=void 0;var eJ=w(),tJ=eJ.StripeResource.method;$5.ReportTypes=eJ.StripeResource.extend({retrieve:tJ({method:"GET",fullPath:"/v1/reporting/report_types/{report_type}"}),list:tJ({method:"GET",fullPath:"/v1/reporting/report_types",methodType:"list"})})});var G5=K((X5)=>{Object.defineProperty(X5,"__esModule",{value:!0});X5.Requests=void 0;var Q5=w(),J9=Q5.StripeResource.method;X5.Requests=Q5.StripeResource.extend({create:J9({method:"POST",fullPath:"/v1/forwarding/requests"}),retrieve:J9({method:"GET",fullPath:"/v1/forwarding/requests/{id}"}),list:J9({method:"GET",fullPath:"/v1/forwarding/requests",methodType:"list"})})});var z5=K((W5)=>{Object.defineProperty(W5,"__esModule",{value:!0});W5.ScheduledQueryRuns=void 0;var B5=w(),V5=B5.StripeResource.method;W5.ScheduledQueryRuns=B5.StripeResource.extend({retrieve:V5({method:"GET",fullPath:"/v1/sigma/scheduled_query_runs/{scheduled_query_run}"}),list:V5({method:"GET",fullPath:"/v1/sigma/scheduled_query_runs",methodType:"list"})})});var w5=K((K5)=>{Object.defineProperty(K5,"__esModule",{value:!0});K5.Secrets=void 0;var L5=w(),m8=L5.StripeResource.method;K5.Secrets=L5.StripeResource.extend({create:m8({method:"POST",fullPath:"/v1/apps/secrets"}),list:m8({method:"GET",fullPath:"/v1/apps/secrets",methodType:"list"}),deleteWhere:m8({method:"POST",fullPath:"/v1/apps/secrets/delete"}),find:m8({method:"GET",fullPath:"/v1/apps/secrets/find"})})});var q5=K((D5)=>{Object.defineProperty(D5,"__esModule",{value:!0});D5.Sessions=void 0;var T5=w(),dU=T5.StripeResource.method;D5.Sessions=T5.StripeResource.extend({create:dU({method:"POST",fullPath:"/v1/billing_portal/sessions"})})});var k5=K((F5)=>{Object.defineProperty(F5,"__esModule",{value:!0});F5.Sessions=void 0;var E5=w(),q0=E5.StripeResource.method;F5.Sessions=E5.StripeResource.extend({create:q0({method:"POST",fullPath:"/v1/checkout/sessions",requestSchema:{kind:"object",fields:{line_items:{kind:"array",element:{kind:"object",fields:{price_data:{kind:"object",fields:{unit_amount_decimal:{kind:"decimal_string"}}}}}}}},responseSchema:{kind:"object",fields:{currency_conversion:{kind:"nullable",inner:{kind:"object",fields:{fx_rate:{kind:"decimal_string"}}}},line_items:{kind:"object",fields:{data:{kind:"array",element:{kind:"object",fields:{price:{kind:"nullable",inner:{kind:"object",fields:{currency_options:{kind:"array",element:{kind:"object",fields:{tiers:{kind:"array",element:{kind:"object",fields:{flat_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},tiers:{kind:"array",element:{kind:"object",fields:{flat_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}}}}}}}}),retrieve:q0({method:"GET",fullPath:"/v1/checkout/sessions/{session}",responseSchema:{kind:"object",fields:{currency_conversion:{kind:"nullable",inner:{kind:"object",fields:{fx_rate:{kind:"decimal_string"}}}},line_items:{kind:"object",fields:{data:{kind:"array",element:{kind:"object",fields:{price:{kind:"nullable",inner:{kind:"object",fields:{currency_options:{kind:"array",element:{kind:"object",fields:{tiers:{kind:"array",element:{kind:"object",fields:{flat_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},tiers:{kind:"array",element:{kind:"object",fields:{flat_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}}}}}}}}),update:q0({method:"POST",fullPath:"/v1/checkout/sessions/{session}",requestSchema:{kind:"object",fields:{line_items:{kind:"array",element:{kind:"object",fields:{price_data:{kind:"object",fields:{unit_amount_decimal:{kind:"decimal_string"}}}}}}}},responseSchema:{kind:"object",fields:{currency_conversion:{kind:"nullable",inner:{kind:"object",fields:{fx_rate:{kind:"decimal_string"}}}},line_items:{kind:"object",fields:{data:{kind:"array",element:{kind:"object",fields:{price:{kind:"nullable",inner:{kind:"object",fields:{currency_options:{kind:"array",element:{kind:"object",fields:{tiers:{kind:"array",element:{kind:"object",fields:{flat_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},tiers:{kind:"array",element:{kind:"object",fields:{flat_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}}}}}}}}),list:q0({method:"GET",fullPath:"/v1/checkout/sessions",methodType:"list",responseSchema:{kind:"object",fields:{data:{kind:"array",element:{kind:"object",fields:{currency_conversion:{kind:"nullable",inner:{kind:"object",fields:{fx_rate:{kind:"decimal_string"}}}},line_items:{kind:"object",fields:{data:{kind:"array",element:{kind:"object",fields:{price:{kind:"nullable",inner:{kind:"object",fields:{currency_options:{kind:"array",element:{kind:"object",fields:{tiers:{kind:"array",element:{kind:"object",fields:{flat_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},tiers:{kind:"array",element:{kind:"object",fields:{flat_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}}}}}}}}}}}),expire:q0({method:"POST",fullPath:"/v1/checkout/sessions/{session}/expire",responseSchema:{kind:"object",fields:{currency_conversion:{kind:"nullable",inner:{kind:"object",fields:{fx_rate:{kind:"decimal_string"}}}},line_items:{kind:"object",fields:{data:{kind:"array",element:{kind:"object",fields:{price:{kind:"nullable",inner:{kind:"object",fields:{currency_options:{kind:"array",element:{kind:"object",fields:{tiers:{kind:"array",element:{kind:"object",fields:{flat_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},tiers:{kind:"array",element:{kind:"object",fields:{flat_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}}}}}}}}),listLineItems:q0({method:"GET",fullPath:"/v1/checkout/sessions/{session}/line_items",methodType:"list",responseSchema:{kind:"object",fields:{data:{kind:"array",element:{kind:"object",fields:{price:{kind:"nullable",inner:{kind:"object",fields:{currency_options:{kind:"array",element:{kind:"object",fields:{tiers:{kind:"array",element:{kind:"object",fields:{flat_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},tiers:{kind:"array",element:{kind:"object",fields:{flat_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}}}}}})})});var P5=K((x5)=>{Object.defineProperty(x5,"__esModule",{value:!0});x5.Sessions=void 0;var N5=w(),A5=N5.StripeResource.method;x5.Sessions=N5.StripeResource.extend({create:A5({method:"POST",fullPath:"/v1/financial_connections/sessions"}),retrieve:A5({method:"GET",fullPath:"/v1/financial_connections/sessions/{session}"})})});var b5=K((v5)=>{Object.defineProperty(v5,"__esModule",{value:!0});v5.Settings=void 0;var R5=w(),S5=R5.StripeResource.method;v5.Settings=R5.StripeResource.extend({retrieve:S5({method:"GET",fullPath:"/v1/tax/settings"}),update:S5({method:"POST",fullPath:"/v1/tax/settings"})})});var g5=K((M5)=>{Object.defineProperty(M5,"__esModule",{value:!0});M5.Suppliers=void 0;var f5=w(),j5=f5.StripeResource.method;M5.Suppliers=f5.StripeResource.extend({retrieve:j5({method:"GET",fullPath:"/v1/climate/suppliers/{supplier}"}),list:j5({method:"GET",fullPath:"/v1/climate/suppliers",methodType:"list"})})});var c5=K((m5)=>{Object.defineProperty(m5,"__esModule",{value:!0});m5.TestClocks=void 0;var h5=w(),o0=h5.StripeResource.method;m5.TestClocks=h5.StripeResource.extend({create:o0({method:"POST",fullPath:"/v1/test_helpers/test_clocks"}),retrieve:o0({method:"GET",fullPath:"/v1/test_helpers/test_clocks/{test_clock}"}),list:o0({method:"GET",fullPath:"/v1/test_helpers/test_clocks",methodType:"list"}),del:o0({method:"DELETE",fullPath:"/v1/test_helpers/test_clocks/{test_clock}"}),advance:o0({method:"POST",fullPath:"/v1/test_helpers/test_clocks/{test_clock}/advance"})})});var d5=K((l5)=>{Object.defineProperty(l5,"__esModule",{value:!0});l5.Tokens=void 0;var n5=w(),Q9=n5.StripeResource.method;l5.Tokens=n5.StripeResource.extend({retrieve:Q9({method:"GET",fullPath:"/v1/issuing/tokens/{token}"}),update:Q9({method:"POST",fullPath:"/v1/issuing/tokens/{token}"}),list:Q9({method:"GET",fullPath:"/v1/issuing/tokens",methodType:"list"})})});var r5=K((o5)=>{Object.defineProperty(o5,"__esModule",{value:!0});o5.TransactionEntries=void 0;var a5=w(),i5=a5.StripeResource.method;o5.TransactionEntries=a5.StripeResource.extend({retrieve:i5({method:"GET",fullPath:"/v1/treasury/transaction_entries/{id}",responseSchema:{kind:"object",fields:{flow_details:{kind:"nullable",inner:{kind:"object",fields:{issuing_authorization:{kind:"object",fields:{fleet:{kind:"nullable",inner:{kind:"object",fields:{reported_breakdown:{kind:"nullable",inner:{kind:"object",fields:{fuel:{kind:"nullable",inner:{kind:"object",fields:{gross_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},non_fuel:{kind:"nullable",inner:{kind:"object",fields:{gross_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},tax:{kind:"nullable",inner:{kind:"object",fields:{local_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},national_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}}}}}},fuel:{kind:"nullable",inner:{kind:"object",fields:{quantity_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_cost_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},transactions:{kind:"array",element:{kind:"object",fields:{purchase_details:{kind:"nullable",inner:{kind:"object",fields:{fleet:{kind:"nullable",inner:{kind:"object",fields:{reported_breakdown:{kind:"nullable",inner:{kind:"object",fields:{fuel:{kind:"nullable",inner:{kind:"object",fields:{gross_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},non_fuel:{kind:"nullable",inner:{kind:"object",fields:{gross_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},tax:{kind:"nullable",inner:{kind:"object",fields:{local_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},national_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}}}}}},fuel:{kind:"nullable",inner:{kind:"object",fields:{quantity_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_cost_decimal:{kind:"decimal_string"}}}}}}}}}}}}}}}}}}),list:i5({method:"GET",fullPath:"/v1/treasury/transaction_entries",methodType:"list",responseSchema:{kind:"object",fields:{data:{kind:"array",element:{kind:"object",fields:{flow_details:{kind:"nullable",inner:{kind:"object",fields:{issuing_authorization:{kind:"object",fields:{fleet:{kind:"nullable",inner:{kind:"object",fields:{reported_breakdown:{kind:"nullable",inner:{kind:"object",fields:{fuel:{kind:"nullable",inner:{kind:"object",fields:{gross_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},non_fuel:{kind:"nullable",inner:{kind:"object",fields:{gross_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},tax:{kind:"nullable",inner:{kind:"object",fields:{local_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},national_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}}}}}},fuel:{kind:"nullable",inner:{kind:"object",fields:{quantity_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_cost_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},transactions:{kind:"array",element:{kind:"object",fields:{purchase_details:{kind:"nullable",inner:{kind:"object",fields:{fleet:{kind:"nullable",inner:{kind:"object",fields:{reported_breakdown:{kind:"nullable",inner:{kind:"object",fields:{fuel:{kind:"nullable",inner:{kind:"object",fields:{gross_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},non_fuel:{kind:"nullable",inner:{kind:"object",fields:{gross_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},tax:{kind:"nullable",inner:{kind:"object",fields:{local_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},national_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}}}}}},fuel:{kind:"nullable",inner:{kind:"object",fields:{quantity_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_cost_decimal:{kind:"decimal_string"}}}}}}}}}}}}}}}}}}}}})})});var JQ=K(($Q)=>{Object.defineProperty($Q,"__esModule",{value:!0});$Q.Transactions=void 0;var e5=w(),t5=e5.StripeResource.method;$Q.Transactions=e5.StripeResource.extend({retrieve:t5({method:"GET",fullPath:"/v1/financial_connections/transactions/{transaction}"}),list:t5({method:"GET",fullPath:"/v1/financial_connections/transactions",methodType:"list"})})});var GQ=K((XQ)=>{Object.defineProperty(XQ,"__esModule",{value:!0});XQ.Transactions=void 0;var QQ=w(),X9=QQ.StripeResource.method;XQ.Transactions=QQ.StripeResource.extend({retrieve:X9({method:"GET",fullPath:"/v1/issuing/transactions/{transaction}",responseSchema:{kind:"object",fields:{purchase_details:{kind:"nullable",inner:{kind:"object",fields:{fleet:{kind:"nullable",inner:{kind:"object",fields:{reported_breakdown:{kind:"nullable",inner:{kind:"object",fields:{fuel:{kind:"nullable",inner:{kind:"object",fields:{gross_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},non_fuel:{kind:"nullable",inner:{kind:"object",fields:{gross_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},tax:{kind:"nullable",inner:{kind:"object",fields:{local_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},national_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}}}}}},fuel:{kind:"nullable",inner:{kind:"object",fields:{quantity_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_cost_decimal:{kind:"decimal_string"}}}}}}}}}}),update:X9({method:"POST",fullPath:"/v1/issuing/transactions/{transaction}",responseSchema:{kind:"object",fields:{purchase_details:{kind:"nullable",inner:{kind:"object",fields:{fleet:{kind:"nullable",inner:{kind:"object",fields:{reported_breakdown:{kind:"nullable",inner:{kind:"object",fields:{fuel:{kind:"nullable",inner:{kind:"object",fields:{gross_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},non_fuel:{kind:"nullable",inner:{kind:"object",fields:{gross_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},tax:{kind:"nullable",inner:{kind:"object",fields:{local_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},national_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}}}}}},fuel:{kind:"nullable",inner:{kind:"object",fields:{quantity_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_cost_decimal:{kind:"decimal_string"}}}}}}}}}}),list:X9({method:"GET",fullPath:"/v1/issuing/transactions",methodType:"list",responseSchema:{kind:"object",fields:{data:{kind:"array",element:{kind:"object",fields:{purchase_details:{kind:"nullable",inner:{kind:"object",fields:{fleet:{kind:"nullable",inner:{kind:"object",fields:{reported_breakdown:{kind:"nullable",inner:{kind:"object",fields:{fuel:{kind:"nullable",inner:{kind:"object",fields:{gross_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},non_fuel:{kind:"nullable",inner:{kind:"object",fields:{gross_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},tax:{kind:"nullable",inner:{kind:"object",fields:{local_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},national_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}}}}}},fuel:{kind:"nullable",inner:{kind:"object",fields:{quantity_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_cost_decimal:{kind:"decimal_string"}}}}}}}}}}}}})})});var UQ=K((BQ)=>{Object.defineProperty(BQ,"__esModule",{value:!0});BQ.Transactions=void 0;var VQ=w(),u8=VQ.StripeResource.method;BQ.Transactions=VQ.StripeResource.extend({retrieve:u8({method:"GET",fullPath:"/v1/tax/transactions/{transaction}"}),createFromCalculation:u8({method:"POST",fullPath:"/v1/tax/transactions/create_from_calculation"}),createReversal:u8({method:"POST",fullPath:"/v1/tax/transactions/create_reversal"}),listLineItems:u8({method:"GET",fullPath:"/v1/tax/transactions/{transaction}/line_items",methodType:"list"})})});var HQ=K((LQ)=>{Object.defineProperty(LQ,"__esModule",{value:!0});LQ.Transactions=void 0;var zQ=w(),Y9=zQ.StripeResource.method;LQ.Transactions=zQ.StripeResource.extend({createForceCapture:Y9({method:"POST",fullPath:"/v1/test_helpers/issuing/transactions/create_force_capture",requestSchema:{kind:"object",fields:{purchase_details:{kind:"object",fields:{fleet:{kind:"object",fields:{reported_breakdown:{kind:"object",fields:{fuel:{kind:"object",fields:{gross_amount_decimal:{kind:"decimal_string"}}},non_fuel:{kind:"object",fields:{gross_amount_decimal:{kind:"decimal_string"}}},tax:{kind:"object",fields:{local_amount_decimal:{kind:"decimal_string"},national_amount_decimal:{kind:"decimal_string"}}}}}}},fuel:{kind:"object",fields:{quantity_decimal:{kind:"decimal_string"},unit_cost_decimal:{kind:"decimal_string"}}},receipt:{kind:"array",element:{kind:"object",fields:{quantity:{kind:"decimal_string"}}}}}}}},responseSchema:{kind:"object",fields:{purchase_details:{kind:"nullable",inner:{kind:"object",fields:{fleet:{kind:"nullable",inner:{kind:"object",fields:{reported_breakdown:{kind:"nullable",inner:{kind:"object",fields:{fuel:{kind:"nullable",inner:{kind:"object",fields:{gross_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},non_fuel:{kind:"nullable",inner:{kind:"object",fields:{gross_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},tax:{kind:"nullable",inner:{kind:"object",fields:{local_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},national_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}}}}}},fuel:{kind:"nullable",inner:{kind:"object",fields:{quantity_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_cost_decimal:{kind:"decimal_string"}}}}}}}}}}),createUnlinkedRefund:Y9({method:"POST",fullPath:"/v1/test_helpers/issuing/transactions/create_unlinked_refund",requestSchema:{kind:"object",fields:{purchase_details:{kind:"object",fields:{fleet:{kind:"object",fields:{reported_breakdown:{kind:"object",fields:{fuel:{kind:"object",fields:{gross_amount_decimal:{kind:"decimal_string"}}},non_fuel:{kind:"object",fields:{gross_amount_decimal:{kind:"decimal_string"}}},tax:{kind:"object",fields:{local_amount_decimal:{kind:"decimal_string"},national_amount_decimal:{kind:"decimal_string"}}}}}}},fuel:{kind:"object",fields:{quantity_decimal:{kind:"decimal_string"},unit_cost_decimal:{kind:"decimal_string"}}},receipt:{kind:"array",element:{kind:"object",fields:{quantity:{kind:"decimal_string"}}}}}}}},responseSchema:{kind:"object",fields:{purchase_details:{kind:"nullable",inner:{kind:"object",fields:{fleet:{kind:"nullable",inner:{kind:"object",fields:{reported_breakdown:{kind:"nullable",inner:{kind:"object",fields:{fuel:{kind:"nullable",inner:{kind:"object",fields:{gross_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},non_fuel:{kind:"nullable",inner:{kind:"object",fields:{gross_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},tax:{kind:"nullable",inner:{kind:"object",fields:{local_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},national_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}}}}}},fuel:{kind:"nullable",inner:{kind:"object",fields:{quantity_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_cost_decimal:{kind:"decimal_string"}}}}}}}}}}),refund:Y9({method:"POST",fullPath:"/v1/test_helpers/issuing/transactions/{transaction}/refund",responseSchema:{kind:"object",fields:{purchase_details:{kind:"nullable",inner:{kind:"object",fields:{fleet:{kind:"nullable",inner:{kind:"object",fields:{reported_breakdown:{kind:"nullable",inner:{kind:"object",fields:{fuel:{kind:"nullable",inner:{kind:"object",fields:{gross_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},non_fuel:{kind:"nullable",inner:{kind:"object",fields:{gross_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},tax:{kind:"nullable",inner:{kind:"object",fields:{local_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},national_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}}}}}},fuel:{kind:"nullable",inner:{kind:"object",fields:{quantity_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_cost_decimal:{kind:"decimal_string"}}}}}}}}}})})});var qQ=K((DQ)=>{Object.defineProperty(DQ,"__esModule",{value:!0});DQ.Transactions=void 0;var TQ=w(),wQ=TQ.StripeResource.method;DQ.Transactions=TQ.StripeResource.extend({retrieve:wQ({method:"GET",fullPath:"/v1/treasury/transactions/{id}",responseSchema:{kind:"object",fields:{entries:{kind:"nullable",inner:{kind:"object",fields:{data:{kind:"array",element:{kind:"object",fields:{flow_details:{kind:"nullable",inner:{kind:"object",fields:{issuing_authorization:{kind:"object",fields:{fleet:{kind:"nullable",inner:{kind:"object",fields:{reported_breakdown:{kind:"nullable",inner:{kind:"object",fields:{fuel:{kind:"nullable",inner:{kind:"object",fields:{gross_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},non_fuel:{kind:"nullable",inner:{kind:"object",fields:{gross_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},tax:{kind:"nullable",inner:{kind:"object",fields:{local_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},national_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}}}}}},fuel:{kind:"nullable",inner:{kind:"object",fields:{quantity_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_cost_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},transactions:{kind:"array",element:{kind:"object",fields:{purchase_details:{kind:"nullable",inner:{kind:"object",fields:{fleet:{kind:"nullable",inner:{kind:"object",fields:{reported_breakdown:{kind:"nullable",inner:{kind:"object",fields:{fuel:{kind:"nullable",inner:{kind:"object",fields:{gross_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},non_fuel:{kind:"nullable",inner:{kind:"object",fields:{gross_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},tax:{kind:"nullable",inner:{kind:"object",fields:{local_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},national_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}}}}}},fuel:{kind:"nullable",inner:{kind:"object",fields:{quantity_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_cost_decimal:{kind:"decimal_string"}}}}}}}}}}}}}}}}}}}}}}}}),list:wQ({method:"GET",fullPath:"/v1/treasury/transactions",methodType:"list",responseSchema:{kind:"object",fields:{data:{kind:"array",element:{kind:"object",fields:{entries:{kind:"nullable",inner:{kind:"object",fields:{data:{kind:"array",element:{kind:"object",fields:{flow_details:{kind:"nullable",inner:{kind:"object",fields:{issuing_authorization:{kind:"object",fields:{fleet:{kind:"nullable",inner:{kind:"object",fields:{reported_breakdown:{kind:"nullable",inner:{kind:"object",fields:{fuel:{kind:"nullable",inner:{kind:"object",fields:{gross_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},non_fuel:{kind:"nullable",inner:{kind:"object",fields:{gross_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},tax:{kind:"nullable",inner:{kind:"object",fields:{local_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},national_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}}}}}},fuel:{kind:"nullable",inner:{kind:"object",fields:{quantity_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_cost_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},transactions:{kind:"array",element:{kind:"object",fields:{purchase_details:{kind:"nullable",inner:{kind:"object",fields:{fleet:{kind:"nullable",inner:{kind:"object",fields:{reported_breakdown:{kind:"nullable",inner:{kind:"object",fields:{fuel:{kind:"nullable",inner:{kind:"object",fields:{gross_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},non_fuel:{kind:"nullable",inner:{kind:"object",fields:{gross_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},tax:{kind:"nullable",inner:{kind:"object",fields:{local_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},national_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}}}}}},fuel:{kind:"nullable",inner:{kind:"object",fields:{quantity_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_cost_decimal:{kind:"decimal_string"}}}}}}}}}}}}}}}}}}}}}}}}}}})})});var kQ=K((FQ)=>{Object.defineProperty(FQ,"__esModule",{value:!0});FQ.ValueListItems=void 0;var EQ=w(),c8=EQ.StripeResource.method;FQ.ValueListItems=EQ.StripeResource.extend({create:c8({method:"POST",fullPath:"/v1/radar/value_list_items"}),retrieve:c8({method:"GET",fullPath:"/v1/radar/value_list_items/{item}"}),list:c8({method:"GET",fullPath:"/v1/radar/value_list_items",methodType:"list"}),del:c8({method:"DELETE",fullPath:"/v1/radar/value_list_items/{item}"})})});var IQ=K((NQ)=>{Object.defineProperty(NQ,"__esModule",{value:!0});NQ.ValueLists=void 0;var AQ=w(),s0=AQ.StripeResource.method;NQ.ValueLists=AQ.StripeResource.extend({create:s0({method:"POST",fullPath:"/v1/radar/value_lists"}),retrieve:s0({method:"GET",fullPath:"/v1/radar/value_lists/{value_list}"}),update:s0({method:"POST",fullPath:"/v1/radar/value_lists/{value_list}"}),list:s0({method:"GET",fullPath:"/v1/radar/value_lists",methodType:"list"}),del:s0({method:"DELETE",fullPath:"/v1/radar/value_lists/{value_list}"})})});var yQ=K((RQ)=>{Object.defineProperty(RQ,"__esModule",{value:!0});RQ.VerificationReports=void 0;var SQ=w(),PQ=SQ.StripeResource.method;RQ.VerificationReports=SQ.StripeResource.extend({retrieve:PQ({method:"GET",fullPath:"/v1/identity/verification_reports/{report}"}),list:PQ({method:"GET",fullPath:"/v1/identity/verification_reports",methodType:"list"})})});var MQ=K((jQ)=>{Object.defineProperty(jQ,"__esModule",{value:!0});jQ.VerificationSessions=void 0;var bQ=w(),E0=bQ.StripeResource.method;jQ.VerificationSessions=bQ.StripeResource.extend({create:E0({method:"POST",fullPath:"/v1/identity/verification_sessions"}),retrieve:E0({method:"GET",fullPath:"/v1/identity/verification_sessions/{session}"}),update:E0({method:"POST",fullPath:"/v1/identity/verification_sessions/{session}"}),list:E0({method:"GET",fullPath:"/v1/identity/verification_sessions",methodType:"list"}),cancel:E0({method:"POST",fullPath:"/v1/identity/verification_sessions/{session}/cancel"}),redact:E0({method:"POST",fullPath:"/v1/identity/verification_sessions/{session}/redact"})})});var G9=K((gQ)=>{Object.defineProperty(gQ,"__esModule",{value:!0});gQ.Accounts=void 0;var _Q=w(),I=_Q.StripeResource.method;gQ.Accounts=_Q.StripeResource.extend({create:I({method:"POST",fullPath:"/v1/accounts"}),retrieve($,...Z){if(typeof $==="string")return I({method:"GET",fullPath:"/v1/accounts/{id}"}).apply(this,[$,...Z]);else{if($===null||$===void 0)[].shift.apply([$,...Z]);return I({method:"GET",fullPath:"/v1/account"}).apply(this,[$,...Z])}},update:I({method:"POST",fullPath:"/v1/accounts/{account}"}),list:I({method:"GET",fullPath:"/v1/accounts",methodType:"list"}),del:I({method:"DELETE",fullPath:"/v1/accounts/{account}"}),createExternalAccount:I({method:"POST",fullPath:"/v1/accounts/{account}/external_accounts"}),createLoginLink:I({method:"POST",fullPath:"/v1/accounts/{account}/login_links"}),createPerson:I({method:"POST",fullPath:"/v1/accounts/{account}/persons"}),deleteExternalAccount:I({method:"DELETE",fullPath:"/v1/accounts/{account}/external_accounts/{id}"}),deletePerson:I({method:"DELETE",fullPath:"/v1/accounts/{account}/persons/{person}"}),listCapabilities:I({method:"GET",fullPath:"/v1/accounts/{account}/capabilities",methodType:"list"}),listExternalAccounts:I({method:"GET",fullPath:"/v1/accounts/{account}/external_accounts",methodType:"list"}),listPersons:I({method:"GET",fullPath:"/v1/accounts/{account}/persons",methodType:"list"}),reject:I({method:"POST",fullPath:"/v1/accounts/{account}/reject"}),retrieveCurrent:I({method:"GET",fullPath:"/v1/account"}),retrieveCapability:I({method:"GET",fullPath:"/v1/accounts/{account}/capabilities/{capability}"}),retrieveExternalAccount:I({method:"GET",fullPath:"/v1/accounts/{account}/external_accounts/{id}"}),retrievePerson:I({method:"GET",fullPath:"/v1/accounts/{account}/persons/{person}"}),updateCapability:I({method:"POST",fullPath:"/v1/accounts/{account}/capabilities/{capability}"}),updateExternalAccount:I({method:"POST",fullPath:"/v1/accounts/{account}/external_accounts/{id}"}),updatePerson:I({method:"POST",fullPath:"/v1/accounts/{account}/persons/{person}"})})});var nQ=K((uQ)=>{Object.defineProperty(uQ,"__esModule",{value:!0});uQ.AccountLinks=void 0;var mQ=w(),iU=mQ.StripeResource.method;uQ.AccountLinks=mQ.StripeResource.extend({create:iU({method:"POST",fullPath:"/v1/account_links"})})});var iQ=K((pQ)=>{Object.defineProperty(pQ,"__esModule",{value:!0});pQ.AccountSessions=void 0;var lQ=w(),aU=lQ.StripeResource.method;pQ.AccountSessions=lQ.StripeResource.extend({create:aU({method:"POST",fullPath:"/v1/account_sessions"})})});var rQ=K((oQ)=>{Object.defineProperty(oQ,"__esModule",{value:!0});oQ.ApplePayDomains=void 0;var aQ=w(),n8=aQ.StripeResource.method;oQ.ApplePayDomains=aQ.StripeResource.extend({create:n8({method:"POST",fullPath:"/v1/apple_pay/domains"}),retrieve:n8({method:"GET",fullPath:"/v1/apple_pay/domains/{domain}"}),list:n8({method:"GET",fullPath:"/v1/apple_pay/domains",methodType:"list"}),del:n8({method:"DELETE",fullPath:"/v1/apple_pay/domains/{domain}"})})});var ZX=K((eQ)=>{Object.defineProperty(eQ,"__esModule",{value:!0});eQ.ApplicationFees=void 0;var tQ=w(),F0=tQ.StripeResource.method;eQ.ApplicationFees=tQ.StripeResource.extend({retrieve:F0({method:"GET",fullPath:"/v1/application_fees/{id}"}),list:F0({method:"GET",fullPath:"/v1/application_fees",methodType:"list"}),createRefund:F0({method:"POST",fullPath:"/v1/application_fees/{id}/refunds"}),listRefunds:F0({method:"GET",fullPath:"/v1/application_fees/{id}/refunds",methodType:"list"}),retrieveRefund:F0({method:"GET",fullPath:"/v1/application_fees/{fee}/refunds/{id}"}),updateRefund:F0({method:"POST",fullPath:"/v1/application_fees/{fee}/refunds/{id}"})})});var YX=K((QX)=>{Object.defineProperty(QX,"__esModule",{value:!0});QX.Balance=void 0;var JX=w(),oU=JX.StripeResource.method;QX.Balance=JX.StripeResource.extend({retrieve:oU({method:"GET",fullPath:"/v1/balance"})})});var UX=K((BX)=>{Object.defineProperty(BX,"__esModule",{value:!0});BX.BalanceSettings=void 0;var VX=w(),GX=VX.StripeResource.method;BX.BalanceSettings=VX.StripeResource.extend({retrieve:GX({method:"GET",fullPath:"/v1/balance_settings"}),update:GX({method:"POST",fullPath:"/v1/balance_settings"})})});var wX=K((KX)=>{Object.defineProperty(KX,"__esModule",{value:!0});KX.BalanceTransactions=void 0;var LX=w(),zX=LX.StripeResource.method;KX.BalanceTransactions=LX.StripeResource.extend({retrieve:zX({method:"GET",fullPath:"/v1/balance_transactions/{id}"}),list:zX({method:"GET",fullPath:"/v1/balance_transactions",methodType:"list"})})});var qX=K((DX)=>{Object.defineProperty(DX,"__esModule",{value:!0});DX.Charges=void 0;var TX=w(),C0=TX.StripeResource.method;DX.Charges=TX.StripeResource.extend({create:C0({method:"POST",fullPath:"/v1/charges"}),retrieve:C0({method:"GET",fullPath:"/v1/charges/{charge}"}),update:C0({method:"POST",fullPath:"/v1/charges/{charge}"}),list:C0({method:"GET",fullPath:"/v1/charges",methodType:"list"}),capture:C0({method:"POST",fullPath:"/v1/charges/{charge}/capture"}),search:C0({method:"GET",fullPath:"/v1/charges/search",methodType:"search"})})});var kX=K((FX)=>{Object.defineProperty(FX,"__esModule",{value:!0});FX.ConfirmationTokens=void 0;var EX=w(),sU=EX.StripeResource.method;FX.ConfirmationTokens=EX.StripeResource.extend({retrieve:sU({method:"GET",fullPath:"/v1/confirmation_tokens/{confirmation_token}"})})});var PX=K((xX)=>{Object.defineProperty(xX,"__esModule",{value:!0});xX.CountrySpecs=void 0;var NX=w(),AX=NX.StripeResource.method;xX.CountrySpecs=NX.StripeResource.extend({retrieve:AX({method:"GET",fullPath:"/v1/country_specs/{country}"}),list:AX({method:"GET",fullPath:"/v1/country_specs",methodType:"list"})})});var yX=K((RX)=>{Object.defineProperty(RX,"__esModule",{value:!0});RX.Coupons=void 0;var SX=w(),r0=SX.StripeResource.method;RX.Coupons=SX.StripeResource.extend({create:r0({method:"POST",fullPath:"/v1/coupons"}),retrieve:r0({method:"GET",fullPath:"/v1/coupons/{coupon}"}),update:r0({method:"POST",fullPath:"/v1/coupons/{coupon}"}),list:r0({method:"GET",fullPath:"/v1/coupons",methodType:"list"}),del:r0({method:"DELETE",fullPath:"/v1/coupons/{coupon}"})})});var MX=K((jX)=>{Object.defineProperty(jX,"__esModule",{value:!0});jX.CreditNotes=void 0;var bX=w(),r=bX.StripeResource.method;jX.CreditNotes=bX.StripeResource.extend({create:r({method:"POST",fullPath:"/v1/credit_notes",requestSchema:{kind:"object",fields:{lines:{kind:"array",element:{kind:"object",fields:{unit_amount_decimal:{kind:"decimal_string"}}}}}},responseSchema:{kind:"object",fields:{lines:{kind:"object",fields:{data:{kind:"array",element:{kind:"object",fields:{unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}}}}}),retrieve:r({method:"GET",fullPath:"/v1/credit_notes/{id}",responseSchema:{kind:"object",fields:{lines:{kind:"object",fields:{data:{kind:"array",element:{kind:"object",fields:{unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}}}}}),update:r({method:"POST",fullPath:"/v1/credit_notes/{id}",responseSchema:{kind:"object",fields:{lines:{kind:"object",fields:{data:{kind:"array",element:{kind:"object",fields:{unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}}}}}),list:r({method:"GET",fullPath:"/v1/credit_notes",methodType:"list",responseSchema:{kind:"object",fields:{data:{kind:"array",element:{kind:"object",fields:{lines:{kind:"object",fields:{data:{kind:"array",element:{kind:"object",fields:{unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}}}}}}}}),listLineItems:r({method:"GET",fullPath:"/v1/credit_notes/{credit_note}/lines",methodType:"list",responseSchema:{kind:"object",fields:{data:{kind:"array",element:{kind:"object",fields:{unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}}}),listPreviewLineItems:r({method:"GET",fullPath:"/v1/credit_notes/preview/lines",methodType:"list",requestSchema:{kind:"object",fields:{lines:{kind:"array",element:{kind:"object",fields:{unit_amount_decimal:{kind:"decimal_string"}}}}}},responseSchema:{kind:"object",fields:{data:{kind:"array",element:{kind:"object",fields:{unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}}}),preview:r({method:"GET",fullPath:"/v1/credit_notes/preview",requestSchema:{kind:"object",fields:{lines:{kind:"array",element:{kind:"object",fields:{unit_amount_decimal:{kind:"decimal_string"}}}}}},responseSchema:{kind:"object",fields:{lines:{kind:"object",fields:{data:{kind:"array",element:{kind:"object",fields:{unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}}}}}),voidCreditNote:r({method:"POST",fullPath:"/v1/credit_notes/{id}/void",responseSchema:{kind:"object",fields:{lines:{kind:"object",fields:{data:{kind:"array",element:{kind:"object",fields:{unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}}}}})})});var mX=K((gX)=>{Object.defineProperty(gX,"__esModule",{value:!0});gX.CustomerSessions=void 0;var _X=w(),rU=_X.StripeResource.method;gX.CustomerSessions=_X.StripeResource.extend({create:rU({method:"POST",fullPath:"/v1/customer_sessions"})})});var lX=K((cX)=>{Object.defineProperty(cX,"__esModule",{value:!0});cX.Customers=void 0;var uX=w(),A=uX.StripeResource.method;cX.Customers=uX.StripeResource.extend({create:A({method:"POST",fullPath:"/v1/customers",responseSchema:{kind:"object",fields:{subscriptions:{kind:"object",fields:{data:{kind:"array",element:{kind:"object",fields:{items:{kind:"object",fields:{data:{kind:"array",element:{kind:"object",fields:{plan:{kind:"object",fields:{amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},tiers:{kind:"array",element:{kind:"object",fields:{flat_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}},price:{kind:"object",fields:{currency_options:{kind:"array",element:{kind:"object",fields:{tiers:{kind:"array",element:{kind:"object",fields:{flat_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},tiers:{kind:"array",element:{kind:"object",fields:{flat_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}}}}}}}}}}}}),retrieve:A({method:"GET",fullPath:"/v1/customers/{customer}"}),update:A({method:"POST",fullPath:"/v1/customers/{customer}",responseSchema:{kind:"object",fields:{subscriptions:{kind:"object",fields:{data:{kind:"array",element:{kind:"object",fields:{items:{kind:"object",fields:{data:{kind:"array",element:{kind:"object",fields:{plan:{kind:"object",fields:{amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},tiers:{kind:"array",element:{kind:"object",fields:{flat_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}},price:{kind:"object",fields:{currency_options:{kind:"array",element:{kind:"object",fields:{tiers:{kind:"array",element:{kind:"object",fields:{flat_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},tiers:{kind:"array",element:{kind:"object",fields:{flat_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}}}}}}}}}}}}),list:A({method:"GET",fullPath:"/v1/customers",methodType:"list",responseSchema:{kind:"object",fields:{data:{kind:"array",element:{kind:"object",fields:{subscriptions:{kind:"object",fields:{data:{kind:"array",element:{kind:"object",fields:{items:{kind:"object",fields:{data:{kind:"array",element:{kind:"object",fields:{plan:{kind:"object",fields:{amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},tiers:{kind:"array",element:{kind:"object",fields:{flat_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}},price:{kind:"object",fields:{currency_options:{kind:"array",element:{kind:"object",fields:{tiers:{kind:"array",element:{kind:"object",fields:{flat_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},tiers:{kind:"array",element:{kind:"object",fields:{flat_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}}}}}}}}}}}}}}}),del:A({method:"DELETE",fullPath:"/v1/customers/{customer}"}),createBalanceTransaction:A({method:"POST",fullPath:"/v1/customers/{customer}/balance_transactions"}),createFundingInstructions:A({method:"POST",fullPath:"/v1/customers/{customer}/funding_instructions"}),createSource:A({method:"POST",fullPath:"/v1/customers/{customer}/sources"}),createTaxId:A({method:"POST",fullPath:"/v1/customers/{customer}/tax_ids"}),deleteDiscount:A({method:"DELETE",fullPath:"/v1/customers/{customer}/discount"}),deleteSource:A({method:"DELETE",fullPath:"/v1/customers/{customer}/sources/{id}"}),deleteTaxId:A({method:"DELETE",fullPath:"/v1/customers/{customer}/tax_ids/{id}"}),listBalanceTransactions:A({method:"GET",fullPath:"/v1/customers/{customer}/balance_transactions",methodType:"list"}),listCashBalanceTransactions:A({method:"GET",fullPath:"/v1/customers/{customer}/cash_balance_transactions",methodType:"list"}),listPaymentMethods:A({method:"GET",fullPath:"/v1/customers/{customer}/payment_methods",methodType:"list"}),listSources:A({method:"GET",fullPath:"/v1/customers/{customer}/sources",methodType:"list"}),listTaxIds:A({method:"GET",fullPath:"/v1/customers/{customer}/tax_ids",methodType:"list"}),retrieveBalanceTransaction:A({method:"GET",fullPath:"/v1/customers/{customer}/balance_transactions/{transaction}"}),retrieveCashBalance:A({method:"GET",fullPath:"/v1/customers/{customer}/cash_balance"}),retrieveCashBalanceTransaction:A({method:"GET",fullPath:"/v1/customers/{customer}/cash_balance_transactions/{transaction}"}),retrievePaymentMethod:A({method:"GET",fullPath:"/v1/customers/{customer}/payment_methods/{payment_method}"}),retrieveSource:A({method:"GET",fullPath:"/v1/customers/{customer}/sources/{id}"}),retrieveTaxId:A({method:"GET",fullPath:"/v1/customers/{customer}/tax_ids/{id}"}),search:A({method:"GET",fullPath:"/v1/customers/search",methodType:"search",responseSchema:{kind:"object",fields:{data:{kind:"array",element:{kind:"object",fields:{subscriptions:{kind:"object",fields:{data:{kind:"array",element:{kind:"object",fields:{items:{kind:"object",fields:{data:{kind:"array",element:{kind:"object",fields:{plan:{kind:"object",fields:{amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},tiers:{kind:"array",element:{kind:"object",fields:{flat_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}},price:{kind:"object",fields:{currency_options:{kind:"array",element:{kind:"object",fields:{tiers:{kind:"array",element:{kind:"object",fields:{flat_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},tiers:{kind:"array",element:{kind:"object",fields:{flat_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}}}}}}}}}}}}}}}),updateBalanceTransaction:A({method:"POST",fullPath:"/v1/customers/{customer}/balance_transactions/{transaction}"}),updateCashBalance:A({method:"POST",fullPath:"/v1/customers/{customer}/cash_balance"}),updateSource:A({method:"POST",fullPath:"/v1/customers/{customer}/sources/{id}"}),verifySource:A({method:"POST",fullPath:"/v1/customers/{customer}/sources/{id}/verify"})})});var aX=K((dX)=>{Object.defineProperty(dX,"__esModule",{value:!0});dX.Disputes=void 0;var pX=w(),l8=pX.StripeResource.method;dX.Disputes=pX.StripeResource.extend({retrieve:l8({method:"GET",fullPath:"/v1/disputes/{dispute}"}),update:l8({method:"POST",fullPath:"/v1/disputes/{dispute}"}),list:l8({method:"GET",fullPath:"/v1/disputes",methodType:"list"}),close:l8({method:"POST",fullPath:"/v1/disputes/{dispute}/close"})})});var eX=K((rX)=>{Object.defineProperty(rX,"__esModule",{value:!0});rX.EphemeralKeys=void 0;var sX=w(),oX=sX.StripeResource.method;rX.EphemeralKeys=sX.StripeResource.extend({create:oX({method:"POST",fullPath:"/v1/ephemeral_keys",validator:($,Z)=>{if(!Z.headers||!Z.headers["Stripe-Version"])throw Error("Passing apiVersion in a separate options hash is required to create an ephemeral key. See https://stripe.com/docs/api/versioning?lang=node")}}),del:oX({method:"DELETE",fullPath:"/v1/ephemeral_keys/{key}"})})});var XY=K((JY)=>{Object.defineProperty(JY,"__esModule",{value:!0});JY.Events=void 0;var ZY=w(),$Y=ZY.StripeResource.method;JY.Events=ZY.StripeResource.extend({retrieve:$Y({method:"GET",fullPath:"/v1/events/{id}"}),list:$Y({method:"GET",fullPath:"/v1/events",methodType:"list"})})});var WY=K((VY)=>{Object.defineProperty(VY,"__esModule",{value:!0});VY.ExchangeRates=void 0;var GY=w(),YY=GY.StripeResource.method;VY.ExchangeRates=GY.StripeResource.extend({retrieve:YY({method:"GET",fullPath:"/v1/exchange_rates/{rate_id}"}),list:YY({method:"GET",fullPath:"/v1/exchange_rates",methodType:"list"})})});var KY=K((zY)=>{Object.defineProperty(zY,"__esModule",{value:!0});zY.FileLinks=void 0;var UY=w(),p8=UY.StripeResource.method;zY.FileLinks=UY.StripeResource.extend({create:p8({method:"POST",fullPath:"/v1/file_links"}),retrieve:p8({method:"GET",fullPath:"/v1/file_links/{link}"}),update:p8({method:"POST",fullPath:"/v1/file_links/{link}"}),list:p8({method:"GET",fullPath:"/v1/file_links",methodType:"list"})})});var DY=K((wY)=>{Object.defineProperty(wY,"__esModule",{value:!0});wY.multipartRequestDataProcessor=void 0;var HY=c(),tU=($,Z,J)=>{let Q=(Math.round(Math.random()*10000000000000000)+Math.round(Math.random()*10000000000000000)).toString();J["Content-Type"]=`multipart/form-data; boundary=${Q}`;let X=new TextEncoder,Y=new Uint8Array(0),G=X.encode(`\r
|
|
12
|
+
`);function V(B){let z=Y,L=B instanceof Uint8Array?B:new Uint8Array(X.encode(B));Y=new Uint8Array(z.length+L.length+2),Y.set(z),Y.set(L,z.length),Y.set(G,Y.length-2)}function U(B){return`"${B.replace(/"|"/g,"%22").replace(/\r\n|\r|\n/g," ")}"`}let W=(0,HY.flattenAndStringify)(Z);for(let B in W){if(!Object.prototype.hasOwnProperty.call(W,B))continue;let z=W[B];if(V(`--${Q}`),Object.prototype.hasOwnProperty.call(z,"data")){let L=z;V(`Content-Disposition: form-data; name=${U(B)}; filename=${U(L.name||"blob")}`),V(`Content-Type: ${L.type||"application/octet-stream"}`),V(""),V(L.data)}else V(`Content-Disposition: form-data; name=${U(B)}`),V(""),V(z)}return V(`--${Q}--`),Y};function eU($,Z,J,Q){if(Z=Z||{},$!=="POST")return Q(null,(0,HY.queryStringifyRequestData)(Z));this._stripe._platformFunctions.tryBufferData(Z).then((X)=>{let Y=tU($,X,J);return Q(null,Y)}).catch((X)=>Q(X,null))}wY.multipartRequestDataProcessor=eU});var FY=K((qY)=>{Object.defineProperty(qY,"__esModule",{value:!0});qY.Files=void 0;var $z=DY(),OY=w(),V9=OY.StripeResource.method;qY.Files=OY.StripeResource.extend({create:V9({method:"POST",fullPath:"/v1/files",headers:{"Content-Type":"multipart/form-data"},host:"files.stripe.com"}),retrieve:V9({method:"GET",fullPath:"/v1/files/{file}"}),list:V9({method:"GET",fullPath:"/v1/files",methodType:"list"}),requestDataProcessor:$z.multipartRequestDataProcessor})});var NY=K((kY)=>{Object.defineProperty(kY,"__esModule",{value:!0});kY.InvoiceItems=void 0;var CY=w(),t0=CY.StripeResource.method;kY.InvoiceItems=CY.StripeResource.extend({create:t0({method:"POST",fullPath:"/v1/invoiceitems",requestSchema:{kind:"object",fields:{price_data:{kind:"object",fields:{unit_amount_decimal:{kind:"decimal_string"}}},quantity_decimal:{kind:"decimal_string"},unit_amount_decimal:{kind:"decimal_string"}}},responseSchema:{kind:"object",fields:{pricing:{kind:"nullable",inner:{kind:"object",fields:{unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},quantity_decimal:{kind:"decimal_string"}}}}),retrieve:t0({method:"GET",fullPath:"/v1/invoiceitems/{invoiceitem}",responseSchema:{kind:"object",fields:{pricing:{kind:"nullable",inner:{kind:"object",fields:{unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},quantity_decimal:{kind:"decimal_string"}}}}),update:t0({method:"POST",fullPath:"/v1/invoiceitems/{invoiceitem}",requestSchema:{kind:"object",fields:{price_data:{kind:"object",fields:{unit_amount_decimal:{kind:"decimal_string"}}},quantity_decimal:{kind:"decimal_string"},unit_amount_decimal:{kind:"decimal_string"}}},responseSchema:{kind:"object",fields:{pricing:{kind:"nullable",inner:{kind:"object",fields:{unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},quantity_decimal:{kind:"decimal_string"}}}}),list:t0({method:"GET",fullPath:"/v1/invoiceitems",methodType:"list",responseSchema:{kind:"object",fields:{data:{kind:"array",element:{kind:"object",fields:{pricing:{kind:"nullable",inner:{kind:"object",fields:{unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},quantity_decimal:{kind:"decimal_string"}}}}}}}),del:t0({method:"DELETE",fullPath:"/v1/invoiceitems/{invoiceitem}"})})});var RY=K((PY)=>{Object.defineProperty(PY,"__esModule",{value:!0});PY.InvoicePayments=void 0;var IY=w(),xY=IY.StripeResource.method;PY.InvoicePayments=IY.StripeResource.extend({retrieve:xY({method:"GET",fullPath:"/v1/invoice_payments/{invoice_payment}"}),list:xY({method:"GET",fullPath:"/v1/invoice_payments",methodType:"list"})})});var jY=K((yY)=>{Object.defineProperty(yY,"__esModule",{value:!0});yY.InvoiceRenderingTemplates=void 0;var vY=w(),d8=vY.StripeResource.method;yY.InvoiceRenderingTemplates=vY.StripeResource.extend({retrieve:d8({method:"GET",fullPath:"/v1/invoice_rendering_templates/{template}"}),list:d8({method:"GET",fullPath:"/v1/invoice_rendering_templates",methodType:"list"}),archive:d8({method:"POST",fullPath:"/v1/invoice_rendering_templates/{template}/archive"}),unarchive:d8({method:"POST",fullPath:"/v1/invoice_rendering_templates/{template}/unarchive"})})});var gY=K((MY)=>{Object.defineProperty(MY,"__esModule",{value:!0});MY.Invoices=void 0;var fY=w(),S=fY.StripeResource.method;MY.Invoices=fY.StripeResource.extend({create:S({method:"POST",fullPath:"/v1/invoices",responseSchema:{kind:"object",fields:{lines:{kind:"object",fields:{data:{kind:"array",element:{kind:"object",fields:{pricing:{kind:"nullable",inner:{kind:"object",fields:{unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},quantity_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}}}}}),retrieve:S({method:"GET",fullPath:"/v1/invoices/{invoice}",responseSchema:{kind:"object",fields:{lines:{kind:"object",fields:{data:{kind:"array",element:{kind:"object",fields:{pricing:{kind:"nullable",inner:{kind:"object",fields:{unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},quantity_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}}}}}),update:S({method:"POST",fullPath:"/v1/invoices/{invoice}",responseSchema:{kind:"object",fields:{lines:{kind:"object",fields:{data:{kind:"array",element:{kind:"object",fields:{pricing:{kind:"nullable",inner:{kind:"object",fields:{unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},quantity_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}}}}}),list:S({method:"GET",fullPath:"/v1/invoices",methodType:"list",responseSchema:{kind:"object",fields:{data:{kind:"array",element:{kind:"object",fields:{lines:{kind:"object",fields:{data:{kind:"array",element:{kind:"object",fields:{pricing:{kind:"nullable",inner:{kind:"object",fields:{unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},quantity_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}}}}}}}}),del:S({method:"DELETE",fullPath:"/v1/invoices/{invoice}"}),addLines:S({method:"POST",fullPath:"/v1/invoices/{invoice}/add_lines",requestSchema:{kind:"object",fields:{lines:{kind:"array",element:{kind:"object",fields:{price_data:{kind:"object",fields:{unit_amount_decimal:{kind:"decimal_string"}}},quantity_decimal:{kind:"decimal_string"}}}}}},responseSchema:{kind:"object",fields:{lines:{kind:"object",fields:{data:{kind:"array",element:{kind:"object",fields:{pricing:{kind:"nullable",inner:{kind:"object",fields:{unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},quantity_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}}}}}),attachPayment:S({method:"POST",fullPath:"/v1/invoices/{invoice}/attach_payment",responseSchema:{kind:"object",fields:{lines:{kind:"object",fields:{data:{kind:"array",element:{kind:"object",fields:{pricing:{kind:"nullable",inner:{kind:"object",fields:{unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},quantity_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}}}}}),createPreview:S({method:"POST",fullPath:"/v1/invoices/create_preview",requestSchema:{kind:"object",fields:{invoice_items:{kind:"array",element:{kind:"object",fields:{price_data:{kind:"object",fields:{unit_amount_decimal:{kind:"decimal_string"}}},quantity_decimal:{kind:"decimal_string"},unit_amount_decimal:{kind:"decimal_string"}}}},schedule_details:{kind:"object",fields:{phases:{kind:"array",element:{kind:"object",fields:{add_invoice_items:{kind:"array",element:{kind:"object",fields:{price_data:{kind:"object",fields:{unit_amount_decimal:{kind:"decimal_string"}}}}}},items:{kind:"array",element:{kind:"object",fields:{price_data:{kind:"object",fields:{unit_amount_decimal:{kind:"decimal_string"}}}}}}}}}}},subscription_details:{kind:"object",fields:{items:{kind:"array",element:{kind:"object",fields:{price_data:{kind:"object",fields:{unit_amount_decimal:{kind:"decimal_string"}}}}}}}}}},responseSchema:{kind:"object",fields:{lines:{kind:"object",fields:{data:{kind:"array",element:{kind:"object",fields:{pricing:{kind:"nullable",inner:{kind:"object",fields:{unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},quantity_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}}}}}),finalizeInvoice:S({method:"POST",fullPath:"/v1/invoices/{invoice}/finalize",responseSchema:{kind:"object",fields:{lines:{kind:"object",fields:{data:{kind:"array",element:{kind:"object",fields:{pricing:{kind:"nullable",inner:{kind:"object",fields:{unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},quantity_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}}}}}),listLineItems:S({method:"GET",fullPath:"/v1/invoices/{invoice}/lines",methodType:"list",responseSchema:{kind:"object",fields:{data:{kind:"array",element:{kind:"object",fields:{pricing:{kind:"nullable",inner:{kind:"object",fields:{unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},quantity_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}}}),markUncollectible:S({method:"POST",fullPath:"/v1/invoices/{invoice}/mark_uncollectible",responseSchema:{kind:"object",fields:{lines:{kind:"object",fields:{data:{kind:"array",element:{kind:"object",fields:{pricing:{kind:"nullable",inner:{kind:"object",fields:{unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},quantity_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}}}}}),pay:S({method:"POST",fullPath:"/v1/invoices/{invoice}/pay",responseSchema:{kind:"object",fields:{lines:{kind:"object",fields:{data:{kind:"array",element:{kind:"object",fields:{pricing:{kind:"nullable",inner:{kind:"object",fields:{unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},quantity_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}}}}}),removeLines:S({method:"POST",fullPath:"/v1/invoices/{invoice}/remove_lines",responseSchema:{kind:"object",fields:{lines:{kind:"object",fields:{data:{kind:"array",element:{kind:"object",fields:{pricing:{kind:"nullable",inner:{kind:"object",fields:{unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},quantity_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}}}}}),search:S({method:"GET",fullPath:"/v1/invoices/search",methodType:"search",responseSchema:{kind:"object",fields:{data:{kind:"array",element:{kind:"object",fields:{lines:{kind:"object",fields:{data:{kind:"array",element:{kind:"object",fields:{pricing:{kind:"nullable",inner:{kind:"object",fields:{unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},quantity_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}}}}}}}}),sendInvoice:S({method:"POST",fullPath:"/v1/invoices/{invoice}/send",responseSchema:{kind:"object",fields:{lines:{kind:"object",fields:{data:{kind:"array",element:{kind:"object",fields:{pricing:{kind:"nullable",inner:{kind:"object",fields:{unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},quantity_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}}}}}),updateLines:S({method:"POST",fullPath:"/v1/invoices/{invoice}/update_lines",requestSchema:{kind:"object",fields:{lines:{kind:"array",element:{kind:"object",fields:{price_data:{kind:"object",fields:{unit_amount_decimal:{kind:"decimal_string"}}},quantity_decimal:{kind:"decimal_string"}}}}}},responseSchema:{kind:"object",fields:{lines:{kind:"object",fields:{data:{kind:"array",element:{kind:"object",fields:{pricing:{kind:"nullable",inner:{kind:"object",fields:{unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},quantity_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}}}}}),updateLineItem:S({method:"POST",fullPath:"/v1/invoices/{invoice}/lines/{line_item_id}",requestSchema:{kind:"object",fields:{price_data:{kind:"object",fields:{unit_amount_decimal:{kind:"decimal_string"}}},quantity_decimal:{kind:"decimal_string"}}},responseSchema:{kind:"object",fields:{pricing:{kind:"nullable",inner:{kind:"object",fields:{unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},quantity_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}),voidInvoice:S({method:"POST",fullPath:"/v1/invoices/{invoice}/void",responseSchema:{kind:"object",fields:{lines:{kind:"object",fields:{data:{kind:"array",element:{kind:"object",fields:{pricing:{kind:"nullable",inner:{kind:"object",fields:{unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},quantity_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}}}}})})});var cY=K((mY)=>{Object.defineProperty(mY,"__esModule",{value:!0});mY.Mandates=void 0;var hY=w(),Zz=hY.StripeResource.method;mY.Mandates=hY.StripeResource.extend({retrieve:Zz({method:"GET",fullPath:"/v1/mandates/{mandate}"})})});var iY=K((pY)=>{Object.defineProperty(pY,"__esModule",{value:!0});pY.OAuth=void 0;var lY=w(),Jz=c(),nY=lY.StripeResource.method,B9="connect.stripe.com";pY.OAuth=lY.StripeResource.extend({basePath:"/",authorizeUrl($,Z){$=$||{},Z=Z||{};let J="oauth/authorize";if(Z.express)J=`express/${J}`;if(!$.response_type)$.response_type="code";if(!$.client_id)$.client_id=this._stripe.getClientId();if(!$.scope)$.scope="read_write";return`https://${B9}/${J}?${(0,Jz.queryStringifyRequestData)($)}`},token:nY({method:"POST",path:"oauth/token",host:B9}),deauthorize($,...Z){if(!$.client_id)$.client_id=this._stripe.getClientId();return nY({method:"POST",path:"oauth/deauthorize",host:B9}).apply(this,[$,...Z])}})});var tY=K((sY)=>{Object.defineProperty(sY,"__esModule",{value:!0});sY.PaymentAttemptRecords=void 0;var oY=w(),aY=oY.StripeResource.method;sY.PaymentAttemptRecords=oY.StripeResource.extend({retrieve:aY({method:"GET",fullPath:"/v1/payment_attempt_records/{id}"}),list:aY({method:"GET",fullPath:"/v1/payment_attempt_records",methodType:"list"})})});var JG=K(($G)=>{Object.defineProperty($G,"__esModule",{value:!0});$G.PaymentIntents=void 0;var eY=w(),g=eY.StripeResource.method;$G.PaymentIntents=eY.StripeResource.extend({create:g({method:"POST",fullPath:"/v1/payment_intents"}),retrieve:g({method:"GET",fullPath:"/v1/payment_intents/{intent}"}),update:g({method:"POST",fullPath:"/v1/payment_intents/{intent}"}),list:g({method:"GET",fullPath:"/v1/payment_intents",methodType:"list"}),applyCustomerBalance:g({method:"POST",fullPath:"/v1/payment_intents/{intent}/apply_customer_balance"}),cancel:g({method:"POST",fullPath:"/v1/payment_intents/{intent}/cancel"}),capture:g({method:"POST",fullPath:"/v1/payment_intents/{intent}/capture"}),confirm:g({method:"POST",fullPath:"/v1/payment_intents/{intent}/confirm"}),incrementAuthorization:g({method:"POST",fullPath:"/v1/payment_intents/{intent}/increment_authorization"}),listAmountDetailsLineItems:g({method:"GET",fullPath:"/v1/payment_intents/{intent}/amount_details_line_items",methodType:"list"}),search:g({method:"GET",fullPath:"/v1/payment_intents/search",methodType:"search"}),verifyMicrodeposits:g({method:"POST",fullPath:"/v1/payment_intents/{intent}/verify_microdeposits"})})});var GG=K((XG)=>{Object.defineProperty(XG,"__esModule",{value:!0});XG.PaymentLinks=void 0;var QG=w(),e0=QG.StripeResource.method;XG.PaymentLinks=QG.StripeResource.extend({create:e0({method:"POST",fullPath:"/v1/payment_links",requestSchema:{kind:"object",fields:{line_items:{kind:"array",element:{kind:"object",fields:{price_data:{kind:"object",fields:{unit_amount_decimal:{kind:"decimal_string"}}}}}}}},responseSchema:{kind:"object",fields:{line_items:{kind:"object",fields:{data:{kind:"array",element:{kind:"object",fields:{price:{kind:"nullable",inner:{kind:"object",fields:{currency_options:{kind:"array",element:{kind:"object",fields:{tiers:{kind:"array",element:{kind:"object",fields:{flat_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},tiers:{kind:"array",element:{kind:"object",fields:{flat_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}}}}}}}}),retrieve:e0({method:"GET",fullPath:"/v1/payment_links/{payment_link}",responseSchema:{kind:"object",fields:{line_items:{kind:"object",fields:{data:{kind:"array",element:{kind:"object",fields:{price:{kind:"nullable",inner:{kind:"object",fields:{currency_options:{kind:"array",element:{kind:"object",fields:{tiers:{kind:"array",element:{kind:"object",fields:{flat_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},tiers:{kind:"array",element:{kind:"object",fields:{flat_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}}}}}}}}),update:e0({method:"POST",fullPath:"/v1/payment_links/{payment_link}",responseSchema:{kind:"object",fields:{line_items:{kind:"object",fields:{data:{kind:"array",element:{kind:"object",fields:{price:{kind:"nullable",inner:{kind:"object",fields:{currency_options:{kind:"array",element:{kind:"object",fields:{tiers:{kind:"array",element:{kind:"object",fields:{flat_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},tiers:{kind:"array",element:{kind:"object",fields:{flat_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}}}}}}}}),list:e0({method:"GET",fullPath:"/v1/payment_links",methodType:"list",responseSchema:{kind:"object",fields:{data:{kind:"array",element:{kind:"object",fields:{line_items:{kind:"object",fields:{data:{kind:"array",element:{kind:"object",fields:{price:{kind:"nullable",inner:{kind:"object",fields:{currency_options:{kind:"array",element:{kind:"object",fields:{tiers:{kind:"array",element:{kind:"object",fields:{flat_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},tiers:{kind:"array",element:{kind:"object",fields:{flat_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}}}}}}}}}}}),listLineItems:e0({method:"GET",fullPath:"/v1/payment_links/{payment_link}/line_items",methodType:"list",responseSchema:{kind:"object",fields:{data:{kind:"array",element:{kind:"object",fields:{price:{kind:"nullable",inner:{kind:"object",fields:{currency_options:{kind:"array",element:{kind:"object",fields:{tiers:{kind:"array",element:{kind:"object",fields:{flat_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},tiers:{kind:"array",element:{kind:"object",fields:{flat_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}}}}}})})});var UG=K((BG)=>{Object.defineProperty(BG,"__esModule",{value:!0});BG.PaymentMethodConfigurations=void 0;var VG=w(),i8=VG.StripeResource.method;BG.PaymentMethodConfigurations=VG.StripeResource.extend({create:i8({method:"POST",fullPath:"/v1/payment_method_configurations"}),retrieve:i8({method:"GET",fullPath:"/v1/payment_method_configurations/{configuration}"}),update:i8({method:"POST",fullPath:"/v1/payment_method_configurations/{configuration}"}),list:i8({method:"GET",fullPath:"/v1/payment_method_configurations",methodType:"list"})})});var HG=K((LG)=>{Object.defineProperty(LG,"__esModule",{value:!0});LG.PaymentMethodDomains=void 0;var zG=w(),$8=zG.StripeResource.method;LG.PaymentMethodDomains=zG.StripeResource.extend({create:$8({method:"POST",fullPath:"/v1/payment_method_domains"}),retrieve:$8({method:"GET",fullPath:"/v1/payment_method_domains/{payment_method_domain}"}),update:$8({method:"POST",fullPath:"/v1/payment_method_domains/{payment_method_domain}"}),list:$8({method:"GET",fullPath:"/v1/payment_method_domains",methodType:"list"}),validate:$8({method:"POST",fullPath:"/v1/payment_method_domains/{payment_method_domain}/validate"})})});var OG=K((TG)=>{Object.defineProperty(TG,"__esModule",{value:!0});TG.PaymentMethods=void 0;var wG=w(),k0=wG.StripeResource.method;TG.PaymentMethods=wG.StripeResource.extend({create:k0({method:"POST",fullPath:"/v1/payment_methods"}),retrieve:k0({method:"GET",fullPath:"/v1/payment_methods/{payment_method}"}),update:k0({method:"POST",fullPath:"/v1/payment_methods/{payment_method}"}),list:k0({method:"GET",fullPath:"/v1/payment_methods",methodType:"list"}),attach:k0({method:"POST",fullPath:"/v1/payment_methods/{payment_method}/attach"}),detach:k0({method:"POST",fullPath:"/v1/payment_methods/{payment_method}/detach"})})});var CG=K((EG)=>{Object.defineProperty(EG,"__esModule",{value:!0});EG.PaymentRecords=void 0;var qG=w(),t=qG.StripeResource.method;EG.PaymentRecords=qG.StripeResource.extend({retrieve:t({method:"GET",fullPath:"/v1/payment_records/{id}"}),reportPayment:t({method:"POST",fullPath:"/v1/payment_records/report_payment"}),reportPaymentAttempt:t({method:"POST",fullPath:"/v1/payment_records/{id}/report_payment_attempt"}),reportPaymentAttemptCanceled:t({method:"POST",fullPath:"/v1/payment_records/{id}/report_payment_attempt_canceled"}),reportPaymentAttemptFailed:t({method:"POST",fullPath:"/v1/payment_records/{id}/report_payment_attempt_failed"}),reportPaymentAttemptGuaranteed:t({method:"POST",fullPath:"/v1/payment_records/{id}/report_payment_attempt_guaranteed"}),reportPaymentAttemptInformational:t({method:"POST",fullPath:"/v1/payment_records/{id}/report_payment_attempt_informational"}),reportRefund:t({method:"POST",fullPath:"/v1/payment_records/{id}/report_refund"})})});var xG=K((AG)=>{Object.defineProperty(AG,"__esModule",{value:!0});AG.Payouts=void 0;var kG=w(),A0=kG.StripeResource.method;AG.Payouts=kG.StripeResource.extend({create:A0({method:"POST",fullPath:"/v1/payouts"}),retrieve:A0({method:"GET",fullPath:"/v1/payouts/{payout}"}),update:A0({method:"POST",fullPath:"/v1/payouts/{payout}"}),list:A0({method:"GET",fullPath:"/v1/payouts",methodType:"list"}),cancel:A0({method:"POST",fullPath:"/v1/payouts/{payout}/cancel"}),reverse:A0({method:"POST",fullPath:"/v1/payouts/{payout}/reverse"})})});var RG=K((PG)=>{Object.defineProperty(PG,"__esModule",{value:!0});PG.Plans=void 0;var IG=w(),Z8=IG.StripeResource.method;PG.Plans=IG.StripeResource.extend({create:Z8({method:"POST",fullPath:"/v1/plans",requestSchema:{kind:"object",fields:{amount_decimal:{kind:"decimal_string"},tiers:{kind:"array",element:{kind:"object",fields:{flat_amount_decimal:{kind:"decimal_string"},unit_amount_decimal:{kind:"decimal_string"}}}}}},responseSchema:{kind:"object",fields:{amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},tiers:{kind:"array",element:{kind:"object",fields:{flat_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}}}),retrieve:Z8({method:"GET",fullPath:"/v1/plans/{plan}",responseSchema:{kind:"object",fields:{amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},tiers:{kind:"array",element:{kind:"object",fields:{flat_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}}}),update:Z8({method:"POST",fullPath:"/v1/plans/{plan}",responseSchema:{kind:"object",fields:{amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},tiers:{kind:"array",element:{kind:"object",fields:{flat_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}}}),list:Z8({method:"GET",fullPath:"/v1/plans",methodType:"list",responseSchema:{kind:"object",fields:{data:{kind:"array",element:{kind:"object",fields:{amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},tiers:{kind:"array",element:{kind:"object",fields:{flat_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}}}}}}),del:Z8({method:"DELETE",fullPath:"/v1/plans/{plan}"})})});var jG=K((yG)=>{Object.defineProperty(yG,"__esModule",{value:!0});yG.Prices=void 0;var vG=w(),J8=vG.StripeResource.method;yG.Prices=vG.StripeResource.extend({create:J8({method:"POST",fullPath:"/v1/prices",requestSchema:{kind:"object",fields:{currency_options:{kind:"array",element:{kind:"object",fields:{tiers:{kind:"array",element:{kind:"object",fields:{flat_amount_decimal:{kind:"decimal_string"},unit_amount_decimal:{kind:"decimal_string"}}}},unit_amount_decimal:{kind:"decimal_string"}}}},tiers:{kind:"array",element:{kind:"object",fields:{flat_amount_decimal:{kind:"decimal_string"},unit_amount_decimal:{kind:"decimal_string"}}}},unit_amount_decimal:{kind:"decimal_string"}}},responseSchema:{kind:"object",fields:{currency_options:{kind:"array",element:{kind:"object",fields:{tiers:{kind:"array",element:{kind:"object",fields:{flat_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},tiers:{kind:"array",element:{kind:"object",fields:{flat_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}),retrieve:J8({method:"GET",fullPath:"/v1/prices/{price}",responseSchema:{kind:"object",fields:{currency_options:{kind:"array",element:{kind:"object",fields:{tiers:{kind:"array",element:{kind:"object",fields:{flat_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},tiers:{kind:"array",element:{kind:"object",fields:{flat_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}),update:J8({method:"POST",fullPath:"/v1/prices/{price}",responseSchema:{kind:"object",fields:{currency_options:{kind:"array",element:{kind:"object",fields:{tiers:{kind:"array",element:{kind:"object",fields:{flat_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},tiers:{kind:"array",element:{kind:"object",fields:{flat_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}),list:J8({method:"GET",fullPath:"/v1/prices",methodType:"list",responseSchema:{kind:"object",fields:{data:{kind:"array",element:{kind:"object",fields:{currency_options:{kind:"array",element:{kind:"object",fields:{tiers:{kind:"array",element:{kind:"object",fields:{flat_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},tiers:{kind:"array",element:{kind:"object",fields:{flat_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}}}),search:J8({method:"GET",fullPath:"/v1/prices/search",methodType:"search",responseSchema:{kind:"object",fields:{data:{kind:"array",element:{kind:"object",fields:{currency_options:{kind:"array",element:{kind:"object",fields:{tiers:{kind:"array",element:{kind:"object",fields:{flat_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},tiers:{kind:"array",element:{kind:"object",fields:{flat_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}}})})});var gG=K((MG)=>{Object.defineProperty(MG,"__esModule",{value:!0});MG.Products=void 0;var fG=w(),n=fG.StripeResource.method;MG.Products=fG.StripeResource.extend({create:n({method:"POST",fullPath:"/v1/products",requestSchema:{kind:"object",fields:{default_price_data:{kind:"object",fields:{currency_options:{kind:"array",element:{kind:"object",fields:{tiers:{kind:"array",element:{kind:"object",fields:{flat_amount_decimal:{kind:"decimal_string"},unit_amount_decimal:{kind:"decimal_string"}}}},unit_amount_decimal:{kind:"decimal_string"}}}},unit_amount_decimal:{kind:"decimal_string"}}}}}}),retrieve:n({method:"GET",fullPath:"/v1/products/{id}"}),update:n({method:"POST",fullPath:"/v1/products/{id}"}),list:n({method:"GET",fullPath:"/v1/products",methodType:"list"}),del:n({method:"DELETE",fullPath:"/v1/products/{id}"}),createFeature:n({method:"POST",fullPath:"/v1/products/{product}/features"}),deleteFeature:n({method:"DELETE",fullPath:"/v1/products/{product}/features/{id}"}),listFeatures:n({method:"GET",fullPath:"/v1/products/{product}/features",methodType:"list"}),retrieveFeature:n({method:"GET",fullPath:"/v1/products/{product}/features/{id}"}),search:n({method:"GET",fullPath:"/v1/products/search",methodType:"search"})})});var cG=K((mG)=>{Object.defineProperty(mG,"__esModule",{value:!0});mG.PromotionCodes=void 0;var hG=w(),a8=hG.StripeResource.method;mG.PromotionCodes=hG.StripeResource.extend({create:a8({method:"POST",fullPath:"/v1/promotion_codes"}),retrieve:a8({method:"GET",fullPath:"/v1/promotion_codes/{promotion_code}"}),update:a8({method:"POST",fullPath:"/v1/promotion_codes/{promotion_code}"}),list:a8({method:"GET",fullPath:"/v1/promotion_codes",methodType:"list"})})});var dG=K((lG)=>{Object.defineProperty(lG,"__esModule",{value:!0});lG.Quotes=void 0;var nG=w(),l=nG.StripeResource.method;lG.Quotes=nG.StripeResource.extend({create:l({method:"POST",fullPath:"/v1/quotes",requestSchema:{kind:"object",fields:{line_items:{kind:"array",element:{kind:"object",fields:{price_data:{kind:"object",fields:{unit_amount_decimal:{kind:"decimal_string"}}}}}}}},responseSchema:{kind:"object",fields:{computed:{kind:"object",fields:{upfront:{kind:"object",fields:{line_items:{kind:"object",fields:{data:{kind:"array",element:{kind:"object",fields:{price:{kind:"nullable",inner:{kind:"object",fields:{currency_options:{kind:"array",element:{kind:"object",fields:{tiers:{kind:"array",element:{kind:"object",fields:{flat_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},tiers:{kind:"array",element:{kind:"object",fields:{flat_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}}}}}}}}}}}}),retrieve:l({method:"GET",fullPath:"/v1/quotes/{quote}",responseSchema:{kind:"object",fields:{computed:{kind:"object",fields:{upfront:{kind:"object",fields:{line_items:{kind:"object",fields:{data:{kind:"array",element:{kind:"object",fields:{price:{kind:"nullable",inner:{kind:"object",fields:{currency_options:{kind:"array",element:{kind:"object",fields:{tiers:{kind:"array",element:{kind:"object",fields:{flat_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},tiers:{kind:"array",element:{kind:"object",fields:{flat_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}}}}}}}}}}}}),update:l({method:"POST",fullPath:"/v1/quotes/{quote}",requestSchema:{kind:"object",fields:{line_items:{kind:"array",element:{kind:"object",fields:{price_data:{kind:"object",fields:{unit_amount_decimal:{kind:"decimal_string"}}}}}}}},responseSchema:{kind:"object",fields:{computed:{kind:"object",fields:{upfront:{kind:"object",fields:{line_items:{kind:"object",fields:{data:{kind:"array",element:{kind:"object",fields:{price:{kind:"nullable",inner:{kind:"object",fields:{currency_options:{kind:"array",element:{kind:"object",fields:{tiers:{kind:"array",element:{kind:"object",fields:{flat_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},tiers:{kind:"array",element:{kind:"object",fields:{flat_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}}}}}}}}}}}}),list:l({method:"GET",fullPath:"/v1/quotes",methodType:"list",responseSchema:{kind:"object",fields:{data:{kind:"array",element:{kind:"object",fields:{computed:{kind:"object",fields:{upfront:{kind:"object",fields:{line_items:{kind:"object",fields:{data:{kind:"array",element:{kind:"object",fields:{price:{kind:"nullable",inner:{kind:"object",fields:{currency_options:{kind:"array",element:{kind:"object",fields:{tiers:{kind:"array",element:{kind:"object",fields:{flat_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},tiers:{kind:"array",element:{kind:"object",fields:{flat_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}}}}}}}}}}}}}}}),accept:l({method:"POST",fullPath:"/v1/quotes/{quote}/accept",responseSchema:{kind:"object",fields:{computed:{kind:"object",fields:{upfront:{kind:"object",fields:{line_items:{kind:"object",fields:{data:{kind:"array",element:{kind:"object",fields:{price:{kind:"nullable",inner:{kind:"object",fields:{currency_options:{kind:"array",element:{kind:"object",fields:{tiers:{kind:"array",element:{kind:"object",fields:{flat_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},tiers:{kind:"array",element:{kind:"object",fields:{flat_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}}}}}}}}}}}}),cancel:l({method:"POST",fullPath:"/v1/quotes/{quote}/cancel",responseSchema:{kind:"object",fields:{computed:{kind:"object",fields:{upfront:{kind:"object",fields:{line_items:{kind:"object",fields:{data:{kind:"array",element:{kind:"object",fields:{price:{kind:"nullable",inner:{kind:"object",fields:{currency_options:{kind:"array",element:{kind:"object",fields:{tiers:{kind:"array",element:{kind:"object",fields:{flat_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},tiers:{kind:"array",element:{kind:"object",fields:{flat_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}}}}}}}}}}}}),finalizeQuote:l({method:"POST",fullPath:"/v1/quotes/{quote}/finalize",responseSchema:{kind:"object",fields:{computed:{kind:"object",fields:{upfront:{kind:"object",fields:{line_items:{kind:"object",fields:{data:{kind:"array",element:{kind:"object",fields:{price:{kind:"nullable",inner:{kind:"object",fields:{currency_options:{kind:"array",element:{kind:"object",fields:{tiers:{kind:"array",element:{kind:"object",fields:{flat_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},tiers:{kind:"array",element:{kind:"object",fields:{flat_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}}}}}}}}}}}}),listComputedUpfrontLineItems:l({method:"GET",fullPath:"/v1/quotes/{quote}/computed_upfront_line_items",methodType:"list",responseSchema:{kind:"object",fields:{data:{kind:"array",element:{kind:"object",fields:{price:{kind:"nullable",inner:{kind:"object",fields:{currency_options:{kind:"array",element:{kind:"object",fields:{tiers:{kind:"array",element:{kind:"object",fields:{flat_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},tiers:{kind:"array",element:{kind:"object",fields:{flat_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}}}}}}),listLineItems:l({method:"GET",fullPath:"/v1/quotes/{quote}/line_items",methodType:"list",responseSchema:{kind:"object",fields:{data:{kind:"array",element:{kind:"object",fields:{price:{kind:"nullable",inner:{kind:"object",fields:{currency_options:{kind:"array",element:{kind:"object",fields:{tiers:{kind:"array",element:{kind:"object",fields:{flat_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},tiers:{kind:"array",element:{kind:"object",fields:{flat_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}}}}}}),pdf:l({method:"GET",fullPath:"/v1/quotes/{quote}/pdf",host:"files.stripe.com",streaming:!0})})});var sG=K((aG)=>{Object.defineProperty(aG,"__esModule",{value:!0});aG.Refunds=void 0;var iG=w(),Q8=iG.StripeResource.method;aG.Refunds=iG.StripeResource.extend({create:Q8({method:"POST",fullPath:"/v1/refunds"}),retrieve:Q8({method:"GET",fullPath:"/v1/refunds/{refund}"}),update:Q8({method:"POST",fullPath:"/v1/refunds/{refund}"}),list:Q8({method:"GET",fullPath:"/v1/refunds",methodType:"list"}),cancel:Q8({method:"POST",fullPath:"/v1/refunds/{refund}/cancel"})})});var $V=K((tG)=>{Object.defineProperty(tG,"__esModule",{value:!0});tG.Reviews=void 0;var rG=w(),W9=rG.StripeResource.method;tG.Reviews=rG.StripeResource.extend({retrieve:W9({method:"GET",fullPath:"/v1/reviews/{review}"}),list:W9({method:"GET",fullPath:"/v1/reviews",methodType:"list"}),approve:W9({method:"POST",fullPath:"/v1/reviews/{review}/approve"})})});var XV=K((JV)=>{Object.defineProperty(JV,"__esModule",{value:!0});JV.SetupAttempts=void 0;var ZV=w(),Qz=ZV.StripeResource.method;JV.SetupAttempts=ZV.StripeResource.extend({list:Qz({method:"GET",fullPath:"/v1/setup_attempts",methodType:"list"})})});var BV=K((GV)=>{Object.defineProperty(GV,"__esModule",{value:!0});GV.SetupIntents=void 0;var YV=w(),V0=YV.StripeResource.method;GV.SetupIntents=YV.StripeResource.extend({create:V0({method:"POST",fullPath:"/v1/setup_intents"}),retrieve:V0({method:"GET",fullPath:"/v1/setup_intents/{intent}"}),update:V0({method:"POST",fullPath:"/v1/setup_intents/{intent}"}),list:V0({method:"GET",fullPath:"/v1/setup_intents",methodType:"list"}),cancel:V0({method:"POST",fullPath:"/v1/setup_intents/{intent}/cancel"}),confirm:V0({method:"POST",fullPath:"/v1/setup_intents/{intent}/confirm"}),verifyMicrodeposits:V0({method:"POST",fullPath:"/v1/setup_intents/{intent}/verify_microdeposits"})})});var LV=K((UV)=>{Object.defineProperty(UV,"__esModule",{value:!0});UV.ShippingRates=void 0;var WV=w(),o8=WV.StripeResource.method;UV.ShippingRates=WV.StripeResource.extend({create:o8({method:"POST",fullPath:"/v1/shipping_rates"}),retrieve:o8({method:"GET",fullPath:"/v1/shipping_rates/{shipping_rate_token}"}),update:o8({method:"POST",fullPath:"/v1/shipping_rates/{shipping_rate_token}"}),list:o8({method:"GET",fullPath:"/v1/shipping_rates",methodType:"list"})})});var TV=K((HV)=>{Object.defineProperty(HV,"__esModule",{value:!0});HV.Sources=void 0;var KV=w(),X8=KV.StripeResource.method;HV.Sources=KV.StripeResource.extend({create:X8({method:"POST",fullPath:"/v1/sources"}),retrieve:X8({method:"GET",fullPath:"/v1/sources/{source}"}),update:X8({method:"POST",fullPath:"/v1/sources/{source}"}),listSourceTransactions:X8({method:"GET",fullPath:"/v1/sources/{source}/source_transactions",methodType:"list"}),verify:X8({method:"POST",fullPath:"/v1/sources/{source}/verify"})})});var EV=K((OV)=>{Object.defineProperty(OV,"__esModule",{value:!0});OV.SubscriptionItems=void 0;var DV=w(),Y8=DV.StripeResource.method;OV.SubscriptionItems=DV.StripeResource.extend({create:Y8({method:"POST",fullPath:"/v1/subscription_items",requestSchema:{kind:"object",fields:{price_data:{kind:"object",fields:{unit_amount_decimal:{kind:"decimal_string"}}}}},responseSchema:{kind:"object",fields:{plan:{kind:"object",fields:{amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},tiers:{kind:"array",element:{kind:"object",fields:{flat_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}},price:{kind:"object",fields:{currency_options:{kind:"array",element:{kind:"object",fields:{tiers:{kind:"array",element:{kind:"object",fields:{flat_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},tiers:{kind:"array",element:{kind:"object",fields:{flat_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}}),retrieve:Y8({method:"GET",fullPath:"/v1/subscription_items/{item}",responseSchema:{kind:"object",fields:{plan:{kind:"object",fields:{amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},tiers:{kind:"array",element:{kind:"object",fields:{flat_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}},price:{kind:"object",fields:{currency_options:{kind:"array",element:{kind:"object",fields:{tiers:{kind:"array",element:{kind:"object",fields:{flat_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},tiers:{kind:"array",element:{kind:"object",fields:{flat_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}}),update:Y8({method:"POST",fullPath:"/v1/subscription_items/{item}",requestSchema:{kind:"object",fields:{price_data:{kind:"object",fields:{unit_amount_decimal:{kind:"decimal_string"}}}}},responseSchema:{kind:"object",fields:{plan:{kind:"object",fields:{amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},tiers:{kind:"array",element:{kind:"object",fields:{flat_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}},price:{kind:"object",fields:{currency_options:{kind:"array",element:{kind:"object",fields:{tiers:{kind:"array",element:{kind:"object",fields:{flat_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},tiers:{kind:"array",element:{kind:"object",fields:{flat_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}}),list:Y8({method:"GET",fullPath:"/v1/subscription_items",methodType:"list",responseSchema:{kind:"object",fields:{data:{kind:"array",element:{kind:"object",fields:{plan:{kind:"object",fields:{amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},tiers:{kind:"array",element:{kind:"object",fields:{flat_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}},price:{kind:"object",fields:{currency_options:{kind:"array",element:{kind:"object",fields:{tiers:{kind:"array",element:{kind:"object",fields:{flat_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},tiers:{kind:"array",element:{kind:"object",fields:{flat_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}}}}}),del:Y8({method:"DELETE",fullPath:"/v1/subscription_items/{item}"})})});var AV=K((CV)=>{Object.defineProperty(CV,"__esModule",{value:!0});CV.SubscriptionSchedules=void 0;var FV=w(),N0=FV.StripeResource.method;CV.SubscriptionSchedules=FV.StripeResource.extend({create:N0({method:"POST",fullPath:"/v1/subscription_schedules",requestSchema:{kind:"object",fields:{phases:{kind:"array",element:{kind:"object",fields:{add_invoice_items:{kind:"array",element:{kind:"object",fields:{price_data:{kind:"object",fields:{unit_amount_decimal:{kind:"decimal_string"}}}}}},items:{kind:"array",element:{kind:"object",fields:{price_data:{kind:"object",fields:{unit_amount_decimal:{kind:"decimal_string"}}}}}}}}}}}}),retrieve:N0({method:"GET",fullPath:"/v1/subscription_schedules/{schedule}"}),update:N0({method:"POST",fullPath:"/v1/subscription_schedules/{schedule}",requestSchema:{kind:"object",fields:{phases:{kind:"array",element:{kind:"object",fields:{add_invoice_items:{kind:"array",element:{kind:"object",fields:{price_data:{kind:"object",fields:{unit_amount_decimal:{kind:"decimal_string"}}}}}},items:{kind:"array",element:{kind:"object",fields:{price_data:{kind:"object",fields:{unit_amount_decimal:{kind:"decimal_string"}}}}}}}}}}}}),list:N0({method:"GET",fullPath:"/v1/subscription_schedules",methodType:"list"}),cancel:N0({method:"POST",fullPath:"/v1/subscription_schedules/{schedule}/cancel"}),release:N0({method:"POST",fullPath:"/v1/subscription_schedules/{schedule}/release"})})});var PV=K((xV)=>{Object.defineProperty(xV,"__esModule",{value:!0});xV.Subscriptions=void 0;var NV=w(),i=NV.StripeResource.method;xV.Subscriptions=NV.StripeResource.extend({create:i({method:"POST",fullPath:"/v1/subscriptions",requestSchema:{kind:"object",fields:{add_invoice_items:{kind:"array",element:{kind:"object",fields:{price_data:{kind:"object",fields:{unit_amount_decimal:{kind:"decimal_string"}}}}}},items:{kind:"array",element:{kind:"object",fields:{price_data:{kind:"object",fields:{unit_amount_decimal:{kind:"decimal_string"}}}}}}}},responseSchema:{kind:"object",fields:{items:{kind:"object",fields:{data:{kind:"array",element:{kind:"object",fields:{plan:{kind:"object",fields:{amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},tiers:{kind:"array",element:{kind:"object",fields:{flat_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}},price:{kind:"object",fields:{currency_options:{kind:"array",element:{kind:"object",fields:{tiers:{kind:"array",element:{kind:"object",fields:{flat_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},tiers:{kind:"array",element:{kind:"object",fields:{flat_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}}}}}}}),retrieve:i({method:"GET",fullPath:"/v1/subscriptions/{subscription_exposed_id}",responseSchema:{kind:"object",fields:{items:{kind:"object",fields:{data:{kind:"array",element:{kind:"object",fields:{plan:{kind:"object",fields:{amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},tiers:{kind:"array",element:{kind:"object",fields:{flat_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}},price:{kind:"object",fields:{currency_options:{kind:"array",element:{kind:"object",fields:{tiers:{kind:"array",element:{kind:"object",fields:{flat_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},tiers:{kind:"array",element:{kind:"object",fields:{flat_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}}}}}}}),update:i({method:"POST",fullPath:"/v1/subscriptions/{subscription_exposed_id}",requestSchema:{kind:"object",fields:{add_invoice_items:{kind:"array",element:{kind:"object",fields:{price_data:{kind:"object",fields:{unit_amount_decimal:{kind:"decimal_string"}}}}}},items:{kind:"array",element:{kind:"object",fields:{price_data:{kind:"object",fields:{unit_amount_decimal:{kind:"decimal_string"}}}}}}}},responseSchema:{kind:"object",fields:{items:{kind:"object",fields:{data:{kind:"array",element:{kind:"object",fields:{plan:{kind:"object",fields:{amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},tiers:{kind:"array",element:{kind:"object",fields:{flat_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}},price:{kind:"object",fields:{currency_options:{kind:"array",element:{kind:"object",fields:{tiers:{kind:"array",element:{kind:"object",fields:{flat_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},tiers:{kind:"array",element:{kind:"object",fields:{flat_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}}}}}}}),list:i({method:"GET",fullPath:"/v1/subscriptions",methodType:"list",responseSchema:{kind:"object",fields:{data:{kind:"array",element:{kind:"object",fields:{items:{kind:"object",fields:{data:{kind:"array",element:{kind:"object",fields:{plan:{kind:"object",fields:{amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},tiers:{kind:"array",element:{kind:"object",fields:{flat_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}},price:{kind:"object",fields:{currency_options:{kind:"array",element:{kind:"object",fields:{tiers:{kind:"array",element:{kind:"object",fields:{flat_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},tiers:{kind:"array",element:{kind:"object",fields:{flat_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}}}}}}}}}}),cancel:i({method:"DELETE",fullPath:"/v1/subscriptions/{subscription_exposed_id}",responseSchema:{kind:"object",fields:{items:{kind:"object",fields:{data:{kind:"array",element:{kind:"object",fields:{plan:{kind:"object",fields:{amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},tiers:{kind:"array",element:{kind:"object",fields:{flat_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}},price:{kind:"object",fields:{currency_options:{kind:"array",element:{kind:"object",fields:{tiers:{kind:"array",element:{kind:"object",fields:{flat_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},tiers:{kind:"array",element:{kind:"object",fields:{flat_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}}}}}}}),deleteDiscount:i({method:"DELETE",fullPath:"/v1/subscriptions/{subscription_exposed_id}/discount"}),migrate:i({method:"POST",fullPath:"/v1/subscriptions/{subscription}/migrate",responseSchema:{kind:"object",fields:{items:{kind:"object",fields:{data:{kind:"array",element:{kind:"object",fields:{plan:{kind:"object",fields:{amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},tiers:{kind:"array",element:{kind:"object",fields:{flat_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}},price:{kind:"object",fields:{currency_options:{kind:"array",element:{kind:"object",fields:{tiers:{kind:"array",element:{kind:"object",fields:{flat_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},tiers:{kind:"array",element:{kind:"object",fields:{flat_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}}}}}}}),resume:i({method:"POST",fullPath:"/v1/subscriptions/{subscription}/resume",responseSchema:{kind:"object",fields:{items:{kind:"object",fields:{data:{kind:"array",element:{kind:"object",fields:{plan:{kind:"object",fields:{amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},tiers:{kind:"array",element:{kind:"object",fields:{flat_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}},price:{kind:"object",fields:{currency_options:{kind:"array",element:{kind:"object",fields:{tiers:{kind:"array",element:{kind:"object",fields:{flat_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},tiers:{kind:"array",element:{kind:"object",fields:{flat_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}}}}}}}),search:i({method:"GET",fullPath:"/v1/subscriptions/search",methodType:"search",responseSchema:{kind:"object",fields:{data:{kind:"array",element:{kind:"object",fields:{items:{kind:"object",fields:{data:{kind:"array",element:{kind:"object",fields:{plan:{kind:"object",fields:{amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},tiers:{kind:"array",element:{kind:"object",fields:{flat_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}},price:{kind:"object",fields:{currency_options:{kind:"array",element:{kind:"object",fields:{tiers:{kind:"array",element:{kind:"object",fields:{flat_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},tiers:{kind:"array",element:{kind:"object",fields:{flat_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}},unit_amount_decimal:{kind:"nullable",inner:{kind:"decimal_string"}}}}}}}}}}}}}}})})});var bV=K((vV)=>{Object.defineProperty(vV,"__esModule",{value:!0});vV.TaxCodes=void 0;var RV=w(),SV=RV.StripeResource.method;vV.TaxCodes=RV.StripeResource.extend({retrieve:SV({method:"GET",fullPath:"/v1/tax_codes/{id}"}),list:SV({method:"GET",fullPath:"/v1/tax_codes",methodType:"list"})})});var _V=K((fV)=>{Object.defineProperty(fV,"__esModule",{value:!0});fV.TaxIds=void 0;var jV=w(),s8=jV.StripeResource.method;fV.TaxIds=jV.StripeResource.extend({create:s8({method:"POST",fullPath:"/v1/tax_ids"}),retrieve:s8({method:"GET",fullPath:"/v1/tax_ids/{id}"}),list:s8({method:"GET",fullPath:"/v1/tax_ids",methodType:"list"}),del:s8({method:"DELETE",fullPath:"/v1/tax_ids/{id}"})})});var uV=K((hV)=>{Object.defineProperty(hV,"__esModule",{value:!0});hV.TaxRates=void 0;var gV=w(),r8=gV.StripeResource.method;hV.TaxRates=gV.StripeResource.extend({create:r8({method:"POST",fullPath:"/v1/tax_rates"}),retrieve:r8({method:"GET",fullPath:"/v1/tax_rates/{tax_rate}"}),update:r8({method:"POST",fullPath:"/v1/tax_rates/{tax_rate}"}),list:r8({method:"GET",fullPath:"/v1/tax_rates",methodType:"list"})})});var dV=K((lV)=>{Object.defineProperty(lV,"__esModule",{value:!0});lV.Tokens=void 0;var nV=w(),cV=nV.StripeResource.method;lV.Tokens=nV.StripeResource.extend({create:cV({method:"POST",fullPath:"/v1/tokens"}),retrieve:cV({method:"GET",fullPath:"/v1/tokens/{token}"})})});var sV=K((aV)=>{Object.defineProperty(aV,"__esModule",{value:!0});aV.Topups=void 0;var iV=w(),G8=iV.StripeResource.method;aV.Topups=iV.StripeResource.extend({create:G8({method:"POST",fullPath:"/v1/topups"}),retrieve:G8({method:"GET",fullPath:"/v1/topups/{topup}"}),update:G8({method:"POST",fullPath:"/v1/topups/{topup}"}),list:G8({method:"GET",fullPath:"/v1/topups",methodType:"list"}),cancel:G8({method:"POST",fullPath:"/v1/topups/{topup}/cancel"})})});var $3=K((tV)=>{Object.defineProperty(tV,"__esModule",{value:!0});tV.Transfers=void 0;var rV=w(),e=rV.StripeResource.method;tV.Transfers=rV.StripeResource.extend({create:e({method:"POST",fullPath:"/v1/transfers"}),retrieve:e({method:"GET",fullPath:"/v1/transfers/{transfer}"}),update:e({method:"POST",fullPath:"/v1/transfers/{transfer}"}),list:e({method:"GET",fullPath:"/v1/transfers",methodType:"list"}),createReversal:e({method:"POST",fullPath:"/v1/transfers/{id}/reversals"}),listReversals:e({method:"GET",fullPath:"/v1/transfers/{id}/reversals",methodType:"list"}),retrieveReversal:e({method:"GET",fullPath:"/v1/transfers/{transfer}/reversals/{id}"}),updateReversal:e({method:"POST",fullPath:"/v1/transfers/{transfer}/reversals/{id}"})})});var X3=K((J3)=>{Object.defineProperty(J3,"__esModule",{value:!0});J3.WebhookEndpoints=void 0;var Z3=w(),V8=Z3.StripeResource.method;J3.WebhookEndpoints=Z3.StripeResource.extend({create:V8({method:"POST",fullPath:"/v1/webhook_endpoints"}),retrieve:V8({method:"GET",fullPath:"/v1/webhook_endpoints/{webhook_endpoint}"}),update:V8({method:"POST",fullPath:"/v1/webhook_endpoints/{webhook_endpoint}"}),list:V8({method:"GET",fullPath:"/v1/webhook_endpoints",methodType:"list"}),del:V8({method:"DELETE",fullPath:"/v1/webhook_endpoints/{webhook_endpoint}"})})});var G3=K((E)=>{Object.defineProperty(E,"__esModule",{value:!0});E.Subscriptions=E.SubscriptionSchedules=E.SubscriptionItems=E.Sources=E.ShippingRates=E.SetupIntents=E.SetupAttempts=E.Reviews=E.Refunds=E.Quotes=E.PromotionCodes=E.Products=E.Prices=E.Plans=E.Payouts=E.PaymentRecords=E.PaymentMethods=E.PaymentMethodDomains=E.PaymentMethodConfigurations=E.PaymentLinks=E.PaymentIntents=E.PaymentAttemptRecords=E.OAuth=E.Mandates=E.Invoices=E.InvoiceRenderingTemplates=E.InvoicePayments=E.InvoiceItems=E.Files=E.FileLinks=E.ExchangeRates=E.Events=E.EphemeralKeys=E.Disputes=E.Customers=E.CustomerSessions=E.CreditNotes=E.Coupons=E.CountrySpecs=E.ConfirmationTokens=E.Charges=E.BalanceTransactions=E.BalanceSettings=E.Balance=E.ApplicationFees=E.ApplePayDomains=E.Accounts=E.AccountSessions=E.AccountLinks=E.Account=void 0;E.V2=E.Treasury=E.TestHelpers=E.Terminal=E.Tax=E.Sigma=E.Reporting=E.Radar=E.Issuing=E.Identity=E.Forwarding=E.FinancialConnections=E.Entitlements=E.Climate=E.Checkout=E.BillingPortal=E.Billing=E.Apps=E.WebhookEndpoints=E.Transfers=E.Topups=E.Tokens=E.TaxRates=E.TaxIds=E.TaxCodes=void 0;var x=w1(),Xz=q1(),Yz=A1(),Gz=P1(),Vz=m1(),Bz=p1(),Wz=o1(),Uz=e1(),zz=Q4(),Lz=V4(),Kz=z4(),Hz=w4(),wz=q4(),Tz=k4(),Dz=I4(),Oz=v4(),qz=f4(),Ez=h4(),Fz=n4(),Cz=a4(),kz=t4(),Az=J6(),Nz=G6(),xz=U6(),Iz=H6(),Pz=q6(),Sz=k6(),Rz=I6(),vz=v6(),yz=f6(),bz=h6(),jz=n6(),fz=i6(),Mz=r6(),_z=Z7(),gz=Y7(),hz=W7(),mz=K7(),uz=D7(),cz=F7(),nz=N7(),lz=S7(),pz=b7(),dz=_7(),iz=u7(),az=p7(),oz=o7(),sz=e7(),rz=QJ(),tz=BJ(),ez=KJ(),$L=DJ(),ZL=FJ(),JL=NJ(),QL=RJ(),XL=jJ(),YL=hJ(),GL=nJ(),VL=iJ(),BL=rJ(),WL=J5(),UL=G5(),zL=z5(),LL=w5(),KL=q5(),HL=k5(),wL=P5(),TL=b5(),DL=g5(),OL=c5(),qL=d5(),EL=r5(),FL=JQ(),CL=GQ(),kL=UQ(),AL=HQ(),NL=qQ(),xL=kQ(),IL=IQ(),PL=yQ(),SL=MQ(),RL=G9();Object.defineProperty(E,"Account",{enumerable:!0,get:function(){return RL.Accounts}});var vL=nQ();Object.defineProperty(E,"AccountLinks",{enumerable:!0,get:function(){return vL.AccountLinks}});var yL=iQ();Object.defineProperty(E,"AccountSessions",{enumerable:!0,get:function(){return yL.AccountSessions}});var bL=G9();Object.defineProperty(E,"Accounts",{enumerable:!0,get:function(){return bL.Accounts}});var jL=rQ();Object.defineProperty(E,"ApplePayDomains",{enumerable:!0,get:function(){return jL.ApplePayDomains}});var fL=ZX();Object.defineProperty(E,"ApplicationFees",{enumerable:!0,get:function(){return fL.ApplicationFees}});var ML=YX();Object.defineProperty(E,"Balance",{enumerable:!0,get:function(){return ML.Balance}});var _L=UX();Object.defineProperty(E,"BalanceSettings",{enumerable:!0,get:function(){return _L.BalanceSettings}});var gL=wX();Object.defineProperty(E,"BalanceTransactions",{enumerable:!0,get:function(){return gL.BalanceTransactions}});var hL=qX();Object.defineProperty(E,"Charges",{enumerable:!0,get:function(){return hL.Charges}});var mL=kX();Object.defineProperty(E,"ConfirmationTokens",{enumerable:!0,get:function(){return mL.ConfirmationTokens}});var uL=PX();Object.defineProperty(E,"CountrySpecs",{enumerable:!0,get:function(){return uL.CountrySpecs}});var cL=yX();Object.defineProperty(E,"Coupons",{enumerable:!0,get:function(){return cL.Coupons}});var nL=MX();Object.defineProperty(E,"CreditNotes",{enumerable:!0,get:function(){return nL.CreditNotes}});var lL=mX();Object.defineProperty(E,"CustomerSessions",{enumerable:!0,get:function(){return lL.CustomerSessions}});var pL=lX();Object.defineProperty(E,"Customers",{enumerable:!0,get:function(){return pL.Customers}});var dL=aX();Object.defineProperty(E,"Disputes",{enumerable:!0,get:function(){return dL.Disputes}});var iL=eX();Object.defineProperty(E,"EphemeralKeys",{enumerable:!0,get:function(){return iL.EphemeralKeys}});var aL=XY();Object.defineProperty(E,"Events",{enumerable:!0,get:function(){return aL.Events}});var oL=WY();Object.defineProperty(E,"ExchangeRates",{enumerable:!0,get:function(){return oL.ExchangeRates}});var sL=KY();Object.defineProperty(E,"FileLinks",{enumerable:!0,get:function(){return sL.FileLinks}});var rL=FY();Object.defineProperty(E,"Files",{enumerable:!0,get:function(){return rL.Files}});var tL=NY();Object.defineProperty(E,"InvoiceItems",{enumerable:!0,get:function(){return tL.InvoiceItems}});var eL=RY();Object.defineProperty(E,"InvoicePayments",{enumerable:!0,get:function(){return eL.InvoicePayments}});var $K=jY();Object.defineProperty(E,"InvoiceRenderingTemplates",{enumerable:!0,get:function(){return $K.InvoiceRenderingTemplates}});var ZK=gY();Object.defineProperty(E,"Invoices",{enumerable:!0,get:function(){return ZK.Invoices}});var JK=cY();Object.defineProperty(E,"Mandates",{enumerable:!0,get:function(){return JK.Mandates}});var QK=iY();Object.defineProperty(E,"OAuth",{enumerable:!0,get:function(){return QK.OAuth}});var XK=tY();Object.defineProperty(E,"PaymentAttemptRecords",{enumerable:!0,get:function(){return XK.PaymentAttemptRecords}});var YK=JG();Object.defineProperty(E,"PaymentIntents",{enumerable:!0,get:function(){return YK.PaymentIntents}});var GK=GG();Object.defineProperty(E,"PaymentLinks",{enumerable:!0,get:function(){return GK.PaymentLinks}});var VK=UG();Object.defineProperty(E,"PaymentMethodConfigurations",{enumerable:!0,get:function(){return VK.PaymentMethodConfigurations}});var BK=HG();Object.defineProperty(E,"PaymentMethodDomains",{enumerable:!0,get:function(){return BK.PaymentMethodDomains}});var WK=OG();Object.defineProperty(E,"PaymentMethods",{enumerable:!0,get:function(){return WK.PaymentMethods}});var UK=CG();Object.defineProperty(E,"PaymentRecords",{enumerable:!0,get:function(){return UK.PaymentRecords}});var zK=xG();Object.defineProperty(E,"Payouts",{enumerable:!0,get:function(){return zK.Payouts}});var LK=RG();Object.defineProperty(E,"Plans",{enumerable:!0,get:function(){return LK.Plans}});var KK=jG();Object.defineProperty(E,"Prices",{enumerable:!0,get:function(){return KK.Prices}});var HK=gG();Object.defineProperty(E,"Products",{enumerable:!0,get:function(){return HK.Products}});var wK=cG();Object.defineProperty(E,"PromotionCodes",{enumerable:!0,get:function(){return wK.PromotionCodes}});var TK=dG();Object.defineProperty(E,"Quotes",{enumerable:!0,get:function(){return TK.Quotes}});var DK=sG();Object.defineProperty(E,"Refunds",{enumerable:!0,get:function(){return DK.Refunds}});var OK=$V();Object.defineProperty(E,"Reviews",{enumerable:!0,get:function(){return OK.Reviews}});var qK=XV();Object.defineProperty(E,"SetupAttempts",{enumerable:!0,get:function(){return qK.SetupAttempts}});var EK=BV();Object.defineProperty(E,"SetupIntents",{enumerable:!0,get:function(){return EK.SetupIntents}});var FK=LV();Object.defineProperty(E,"ShippingRates",{enumerable:!0,get:function(){return FK.ShippingRates}});var CK=TV();Object.defineProperty(E,"Sources",{enumerable:!0,get:function(){return CK.Sources}});var kK=EV();Object.defineProperty(E,"SubscriptionItems",{enumerable:!0,get:function(){return kK.SubscriptionItems}});var AK=AV();Object.defineProperty(E,"SubscriptionSchedules",{enumerable:!0,get:function(){return AK.SubscriptionSchedules}});var NK=PV();Object.defineProperty(E,"Subscriptions",{enumerable:!0,get:function(){return NK.Subscriptions}});var xK=bV();Object.defineProperty(E,"TaxCodes",{enumerable:!0,get:function(){return xK.TaxCodes}});var IK=_V();Object.defineProperty(E,"TaxIds",{enumerable:!0,get:function(){return IK.TaxIds}});var PK=uV();Object.defineProperty(E,"TaxRates",{enumerable:!0,get:function(){return PK.TaxRates}});var SK=dV();Object.defineProperty(E,"Tokens",{enumerable:!0,get:function(){return SK.Tokens}});var RK=sV();Object.defineProperty(E,"Topups",{enumerable:!0,get:function(){return RK.Topups}});var vK=$3();Object.defineProperty(E,"Transfers",{enumerable:!0,get:function(){return vK.Transfers}});var yK=X3();Object.defineProperty(E,"WebhookEndpoints",{enumerable:!0,get:function(){return yK.WebhookEndpoints}});E.Apps=(0,x.resourceNamespace)("apps",{Secrets:LL.Secrets});E.Billing=(0,x.resourceNamespace)("billing",{Alerts:Wz.Alerts,CreditBalanceSummary:Fz.CreditBalanceSummary,CreditBalanceTransactions:Cz.CreditBalanceTransactions,CreditGrants:kz.CreditGrants,MeterEventAdjustments:Mz.MeterEventAdjustments,MeterEvents:mz.MeterEvents,Meters:cz.Meters});E.BillingPortal=(0,x.resourceNamespace)("billingPortal",{Configurations:Dz.Configurations,Sessions:KL.Sessions});E.Checkout=(0,x.resourceNamespace)("checkout",{Sessions:HL.Sessions});E.Climate=(0,x.resourceNamespace)("climate",{Orders:lz.Orders,Products:ez.Products,Suppliers:DL.Suppliers});E.Entitlements=(0,x.resourceNamespace)("entitlements",{ActiveEntitlements:Bz.ActiveEntitlements,Features:vz.Features});E.FinancialConnections=(0,x.resourceNamespace)("financialConnections",{Accounts:Gz.Accounts,Sessions:wL.Sessions,Transactions:FL.Transactions});E.Forwarding=(0,x.resourceNamespace)("forwarding",{Requests:UL.Requests});E.Identity=(0,x.resourceNamespace)("identity",{VerificationReports:PL.VerificationReports,VerificationSessions:SL.VerificationSessions});E.Issuing=(0,x.resourceNamespace)("issuing",{Authorizations:zz.Authorizations,Cardholders:Hz.Cardholders,Cards:wz.Cards,Disputes:Iz.Disputes,PersonalizationDesigns:sz.PersonalizationDesigns,PhysicalBundles:tz.PhysicalBundles,Tokens:qL.Tokens,Transactions:CL.Transactions});E.Radar=(0,x.resourceNamespace)("radar",{EarlyFraudWarnings:Pz.EarlyFraudWarnings,PaymentEvaluations:oz.PaymentEvaluations,ValueListItems:xL.ValueListItems,ValueLists:IL.ValueLists});E.Reporting=(0,x.resourceNamespace)("reporting",{ReportRuns:BL.ReportRuns,ReportTypes:WL.ReportTypes});E.Sigma=(0,x.resourceNamespace)("sigma",{ScheduledQueryRuns:zL.ScheduledQueryRuns});E.Tax=(0,x.resourceNamespace)("tax",{Associations:Uz.Associations,Calculations:Kz.Calculations,Registrations:VL.Registrations,Settings:TL.Settings,Transactions:kL.Transactions});E.Terminal=(0,x.resourceNamespace)("terminal",{Configurations:Oz.Configurations,ConnectionTokens:Ez.ConnectionTokens,Locations:fz.Locations,OnboardingLinks:nz.OnboardingLinks,Readers:$L.Readers});E.TestHelpers=(0,x.resourceNamespace)("testHelpers",{ConfirmationTokens:qz.ConfirmationTokens,Customers:Nz.Customers,Refunds:GL.Refunds,TestClocks:OL.TestClocks,Issuing:(0,x.resourceNamespace)("issuing",{Authorizations:Lz.Authorizations,Cards:Tz.Cards,PersonalizationDesigns:rz.PersonalizationDesigns,Transactions:AL.Transactions}),Terminal:(0,x.resourceNamespace)("terminal",{Readers:ZL.Readers}),Treasury:(0,x.resourceNamespace)("treasury",{InboundTransfers:bz.InboundTransfers,OutboundPayments:pz.OutboundPayments,OutboundTransfers:iz.OutboundTransfers,ReceivedCredits:JL.ReceivedCredits,ReceivedDebits:XL.ReceivedDebits})});E.Treasury=(0,x.resourceNamespace)("treasury",{CreditReversals:Az.CreditReversals,DebitReversals:xz.DebitReversals,FinancialAccounts:yz.FinancialAccounts,InboundTransfers:jz.InboundTransfers,OutboundPayments:dz.OutboundPayments,OutboundTransfers:az.OutboundTransfers,ReceivedCredits:QL.ReceivedCredits,ReceivedDebits:YL.ReceivedDebits,TransactionEntries:EL.TransactionEntries,Transactions:NL.Transactions});E.V2=(0,x.resourceNamespace)("v2",{Billing:(0,x.resourceNamespace)("billing",{MeterEventAdjustments:_z.MeterEventAdjustments,MeterEventSession:gz.MeterEventSession,MeterEventStream:hz.MeterEventStream,MeterEvents:uz.MeterEvents}),Core:(0,x.resourceNamespace)("core",{AccountLinks:Xz.AccountLinks,AccountTokens:Yz.AccountTokens,Accounts:Vz.Accounts,EventDestinations:Sz.EventDestinations,Events:Rz.Events})})});var C3=K((E3)=>{Object.defineProperty(E3,"__esModule",{value:!0});E3.createStripe=void 0;var V3=M0(),rK=hZ(),O3=w(),B3=G1(),tK=W1(),q3=L1(),eK=b0(),$H=I8(),W3=j0(),t8=G3(),B0=c(),U3="api.stripe.com",z3="443",L3="/v1/",K3=q3.ApiVersion,H3=80000,w3=5,T3=0.5,ZH=["name","version","url","partner_id"],D3=["authenticator","apiVersion","typescript","maxNetworkRetries","httpAgent","httpClient","timeout","host","port","protocol","telemetry","appInfo","stripeAccount","stripeContext"],JH=($)=>new rK.RequestSender($,O3.StripeResource.MAX_BUFFERED_REQUEST_METRICS);function QH($,Z=JH){Q.PACKAGE_VERSION="21.0.1",Q.API_VERSION=q3.ApiVersion;let J=typeof process<"u"&&process.env?(0,B0.detectAIAgent)(process.env):"";Q.AI_AGENT=J,Q.USER_AGENT={bindings_version:Q.PACKAGE_VERSION,lang:"node",typescript:!1,...(0,B0.determineProcessUserAgentProperties)(),...J?{ai_agent:J}:{}},Q.StripeResource=O3.StripeResource,Q.StripeContext=B3.StripeContext,Q.resources=t8,Q.HttpClient=W3.HttpClient,Q.HttpClientResponse=W3.HttpClientResponse,Q.CryptoProvider=eK.CryptoProvider,Q.webhooks=(0,tK.createWebhooks)($),Q.Decimal=$H.Decimal;function Q(X,Y={}){if(!(this instanceof Q))return new Q(X,Y);let G=this._getPropsFromConfig(Y);this._platformFunctions=$,Object.defineProperty(this,"_emitter",{value:this._platformFunctions.createEmitter(),enumerable:!1,configurable:!1,writable:!1}),this.VERSION=Q.PACKAGE_VERSION,this.on=this._emitter.on.bind(this._emitter),this.once=this._emitter.once.bind(this._emitter),this.off=this._emitter.removeListener.bind(this._emitter);let V=G.httpAgent||null;this._api={host:G.host||U3,port:G.port||z3,protocol:G.protocol||"https",basePath:L3,version:G.apiVersion||K3,timeout:(0,B0.validateInteger)("timeout",G.timeout,H3),maxNetworkRetries:(0,B0.validateInteger)("maxNetworkRetries",G.maxNetworkRetries,2),agent:V,httpClient:G.httpClient||(V?this._platformFunctions.createNodeHttpClient(V):this._platformFunctions.createDefaultHttpClient()),dev:!1,stripeAccount:G.stripeAccount||null,stripeContext:G.stripeContext||null};let U=G.typescript||!1;if(U!==Q.USER_AGENT.typescript)Q.USER_AGENT.typescript=U;if(G.appInfo)this._setAppInfo(G.appInfo);this._prepResources(),this._setAuthenticator(X,G.authenticator),this.errors=V3,this.webhooks=Q.webhooks,this._prevRequestMetrics=[],this._enableTelemetry=G.telemetry!==!1,this._requestSender=Z(this),this.StripeResource=Q.StripeResource,this.Decimal=Q.Decimal}return Q.errors=V3,Q.createNodeHttpClient=$.createNodeHttpClient,Q.createFetchHttpClient=$.createFetchHttpClient,Q.createNodeCryptoProvider=$.createNodeCryptoProvider,Q.createSubtleCryptoProvider=$.createSubtleCryptoProvider,Q.prototype={_appInfo:void 0,on:null,off:null,once:null,VERSION:null,StripeResource:null,webhooks:null,errors:null,_api:null,_prevRequestMetrics:null,_emitter:null,_enableTelemetry:null,_requestSender:null,_platformFunctions:null,rawRequest(X,Y,G,V){return this._requestSender._rawRequest(X,Y,G,V)},_setAuthenticator(X,Y){if(X&&Y)throw Error("Can't specify both apiKey and authenticator");if(!X&&!Y)throw Error("Neither apiKey nor config.authenticator provided");this._authenticator=X?(0,B0.createApiKeyAuthenticator)(X):Y},_setAppInfo(X){if(X&&typeof X!=="object")throw Error("AppInfo must be an object.");if(X&&!X.name)throw Error("AppInfo.name is required");X=X||{},this._appInfo=ZH.reduce((Y,G)=>{if(typeof X[G]=="string")Y=Y||{},Y[G]=X[G];return Y},{})},_setApiField(X,Y){this._api[X]=Y},getApiField(X){return this._api[X]},setClientId(X){this._clientId=X},getClientId(){return this._clientId},getConstant:(X)=>{switch(X){case"DEFAULT_HOST":return U3;case"DEFAULT_PORT":return z3;case"DEFAULT_BASE_PATH":return L3;case"DEFAULT_API_VERSION":return K3;case"DEFAULT_TIMEOUT":return H3;case"MAX_NETWORK_RETRY_DELAY_SEC":return w3;case"INITIAL_NETWORK_RETRY_DELAY_SEC":return T3}return Q[X]},getMaxNetworkRetries(){return this.getApiField("maxNetworkRetries")},_setApiNumberField(X,Y,G){let V=(0,B0.validateInteger)(X,Y,G);this._setApiField(X,V)},getMaxNetworkRetryDelay(){return w3},getInitialNetworkRetryDelay(){return T3},getClientUserAgent(X){return this.getClientUserAgentSeeded(Q.USER_AGENT,X)},getClientUserAgentSeeded(X,Y){let G={};for(let W in X){if(!Object.prototype.hasOwnProperty.call(X,W))continue;G[W]=encodeURIComponent(X[W]??"null")}let V=this._platformFunctions.getPlatformInfo();if(V&&this.getTelemetryEnabled())G.platform=encodeURIComponent(V);else delete G.platform;let U=this.getApiField("httpClient");if(U)G.httplib=encodeURIComponent(U.getClientName());if(this._appInfo)G.application=this._appInfo;Y(JSON.stringify(G))},getAppInfoAsString(){if(!this._appInfo)return"";let X=this._appInfo.name;if(this._appInfo.version)X+=`/${this._appInfo.version}`;if(this._appInfo.url)X+=` (${this._appInfo.url})`;return X},getTelemetryEnabled(){return this._enableTelemetry},_prepResources(){for(let X in t8){if(!Object.prototype.hasOwnProperty.call(t8,X))continue;this[(0,B0.pascalToCamelCase)(X)]=new t8[X](this)}},_getPropsFromConfig(X){if(!X)return{};let Y=typeof X==="string";if(!(X===Object(X)&&!Array.isArray(X))&&!Y)throw Error("Config must either be an object or a string");if(Y)return{apiVersion:X};if(Object.keys(X).filter((U)=>!D3.includes(U)).length>0)throw Error(`Config object may only contain the following: ${D3.join(", ")}`);return X},parseEventNotification(X,Y,G,V,U,W){this.webhooks.signature.verifyHeader(X,Y,G,V||this.webhooks.DEFAULT_TOLERANCE,U,W);let B=X instanceof Uint8Array?JSON.parse(new TextDecoder("utf8").decode(X)):JSON.parse(X);if(B&&B.object==="event")throw Error("You passed a webhook payload to stripe.parseEventNotification, which expects an event notification. Use stripe.webhooks.constructEvent instead.");if(B.context)B.context=B3.StripeContext.parse(B.context);return B.fetchEvent=()=>{return this._requestSender._rawRequest("GET",`/v2/core/events/${B.id}`,void 0,{stripeContext:B.context,headers:{"Stripe-Request-Trigger":`event=${B.id}`}},["fetch_event"])},B.fetchRelatedObject=()=>{if(!B.related_object)return Promise.resolve(null);return this._requestSender._rawRequest("GET",B.related_object.url,void 0,{stripeContext:B.context,headers:{"Stripe-Request-Trigger":`event=${B.id}`}},["fetch_related_object"])},B}},Q}E3.createStripe=QH});var A3=K((k3,B8)=>{Object.defineProperty(k3,"__esModule",{value:!0});var XH=fZ(),YH=C3(),GH=I8(),U9=(0,YH.createStripe)(new XH.NodePlatformFunctions);B8.exports=U9;B8.exports.Stripe=U9;B8.exports.default=U9;B8.exports.Decimal=GH.Decimal});import"@stacksjs/validation";import{log as Q$}from"@stacksjs/cli";import{db as T9}from"@stacksjs/database";async function JB($,Z={}){let{olderThanDays:J=30,column:Q="created_at",query:X}=Z;try{if(X){let W=T9.deleteFrom($);W=X(W);let B=await W.execute(),z=Array.isArray(B)?B:[B],L=Number(z[0]?.numDeletedRows??z.length??0);return Q$.info(`Pruned ${L} records from ${$}`),L}let Y=new Date;Y.setDate(Y.getDate()-J);let G=await T9.deleteFrom($).where(Q,"<",Y.toISOString()).execute(),V=Array.isArray(G)?G:[G],U=Number(V[0]?.numDeletedRows??V.length??0);return Q$.info(`Pruned ${U} records from ${$} older than ${J} days`),U}catch(Y){throw Q$.error(`Failed to prune ${$}:`,Y),Y}}async function ZT($,Z={}){return JB($,Z)}function JT($){if(!$?.prunable)return null;if(typeof $.prunable==="boolean")return{olderThanDays:30,column:"created_at"};return $.prunable}import{createCipheriv as QB,createDecipheriv as XB,createHash as YB,randomBytes as GB}from"crypto";import{log as H8}from"@stacksjs/logging";var D9="enc:",O9="aes-256-gcm",VB=12,K8=null;async function q9(){if(K8)return K8;let $=process.env.APP_KEY;if(!$)try{$=(await import("@stacksjs/config").catch(()=>null))?.config?.app?.key}catch{}if(!$)return null;return K8=YB("sha256").update($).digest(),K8}function S0($){return typeof $==="string"&&$.startsWith(D9)}async function X$($){if($==null)return $;if(S0($))return $;if(typeof $!=="string")return $;let Z=await q9();if(!Z)return H8.warn("[orm] encrypted attribute: APP_KEY not set \u2014 storing value in plaintext"),$;let J=GB(VB),Q=QB(O9,Z,J),X=Buffer.concat([Q.update($,"utf8"),Q.final()]),Y=Q.getAuthTag();return`${D9}${J.toString("base64")}:${Y.toString("base64")}:${X.toString("base64")}`}async function Y$($){if($==null)return $;if(typeof $!=="string")return $;if(!S0($))return $;try{let Z=await q9();if(!Z)return H8.warn("[orm] encrypted attribute: APP_KEY not set \u2014 cannot decrypt"),null;let[,J,Q,X]=$.split(":");if(!J||!Q||!X)return H8.warn("[orm] encrypted attribute: malformed envelope, returning null"),null;let Y=Buffer.from(J,"base64"),G=Buffer.from(Q,"base64"),V=Buffer.from(X,"base64"),U=XB(O9,Z,Y);return U.setAuthTag(G),Buffer.concat([U.update(V),U.final()]).toString("utf8")}catch(Z){return H8.warn("[orm] encrypted attribute: decrypt failed (key rotation? corrupted ciphertext?)",{error:Z}),null}}function G$($){let Z=$.attributes;if(!Z||typeof Z!=="object")return[];let J=[];for(let[Q,X]of Object.entries(Z))if(X&&typeof X==="object"&&X.encrypted===!0)J.push(Q);return J}import{log as v0}from"@stacksjs/logging";var BB=[/^password$/i,/^password_hash$/i,/^api_key$/i,/_token$/i,/_secret$/i,/^remember_token$/i],F9="model_audits",W$=null;function WB($){W$=$}async function V$(){if(W$!=null)return W$;try{let $=await import("@stacksjs/router").catch(()=>null);if(!$)return null;let Z=$.getCurrentRequest;if(typeof Z!=="function")return null;let J=Z();if(!J)return null;return(J.user??J._user)?.id??null}catch{return null}}function w8($){if(!$||typeof $!=="object")return null;let Z={};for(let[J,Q]of Object.entries($)){if(BB.some((X)=>X.test(J)))continue;Z[J]=Q}return Z}function R0($){if(!$||typeof $!=="object")return null;let Z=$;if(Z._attributes&&typeof Z._attributes==="object")return{...Z._attributes};return{...$}}function UB($,Z){if(!$||!Z)return{old:$,next:Z};let J={},Q={},X=new Set([...Object.keys($),...Object.keys(Z)]);for(let Y of X)if($[Y]!==Z[Y])J[Y]=$[Y],Q[Y]=Z[Y];return{old:J,next:Q}}async function B$($,Z=!1){try{let{db:J}=await import("@stacksjs/database");await J.insertInto(F9).values({auditable_type:$.auditable_type,auditable_id:$.auditable_id,event:$.event,old_values:$.old_values?JSON.stringify($.old_values):null,new_values:$.new_values?JSON.stringify($.new_values):null,user_id:$.user_id,created_at:new Date().toISOString()}).executeTakeFirst()}catch(J){if(v0.warn(`[orm] audit row write failed for ${$.auditable_type}#${String($.auditable_id)} (${$.event})`,{error:J}),Z)throw J}}function C9($){return{async audits(Z){try{let{db:J}=await import("@stacksjs/database");return(await J.selectFrom(F9).selectAll().where("auditable_type","=",$).where("auditable_id","=",Z).orderBy("created_at","desc").execute()??[]).map((X)=>({...X,old_values:typeof X.old_values==="string"?E9(X.old_values):X.old_values,new_values:typeof X.new_values==="string"?E9(X.new_values):X.new_values}))}catch(J){return v0.warn(`[orm] audits() lookup failed for ${$}#${String(Z)}`,{error:J}),[]}}}}function E9($){try{return JSON.parse($)}catch{return $}}function k9($){if($&&typeof $==="object"&&"transactional"in $)return{transactional:$.transactional===!0};return{transactional:!1}}function A9($,Z,J="id",Q={}){let X=Q.transactional===!0,Y=$;if(typeof $.audits!=="function")$.audits=C9(Z).audits;let G=async(B)=>{if(!X)return await B();let{db:z}=await import("@stacksjs/database");return await z.transaction(async()=>B())},V=$.create;if(typeof V==="function")$.create=async function(...B){return await G(async()=>{let z=await V.apply(this,B);try{let L=R0(z),H=L?.[J];if(H!=null){let T=await V$();await B$({auditable_type:Z,auditable_id:H,event:"created",old_values:null,new_values:w8(L),user_id:T},X)}}catch(L){if(v0.warn(`[orm] audit(create) failed for ${Z}`,{error:L}),X)throw L}return z})};let U=$.update;if(typeof U==="function")$.update=async function(B,z){return await G(async()=>{let L=Y.find,H=typeof L==="function"?R0(await L.call(Y,B)):null,T=await U.call(this,B,z);try{let D=R0(T)??(typeof L==="function"?R0(await L.call(Y,B)):null),{old:q,next:O}=UB(H,D);if(O&&Object.keys(O).length>0){let k=await V$();await B$({auditable_type:Z,auditable_id:B,event:"updated",old_values:w8(q),new_values:w8(O),user_id:k},X)}}catch(D){if(v0.warn(`[orm] audit(update) failed for ${Z}#${String(B)}`,{error:D}),X)throw D}return T})};let W=(B)=>{let z=$[B];if(typeof z!=="function")return;$[B]=async function(L){return await G(async()=>{let H=Y.find,T=typeof H==="function"?R0(await H.call(Y,L)):null,D=await z.call(this,L);try{if(D!==!1&&T){let q=await V$();await B$({auditable_type:Z,auditable_id:L,event:"deleted",old_values:w8(T),new_values:null,user_id:q},X)}}catch(q){if(v0.warn(`[orm] audit(${B}) failed for ${Z}#${String(L)}`,{error:q}),X)throw q}return D})}};W("delete"),W("softDelete")}function N9($){let Z=$;return Z?.code==="SQLITE_CONSTRAINT_UNIQUE"||Z?.code==="SQLITE_CONSTRAINT"||Z?.code==="23505"||Z?.errno===1062||/unique|duplicate/i.test(Z?.message??"")}function zB($,Z,J){let Q=$;if($ instanceof Error&&typeof Q.status==="number"&&Number.isInteger(Q.status)&&Q.status>=400&&Q.status<600){let X={error:$.message};if(Q.details!==void 0)X.details=Q.details;return{status:Q.status,body:X}}if(N9($))return{status:409,body:{error:`${Z} already exists`}};return{status:500,body:{error:`Failed to ${J} ${Z}`,detail:String($)}}}import{cacheRequestQuery as LB}from"@stacksjs/router";var T8=new WeakMap;function zT($,Z){return LB(`batchLoad:${$.name??"model"}:${String(Z)}`,async()=>{return new Promise((J,Q)=>{let X=T8.get($);if(!X)X={keys:[],resolvers:[],scheduled:!1},T8.set($,X);if(X.keys.push(Z),X.resolvers.push({key:Z,resolve:J,reject:Q}),X.scheduled)return;X.scheduled=!0,Promise.resolve().then(async()=>{let Y=T8.get($);if(!Y)return;T8.delete($);let G=Array.from(new Set(Y.keys));try{let V=typeof $.findMany==="function"?await $.findMany(G):await Promise.all(G.map((W)=>$.find?.(W))),U=new Map;for(let W of V??[]){let B=W?.id;if(B!==void 0)U.set(B,W)}for(let W of Y.resolvers)W.resolve(U.get(W.key))}catch(V){for(let U of Y.resolvers)U.reject(V)}})})})}import{db as wT}from"@stacksjs/database";class KB{conditions=[];where($,...Z){let[J,Q]=Z,X=Q===void 0?"=":J,Y=Q===void 0?J:Q;this.addCondition("and","where",$,X,Y)}orWhere($,...Z){let[J,Q]=Z,X=Q===void 0?"=":J,Y=Q===void 0?J:Q;this.addCondition("or","where",$,X,Y)}whereIn($,Z){this.conditions.push({type:"and",method:"whereIn",column:$,values:Z})}whereNotIn($,Z){this.conditions.push({type:"and",method:"whereIn",column:$,values:Z,operator:"not in"})}whereNull($){this.conditions.push({type:"and",method:"whereNull",column:$})}whereNotNull($){this.conditions.push({type:"and",method:"whereNotNull",column:$})}whereBetween($,Z){this.conditions.push({type:"and",method:"whereBetween",column:$,range:Z})}whereExists($){this.conditions.push({type:"and",method:"whereExists",column:"",callback:$})}addCondition($,Z,J,Q,X){this.conditions.push({type:$,method:Z,column:J,operator:Q,value:X})}getConditions(){return this.conditions}}import{db as D8,runInTransactionScope as HB}from"@stacksjs/database";async function OT($,Z){return await HB(async()=>{return await D8.transaction($,Z)})}function qT($){return D8.transaction(async()=>{await $()})}async function ET($){return await D8.savepoint($)}function FT($,Z){return D8.transactional($,Z)}import{path as p}from"@stacksjs/path";import{fs as a,globSync as H$}from"@stacksjs/storage";import{plural as R9,singular as x9,snakeCase as b}from"@stacksjs/strings";import{isString as O8}from"@stacksjs/validation";var U$;function v9(){if(!U$)U$=import("@stacksjs/build");return U$}async function IT($){if(typeof $==="string")$=(await import($)).default;return $.table??b(R9($?.name||""))}function y0($,Z){if($.name)return $.name;return p.basename(Z).replace(/\.ts$/,"")}function u($,Z){if($.table)return $.table;return b(R9(y0($,Z)))}function wB($,Z){let J=[$,Z];return J.sort(),J.join("_")}function PT($,Z){return Z in $}async function TB($,Z){let J=[];if($.hasOne)for(let Q of $.hasOne)J.push(await z$(Q,$,Z,"hasOne"));if($.hasMany)for(let Q of $.hasMany)J.push(await z$(Q,$,Z,"hasMany"));if($.belongsTo)for(let Q of $.belongsTo)J.push(await z$(Q,$,Z,"belongsTo"));if($.hasOneThrough)for(let Q of $.hasOneThrough)J.push(await P9(Q,$,Z,"hasOneThrough"));if($.hasManyThrough)for(let Q of $.hasManyThrough)J.push(await P9(Q,$,Z,"hasManyThrough"));if($.belongsToMany)for(let Q of $.belongsToMany)J.push(await OB(Q,$,Z,"belongsToMany"));if($.morphOne)J.push(await S9($.morphOne,$,Z,"morphOne"));if($.morphMany){let Q=Array.isArray($.morphMany)?$.morphMany:[$.morphMany];for(let X of Q)J.push(await S9(X,$,Z,"morphMany"))}if($.morphTo){let Q=$.morphTo,X=Array.isArray(Q)?Q:typeof Q==="object"&&Q!==null?[Q]:[];for(let Y of X)J.push(DB(Y,$,Z))}if($.morphToMany){let Q=Array.isArray($.morphToMany)?$.morphToMany:[$.morphToMany];for(let X of Q)J.push(I9(X,$,Z,"morphToMany"))}if($.morphedByMany){let Q=Array.isArray($.morphedByMany)?$.morphedByMany:[$.morphedByMany];for(let X of Q)J.push(I9(X,$,Z,"morphedByMany"))}return J}function DB($,Z,J){let Q=$&&typeof $==="object"&&$.name?String($.name):`${b(J)}able`,X=$?.type||`${Q}_type`;return{relationship:"morphTo",model:"",table:"",relationTable:"",foreignKey:$?.id||`${Q}_id`,modelKey:X,relationName:Q,relationModel:J,throughModel:"",throughForeignKey:"",pivotForeign:"",pivotKey:"",pivotTable:""}}function I9($,Z,J,Q){let X=typeof $==="object"&&$!==null,Y=X?String($.model||""):String($),G=X&&$.morphName?String($.morphName):`${b(J)}able`,V=X&&$.pivotTable?String($.pivotTable):G,U=X&&$.id||`${G}_id`,W=X&&$.type||`${G}_type`;return{relationship:Q,model:Y,table:"",relationTable:"",foreignKey:U,modelKey:W,relationName:G,relationModel:J,throughModel:"",throughForeignKey:"",pivotForeign:U,pivotKey:W,pivotTable:V}}async function q8($,Z){let J=K$(`${Z}.ts`),Q=K$(`${$}.ts`),X=L$(`${$}.ts`),Y=L$(`${Z}.ts`);if(!J&&!Y)throw Error(`Model not found: ${Z}`);if(!Q&&!X)throw Error(`Model not found: ${$}`);let G;try{if(a.existsSync(J))G=(await import(J)).default;else G=(await import(Y)).default}catch(U){throw Error(`Failed to load model: ${Z}. Error: ${U?.message||"Unknown error"}`)}let V=a.existsSync(Q)?Q:X;return{modelRelation:G,modelPath:V,modelRelationPath:a.existsSync(J)?J:Y}}async function P9($,Z,J,Q){let X="",Y="",G="",V="";if(O8($))X=$;else X=$.model,Y=$.relationName||"",G=$.through,V=$.throughForeignKey||"";let{modelRelation:U,modelPath:W,modelRelationPath:B}=await q8(J,X),z=u(U,B),L=u(Z,W),H=b(y0(U,B)),T=b(J);return{relationship:Q,model:X,table:z,relationTable:L,foreignKey:`${T}_id`,modelKey:`${H}_id`,relationName:Y,relationModel:J,throughModel:G,throughForeignKey:V,pivotForeign:`${T}_id`,pivotKey:`${H}_id`,pivotTable:L}}async function OB($,Z,J,Q){let X="",Y="",G="",V=b(J);if(O8($))X=$;else X=$.model,Y=$.pivotTable||"",G=$.firstForeignKey||`${V}_id`;let{modelRelation:U,modelPath:W,modelRelationPath:B}=await q8(J,X),z=u(U,B),L=u(Z,W),H=b(y0(U,B));return{relationship:Q,model:X,table:z,relationTable:L,foreignKey:typeof $==="string"?`${V}_id`:$.firstForeignKey||`${V}_id`,modelKey:typeof $==="string"?`${H}_id`:$.secondForeignKey||`${H}_id`,relationName:"",relationModel:J,throughModel:"",throughForeignKey:"",pivotForeign:G,pivotKey:`${H}_id`,pivotTable:Y}}async function S9($,Z,J,Q){let X="",Y="",G="",V="";if(O8($))X=$,Y=`${b(J)}able`;else X=$.model,Y=$.morphName||`${b(J)}able`,G=$.type||`${Y}_type`,V=$.id||`${Y}_id`;let{modelRelation:U,modelPath:W,modelRelationPath:B}=await q8(J,X),z=u(U,B),L=u(Z,W);return{relationship:Q,model:X,table:z,relationTable:L,foreignKey:V||`${Y}_id`,modelKey:G||`${Y}_type`,relationName:Y,relationModel:J,throughModel:"",throughForeignKey:"",pivotForeign:"",pivotKey:"",pivotTable:L}}async function z$($,Z,J,Q){let X="",Y="";if(O8($))X=$;else X=$.model,Y=$.relationName||"";let{modelRelation:G,modelPath:V,modelRelationPath:U}=await q8(J,X),W=u(G,U),B=u(Z,V),z=b(y0(G,U)),L=b(J),H={relationship:Q,model:X,table:W,relationTable:B,foreignKey:typeof $==="string"?`${L}_id`:$.foreignKey||`${L}_id`,modelKey:`${z}_id`,relationName:Y,relationModel:J,throughModel:"",throughForeignKey:"",pivotForeign:`${L}_id`,pivotKey:`${z}_id`,pivotTable:B};if(Q==="belongsTo")H.foreignKey="";return H}function ST($){let Z=/belongs/,J=/has/,Q=/Through/,X=/morph/;if(Q.test($))return"throughType";if(Z.test($))return"belongsType";if(J.test($))return"hasType";if(X.test($))return"morphType";return""}function RT($){let Z=/One/;if(/Many/.test($))return"many";if(Z.test($))return"one";return""}async function vT($,Z){let J=[];if("belongsToMany"in $){let Q=$.belongsToMany||[];for(let X of Q){let Y,G;if(typeof X==="string")G=X;else G=X.model;let V=K$(`${G}.ts`),U=L$(`${G}.ts`);if(a.existsSync(V))Y=(await import(V)).default;else Y=(await import(U)).default;let W=u(Y,V),B=u($,Z),z=typeof X==="object"&&"firstForeignKey"in X?X.firstForeignKey:`${x9(B)}_${$.primaryKey}`,L=typeof X==="object"&&"secondForeignKey"in X?X.secondForeignKey:`${x9(W)}_${$.primaryKey}`;J.push({table:(typeof X==="object"&&"pivotTable"in X?X.pivotTable:void 0)??wB(B,W),firstForeignKey:z,secondForeignKey:L})}return J}return[]}async function yT($){let Z=H$([p.userModelsPath("*.ts"),p.storagePath("framework/defaults/app/Models/**/*.ts")],{absolute:!0}),J=[];for(let Q=0;Q<Z.length;Q++){let X=Z[Q],Y=await import(X);if($===Y.default.name)continue;let G=y0(Y,X),V=await TB(Y.default,G);if(!V.length)continue;let U=V.find((W)=>W.model===$);if(U)J.push(U)}return J}function bT($){if($===void 0)return[];return Object.keys($).filter((Z)=>{return $[Z]?.hidden===!0})}function jT($){let Z=$.attributes;if(Z===void 0)return[];return Object.keys(Z).filter((J)=>{return Z[J]?.guarded===!0}).map((J)=>b(J))}function fT($,Z){let J=$.attributes,Q=[];if(J===void 0)return[];let X=typeof $.traits?.billable==="object"||typeof $.traits?.billable==="boolean",Y=typeof $.traits?.useAuth==="object"?$.traits?.useAuth.usePasskey:!1,G=$.traits?.useUuid||!1;if(X)Q.push("stripe_id");if(G)Q.push("uuid");if(Y)Q.push(...["two_factor_secret","public_key"]);let V=Z.map((U)=>U.foreignKey).filter((U)=>U);return[...Object.keys(J).filter((U)=>{if(J===void 0)return!1;return J[U]?.fillable===!0}).map((U)=>b(U)),...Q,...V]}async function MT($,Z){let J=$.attributes;if(!J)J={};let Q=Object.keys(J),X=[],Y=Bun.file(Z),G="";try{if(await Y.exists())G=await Y.text()}catch{G=""}let V=/rule:.*$/gm,U;U=V.exec(G);while(U!==null)X.push(U[0]),U=V.exec(G);return Q.map((B,z)=>{let L=J[B],H=null,T=!1,D=!1,q=!1,O=!1;if(L)H=L||null,T=L.unique||!1,D=L.hidden||!1,q=L.fillable||!1;let k=X[z]??"";return O=(L.validation?.rule).isRequired??!1,{field:B,default:H,unique:T,hidden:D,fillable:q,required:O,fieldArray:qB(k)}})}function qB($){let Z=$.split("rule: schema.");if(Z.length!==2)return null;if(!Z[1])Z[1]="";let J=Z[1].replace(/,/g,"");if(!J)return null;let Q=J.split("."),X=/\(([^)]+)\)/;return Q.map((Y)=>{let G=X.exec(Y),V=G?G[1]:null;return{entity:Y.replace(X,"").replace(/\(|\)/g,""),charValue:V}})[0]||null}function _T($){let Z=$.fieldArray?.entity;switch(Z){case"enum":return"string | string[]";case"date":return"Date | string";case"timestamp":return"Date | string";case"datetime":return"Date | string";case"float":return"number";case"double":return"number";case"decimal":return"number";case"integer":return"number";case"bigint":return"number";default:return Z}}async function gT($){let{generator:Z,parser:J,traverse:Q}=await v9(),X=a.readFileSync($,"utf8"),Y=J.parse(X,{sourceType:"module",plugins:["typescript","classProperties","decorators-legacy"]}),G=[];return Q(Y,{ImportDeclaration(V){let U=Z(V.node,{},X);G.push(U.code)}}),G}async function hT($){let{generator:Z,parser:J,traverse:Q}=await v9(),X=a.readFileSync($,"utf8"),Y=J.parse(X,{sourceType:"module",plugins:["typescript","classProperties","decorators-legacy"]}),G;return Q(Y,{ObjectExpression(V){let U=V.node.properties.find((W)=>W.type==="ObjectProperty"&&W.key.type==="Identifier"&&W.key.name==="attributes");if(U&&U.type==="ObjectProperty"&&U.value)G=Z(U.value,{},X).code,V.stop()}}),G}function L$($){let Z=p.join(p.storagePath("framework/defaults/app/Models"),"/"),J=p.join(Z,$);if(a.existsSync(J))return J;return H$(`${Z}**/${$}`,{absolute:!0})[0]??""}function K$($){let Z=p.join(p.userModelsPath("/"),"/"),J=p.join(Z,$);if(a.existsSync(J))return J;return H$(`${Z}**/${$}`,{absolute:!0})[0]??""}function mT($){let Z=typeof $==="number"?new Date($):typeof $==="string"?new Date($):$;if(Number.isNaN(Z.getTime()))throw Error(`Invalid date value: ${String($)}`);return Z.toISOString().replace("T"," ").split(".")[0]??""}function uT($){return $.toISOString().split("T")[0]??""}function cT($){return $.getTime()}import{createModel as zH,registerModel as LH}from"@stacksjs/query-builder";import{log as h}from"@stacksjs/logging";import{snakeCase as Z$}from"@stacksjs/strings";import{AsyncLocalStorage as KH}from"async_hooks";function EB($){if($===null||typeof $!=="object")return!1;let Z=$;return Array.isArray(Z.data)&&typeof Z.current_page==="number"&&typeof Z.per_page==="number"&&typeof Z.total==="number"&&typeof Z.last_page==="number"}function FB($){if($===null||typeof $!=="object")return!1;let Z=$;return Array.isArray(Z.data)&&typeof Z.current_page==="number"&&typeof Z.per_page==="number"&&typeof Z.has_more_pages==="boolean"&&!("total"in Z)}function CB($){if($===null||typeof $!=="object")return!1;let Z=$;return Array.isArray(Z.data)&&(typeof Z.next_cursor==="string"||Z.next_cursor===null)}function w$($){let{data:Z}=$,{perPage:J,page:Q,total:X,lastPage:Y}=$.meta,G=Z.length===0,V=G?null:(Q-1)*J+1,U=G?null:V+Z.length-1;return{data:Z,current_page:Q,per_page:J,total:X,last_page:Y,from:V,to:U,has_more_pages:Q<Y}}function T$($){return{data:$.data,current_page:$.meta.page,per_page:$.meta.perPage,has_more_pages:$.meta.hasMore}}function D$($){return{data:$.data,per_page:$.meta.perPage,next_cursor:y9($.meta.nextCursor),prev_cursor:y9($.meta.prevCursor),has_more_pages:$.meta.nextCursor!==null&&$.meta.nextCursor!==void 0}}function y9($){if($===null||$===void 0)return null;if(typeof $==="string")return $;return JSON.stringify($)}function q$($,Z){let J=C$(),Q=J?O$(J,"per_page"):void 0,X=J?O$(J,"page"):void 0,Y=$!==void 0?Math.max(1,Math.floor($)):Math.min(100,Math.max(1,Q??15)),G=Math.max(1,Math.floor(Z??X??1));return{perPage:Y,page:G}}function E$($,Z){let J=C$(),Q=J?j9(J,"cursor"):void 0,X=J?O$(J,"per_page"):void 0,Y=$!==void 0?Math.max(1,Math.floor($)):Math.min(100,Math.max(1,X??15)),V=b9(Z!==void 0?Z:Q??null);return{perPage:Y,cursor:V}}function b9($){if($===null||$===void 0)return null;if(Array.isArray($))return $;if(typeof $==="string"&&$.startsWith("["))try{let Z=JSON.parse($);if(Array.isArray(Z))return Z}catch{}return $}function F$($){let Z=C$();if(!Z)return $;let J=(()=>{try{return new URL(Z.url)}catch{return null}})();if(!J)return $;let Q=J.pathname;if($.path=Q,"next_cursor"in $)return $.next_page_url=$.next_cursor!==null?Z0(J,{cursor:$.next_cursor}):null,$.prev_page_url=$.prev_cursor!==null?Z0(J,{cursor:$.prev_cursor}):null,$;let X=$.current_page;if($.prev_page_url=X>1?Z0(J,{page:X-1}):null,"total"in $){let Y=$.last_page;$.next_page_url=X<Y?Z0(J,{page:X+1}):null,$.first_page_url=Z0(J,{page:1}),$.last_page_url=Z0(J,{page:Y})}else $.next_page_url=$.has_more_pages?Z0(J,{page:X+1}):null;return $}function Z0($,Z){let J=new URL($.toString());for(let[Q,X]of Object.entries(Z))J.searchParams.set(Q,String(X));return`${J.pathname}${J.search}`}var K0;function C$(){if(K0===null)return;if(K0===void 0)try{let Z=C("@stacksjs/router");if(typeof Z.getCurrentRequest==="function")K0=Z.getCurrentRequest;else{K0=null;return}}catch{K0=null;return}return K0()}function O$($,Z){let J=j9($,Z);if(J===void 0)return;let Q=Number(J);return Number.isFinite(Q)?Q:void 0}function j9($,Z){let J=$.query?.[Z];if(J===void 0)return;return Array.isArray(J)?J[0]:J}import{db as kB,sql as AB}from"@stacksjs/database";function k$($,Z){if(typeof $!=="number"||!Number.isFinite($)||$<=0)throw Error(`[orm/taggable] ${Z} requires a positive numeric id (received ${String($)})`)}function f9($){let Z=kB;return{async tags(J){return k$(J,"tags"),await Z.selectFrom("taggable").where("taggable_id","=",J).where("taggable_type","=",$).selectAll().execute()},async tagCount(J){k$(J,"tagCount");let Q=await Z.selectFrom("taggable").select(AB`count(*) as count`).where("taggable_id","=",J).where("taggable_type","=",$).executeTakeFirst();return Number(Q?.count)||0},async addTag(J,Q){if(k$(J,"addTag"),!Q||typeof Q.name!=="string"||Q.name.trim().length===0)throw Error("[orm/taggable] addTag requires a non-empty tag.name");return await Z.insertInto("taggable").values({...Q,taggable_id:J,taggable_type:$,slug:Q.name.toLowerCase().replace(/[^a-z0-9]+/g,"-"),order:0,is_active:!0,created_at:new Date().toISOString(),updated_at:new Date().toISOString()}).returningAll().executeTakeFirst()},async activeTags(J){return await Z.selectFrom("taggable").where("taggable_id","=",J).where("taggable_type","=",$).where("is_active","=",!0).selectAll().execute()},async inactiveTags(J){return await Z.selectFrom("taggable").where("taggable_id","=",J).where("taggable_type","=",$).where("is_active","=",!1).selectAll().execute()},async removeTag(J,Q){await Z.deleteFrom("taggable").where("taggable_id","=",J).where("taggable_type","=",$).where("id","=",Q).execute()}}}import{db as NB}from"@stacksjs/database";function M9($){let Z=NB;async function J(Q){return(await Z.selectFrom("categorizable_models").where("categorizable_id","=",Q).where("categorizable_type","=",$).selectAll().execute()).map((Y)=>Y.category_id)}return{async categories(Q){let X=await J(Q);if(X.length===0)return[];return await Z.selectFrom("categorizable").where("id","in",X).selectAll().execute()},async categoryCount(Q){return(await J(Q)).length},async addCategory(Q,X){let Y=await Z.selectFrom("categorizable").where("name","=",X.name).selectAll().executeTakeFirst();if(!Y)Y=await Z.insertInto("categorizable").values({name:X.name,description:X.description,slug:X.name.toLowerCase().replace(/[^a-z0-9]+/g,"-"),is_active:!0,created_at:new Date().toISOString(),updated_at:new Date().toISOString()}).returningAll().executeTakeFirst();return await Z.insertInto("categorizable_models").values({categorizable_id:Q,categorizable_type:$,category_id:Y.id,created_at:new Date().toISOString(),updated_at:new Date().toISOString()}).returningAll().executeTakeFirst()},async activeCategories(Q){let X=await J(Q);if(X.length===0)return[];return await Z.selectFrom("categorizable").where("id","in",X).where("is_active","=",!0).selectAll().execute()},async inactiveCategories(Q){let X=await J(Q);if(X.length===0)return[];return await Z.selectFrom("categorizable").where("id","in",X).where("is_active","=",!1).selectAll().execute()},async removeCategory(Q,X){await Z.deleteFrom("categorizable_models").where("categorizable_id","=",Q).where("categorizable_type","=",$).where("category_id","=",X).execute()}}}import{db as xB,sql as IB}from"@stacksjs/database";function _9($,Z){if(typeof $!=="number"||!Number.isFinite($)||$<=0)throw Error(`[orm/commentable] ${Z} requires a positive numeric id (received ${String($)})`)}function g9($){let Z=xB;return{async comments(J){return _9(J,"comments"),await Z.selectFrom("comments").where("commentables_id","=",J).where("commentables_type","=",$).selectAll().execute()},async commentCount(J){let Q=await Z.selectFrom("comments").select(IB`count(*) as count`).where("commentables_id","=",J).where("commentables_type","=",$).executeTakeFirst();return Number(Q?.count)||0},async addComment(J,Q){if(_9(J,"addComment"),!Q||typeof Q.title!=="string"||Q.title.trim().length===0)throw Error("[orm/commentable] addComment requires a non-empty comment.title");if(typeof Q.body!=="string"||Q.body.trim().length===0)throw Error("[orm/commentable] addComment requires a non-empty comment.body");return await Z.insertInto("comments").values({...Q,commentables_id:J,commentables_type:$,status:"pending",created_at:new Date().toISOString(),updated_at:new Date().toISOString()}).returningAll().executeTakeFirst()},async approvedComments(J){return await Z.selectFrom("comments").where("commentables_id","=",J).where("commentables_type","=",$).where("status","=","approved").selectAll().execute()},async pendingComments(J){return await Z.selectFrom("comments").where("commentables_id","=",J).where("commentables_type","=",$).where("status","=","pending").selectAll().execute()},async rejectedComments(J){return await Z.selectFrom("comments").where("commentables_id","=",J).where("commentables_type","=",$).where("status","=","rejected").selectAll().execute()}}}import{db as VH}from"@stacksjs/database";function N3($){let Z=VH;return{async createStripeUser(J,Q){let{manageCustomer:X}=await import("@stacksjs/payments");return await X.createStripeCustomer(J,Q)},async updateStripeUser(J,Q){let{manageCustomer:X}=await import("@stacksjs/payments");return await X.updateStripeCustomer(J,Q)},async deleteStripeUser(J){let{manageCustomer:Q}=await import("@stacksjs/payments");return await Q.deleteStripeUser(J)},async createOrGetStripeUser(J,Q){let{manageCustomer:X}=await import("@stacksjs/payments");return await X.createOrGetStripeUser(J,Q)},async retrieveStripeUser(J){let{manageCustomer:Q}=await import("@stacksjs/payments");return await Q.retrieveStripeUser(J)},async defaultPaymentMethod(J){let{managePaymentMethod:Q}=await import("@stacksjs/payments");return await Q.retrieveDefaultPaymentMethod(J)},async setDefaultPaymentMethod(J,Q){let{managePaymentMethod:X}=await import("@stacksjs/payments");return await X.setDefaultPaymentMethod(J,Q)},async addPaymentMethod(J,Q){let{managePaymentMethod:X}=await import("@stacksjs/payments");return await X.addPaymentMethod(J,Q)},async paymentMethods(J,Q){let{managePaymentMethod:X}=await import("@stacksjs/payments");return await X.listPaymentMethods(J,Q)},async newSubscription(J,Q,X,Y={}){let{manageSubscription:G}=await import("@stacksjs/payments"),V=await G.create(J,Q,X,Y),W=V.latest_invoice?.payment_intent;return{subscription:V,paymentIntent:W}},async updateSubscription(J,Q,X,Y={}){let{manageSubscription:G}=await import("@stacksjs/payments"),V=await G.update(J,Q,X,Y),W=V.latest_invoice?.payment_intent;return{subscription:V,paymentIntent:W}},async cancelSubscription(J,Q,X={}){let{manageSubscription:Y}=await import("@stacksjs/payments");return{subscription:await Y.cancel(Q,X)}},async activeSubscription(J){let{manageSubscription:Q}=await import("@stacksjs/payments"),X=await Z.selectFrom("subscriptions").where("user_id","=",J.id).where("provider_status","=","active").selectAll().executeTakeFirst();if(X){let Y=await Q.retrieve(J,X.provider_id||"");return{subscription:X,providerSubscription:Y}}return},async checkout(J,Q,X={}){let{manageCheckout:Y,manageCustomer:G}=await import("@stacksjs/payments"),V={};if(X.enableTax)V.automatic_tax={enabled:!0},delete X.enableTax;if(X.allowPromotions)V.allow_promotion_codes=!0,delete X.allowPromotions;let B={...{mode:"payment",customer:(await G.createOrGetStripeUser(J,{})).id,line_items:Q.map((z)=>({price:z.priceId,quantity:z.quantity||1}))},...V,...X};return await Y.create(J,B)},async createSetupIntent(J,Q={}){let{manageSetupIntent:X}=await import("@stacksjs/payments");return await X.create(J,Q)},async subscriptionHistory(J){let{manageInvoice:Q}=await import("@stacksjs/payments");return await Q.list(J)},async transactionHistory(J){let{manageTransaction:Q}=await import("@stacksjs/payments");return await Q.list(J)},async connectAccount(J,Q={}){let X=Q.accountColumn||"stripe_account_id",Y=(J._attributes??J)[X];if(!Y)return null;let G=await W8();try{return await G.accounts.retrieve(Y)}catch{return null}},async createConnectAccount(J,Q={}){let X=Q.accountColumn||"stripe_account_id",Y=J._attributes??J,G=Y[X],V=await W8();if(!G){let{stacksIdempotencyKey:U}=await import("@stacksjs/payments"),W=Q.modelTable||$,B=await V.accounts.create({type:Q.type??"express",email:Q.email??Y.email,country:Q.country??"US",capabilities:Q.capabilities??{card_payments:{requested:!0},transfers:{requested:!0}}},{idempotencyKey:U("connect.account.create",W,Y.id)});return G=B.id,await Z.updateTable(W).set({[X]:G}).where("id","=",Number(Y.id)).execute(),B}return await V.accounts.retrieve(G)},async connectOnboardLink(J,Q){let X=Q.accountColumn||"stripe_account_id",G=(J._attributes??J)[X];if(!G)throw Error("connectOnboardLink: model has no Stripe Connect account; call createConnectAccount first");return{url:(await(await W8()).accountLinks.create({account:G,refresh_url:Q.refreshUrl,return_url:Q.returnUrl,type:Q.type??"account_onboarding"})).url,accountId:G}},async syncConnectStatus(J,Q={}){let X=Q.accountColumn||"stripe_account_id",Y=Q.chargesColumn||"charges_enabled",G=Q.payoutsColumn||"payouts_enabled",V=J._attributes??J,U=V[X];if(!U)return{chargesEnabled:!1,payoutsEnabled:!1};let B=await(await W8()).accounts.retrieve(U),z=!!B.charges_enabled,L=!!B.payouts_enabled,H=Q.modelTable||$;return await Z.updateTable(H).set({[Y]:z,[G]:L}).where("id","=",Number(V.id)).execute(),{chargesEnabled:z,payoutsEnabled:L}},async chargeWithSplit(J,Q){let X=await W8(),Y=Q.accountColumn||"stripe_account_id",G=J._attributes??J,V=Q.connectAccountId||G[Y],U={amount:Q.amountCents,currency:Q.currency||"usd",automatic_payment_methods:{enabled:!0},metadata:Q.metadata};if(V){if(U.transfer_data={destination:V},Q.platformFeeCents)U.application_fee_amount=Q.platformFeeCents}let{freshIdempotencyKey:W}=await import("@stacksjs/payments");return await X.paymentIntents.create(U,{idempotencyKey:W("payment_intent.create",G.id,Q.amountCents)})}}}async function W8(){let $=globalThis.process?.env?.STRIPE_SECRET_KEY;if(!$)throw Error("Stripe Connect: STRIPE_SECRET_KEY not configured");return new(await Promise.resolve().then(() => ZB(A3(),1))).default($,{apiVersion:"2024-06-20"})}import{db as BH}from"@stacksjs/database";function x3($,Z){let J=BH,Q=Z?.table||`${$}_likes`,X=Z?.foreignKey||`${$.replace(/s$/,"")}_id`;return{async likes(Y){return await J.selectFrom(Q).where(X,"=",Y).selectAll().execute()},async likeCount(Y){let G=await J.selectFrom(Q).select("count(*) as count").where(X,"=",Y).executeTakeFirst();return Number(G?.count)||0},async like(Y,G){if(typeof Y!=="number"||!Number.isFinite(Y)||Y<=0)throw Error(`[orm/likeable] like requires a positive numeric id (received ${String(Y)})`);if(typeof G!=="number"||!Number.isFinite(G)||G<=0)throw Error(`[orm/likeable] like requires a positive numeric userId (received ${String(G)})`);let V=new Date().toISOString();try{return await J.insertInto(Q).values({[X]:Y,user_id:G,created_at:V,updated_at:V}).returningAll().executeTakeFirst()}catch(U){let W=U;if(!(W.code==="SQLITE_CONSTRAINT_UNIQUE"||W.code==="SQLITE_CONSTRAINT"||W.code==="23505"||W.errno===1062||/unique|duplicate/i.test(W.message??"")))throw U;let z=await J.selectFrom(Q).where(X,"=",Y).where("user_id","=",G).selectAll().executeTakeFirst();if(z)return z;throw U}},async unlike(Y,G){await J.deleteFrom(Q).where(X,"=",Y).where("user_id","=",G).execute()},async isLiked(Y,G){return!!await J.selectFrom(Q).where(X,"=",Y).where("user_id","=",G).selectAll().executeTakeFirst()},async likedBy(Y){return(await J.selectFrom(Q).select([X]).where("user_id","=",Y).execute()).map((V)=>Number(V[X])).filter(Boolean)}}}function I3(){return{async generateTwoFactorForModel($){let{generateTwoFactorSecret:Z}=await import("@stacksjs/auth"),J=Z();await $.update({two_factor_secret:J})},async verifyTwoFactorCode($,Z){let J=$.get("two_factor_secret");if(typeof J!=="string")return!1;let{verifyTwoFactorCode:Q,RateLimiter:X}=await import("@stacksjs/auth"),Y=String($.id??$.get?.("id")??$.get?.("email")??J),G=`2fa:${Y}`;if(await X.isRateLimited(G)){let{HttpError:U}=await import("@stacksjs/error-handling");throw new U(429,"Too many verification attempts. Please try again later.")}if(!await Q(Z,J))return await X.recordFailedAttempt(G),!1;try{let{cache:U}=await import("@stacksjs/cache"),W=`2fa:used:${Y}:${Z}`;if(await U.has(W))return await X.recordFailedAttempt(G),!1;await U.set(W,"1",90)}catch{}return await X.resetAttempts(G),!0}}}import{log as x0}from"@stacksjs/logging";var e8="deleted_at";function P3($,Z="id"){return{async softDelete(J){let Q=new Date().toISOString(),X=$.where(Z,J);if(typeof X?.update==="function")return await X.update({[e8]:Q}),!0;return!1},async restore(J){let Q=$.where(Z,J);if(typeof Q?.update==="function")return await Q.update({[e8]:null}),!0;return!1},async forceDelete(J){let Q=$.where(Z,J);if(typeof Q?.delete==="function")return await Q.delete(),!0;return!1},withTrashed(){return typeof $.query==="function"?$.query():$},onlyTrashed(){let J=typeof $.query==="function"?$.query():$;if(typeof J?.whereNotNull==="function")return J.whereNotNull(e8);return J?.where?.(e8,"!=",null)??J}}}function S3($){if($===!0||$==null)return{};if(typeof $==="object"&&!Array.isArray($)){let Z=$;if(Array.isArray(Z.cascade)){let J=Z.cascade.filter((Q)=>typeof Q==="string");return J.length?{cascade:J}:{}}return{}}return{}}function WH($,Z){let J=$.hasMany??[],Q=$.hasOne??[],X=J.some((B)=>z9(B,Z,!0)),Y=Q.some((B)=>z9(B,Z,!1));if(!X&&!Y)return x0.warn(`[orm] soft-delete cascade: '${Z}' is not a declared hasMany/hasOne relation \u2014 skipping`),null;let V=(X?J:Q).find((B)=>z9(B,Z,X))??null;if(!V)return null;let W=globalThis[V];if(!W)return x0.warn(`[orm] soft-delete cascade: model '${V}' is not yet on globalThis \u2014 skipping cascade for '${Z}'`),null;return{className:V,model:W}}function z9($,Z,J){let Q=$.toLowerCase();if(Z===Q)return!0;if(J&&Z===`${Q}s`)return!0;if(J&&Q.endsWith("y")&&Z===`${Q.slice(0,-1)}ies`)return!0;return!1}async function UH($,Z,J,Q,X){try{let Y=J.where;if(typeof Y!=="function"){x0.warn(`[orm] cascade ${X}: child model has no .where()`);return}if(X==="softDelete"){let G=J.softDelete;if(typeof G==="function"){let U=Y.call(J,Q,Z),W=typeof U?.get==="function"?await U.get():Array.isArray(U)?U:[],B=J.primaryKey||"id";for(let z of W){let L=z?.[B];if(L!=null)await G.call(J,L)}return}let V=Y.call(J,Q,Z);if(typeof V?.delete==="function"){x0.debug(`[orm] cascade soft-delete: child has no softDeletes trait, hard-deleting from ${String(J.table??"?")}`),await V.delete();return}}else{let G=J.restore;if(typeof G!=="function"){x0.debug("[orm] cascade restore: child has no restore() \u2014 nothing to do");return}let V=J.withTrashed,W=(typeof V==="function"?V.call(J):J).where?.(Q,Z),B=typeof W?.get==="function"?await W.get():[],z=J.primaryKey||"id";for(let L of B){let H=L?.[z];if(H!=null)await G.call(J,H)}}}catch(Y){if(x0.warn(`[orm] soft-delete cascade ${X} on ${$}#${String(Z)} failed`,{error:Y}),process.env.STACKS_ORM_CASCADE_SWALLOW!=="true")throw Y}}async function U8($,Z,J,Q){let X=Z.cascade;if(!X||X.length===0)return;let Y=`${$.name.toLowerCase()}_id`;for(let G of X){let V=WH($,G);if(!V)continue;await UH(V.className,J,V.model,Y,Q)}}var _3=new KH;function U0(){return _3.getStore()?.suppressed===!0}function W0($){return Promise.resolve(_3.run({suppressed:!0},$))}var R3=new Set;function HH($,Z){let J=typeof $==="string"?$.slice(0,80):String($),Q=`${typeof $}:${J}`;if(R3.has(Q))return;R3.add(Q);let X=Z instanceof Error?Z.message:String(Z);console.error(`[orm] JSON cast failed to parse value (returning null): ${X} \u2014 value preview: ${JSON.stringify(J)}`)}var wH={string:{get:($)=>$!=null?String($):null,set:($)=>$!=null?String($):null},number:{get:($)=>$!=null?Number($):null,set:($)=>$!=null?Number($):null},integer:{get:($)=>$!=null?Math.trunc(Number($)):null,set:($)=>$!=null?Math.trunc(Number($)):null},float:{get:($)=>$!=null?Number.parseFloat(String($)):null,set:($)=>$!=null?Number.parseFloat(String($)):null},boolean:{get:($)=>$===1||$==="1"||$===!0||$==="true",set:($)=>$===!0||$===1||$==="1"||$==="true"?1:0},json:{get:($)=>{if($==null)return null;if(typeof $==="string")try{return JSON.parse($)}catch(Z){return HH($,Z),null}return $},set:($)=>{if($==null)return null;return typeof $==="string"?$:JSON.stringify($)}},datetime:{get:($)=>$?new Date($):null,set:($)=>$ instanceof Date?$.toISOString():$},date:{get:($)=>$?new Date($):null,set:($)=>$ instanceof Date?$.toISOString().split("T")[0]:$},array:{get:($)=>{if($==null)return[];if(Array.isArray($))return $;if(typeof $==="string")try{return JSON.parse($)}catch{return[]}return[]},set:($)=>{if($==null)return null;return Array.isArray($)?JSON.stringify($):$}}};function g3($){return typeof $==="string"?wH[$]:$}function v3($,Z,J){if(!$||typeof $!=="object")return $;let Q={...$};for(let[X,Y]of Object.entries(Z))if(X in Q){let G=g3(Y);Q[X]=G[J](Q[X])}return Q}var $$=new Set(["_attributes","_original","_definition","_hasSaved","_relations"]),y3=Symbol.for("stacks.modelInstanceProxy"),TH={tags:{bag:"_taggable",mode:"id"},tagCount:{bag:"_taggable",mode:"id"},addTag:{bag:"_taggable",mode:"id"},activeTags:{bag:"_taggable",mode:"id"},inactiveTags:{bag:"_taggable",mode:"id"},removeTag:{bag:"_taggable",mode:"id"},categories:{bag:"_categorizable",mode:"id"},categoryCount:{bag:"_categorizable",mode:"id"},addCategory:{bag:"_categorizable",mode:"id"},activeCategories:{bag:"_categorizable",mode:"id"},inactiveCategories:{bag:"_categorizable",mode:"id"},removeCategory:{bag:"_categorizable",mode:"id"},comments:{bag:"_commentable",mode:"id"},commentCount:{bag:"_commentable",mode:"id"},addComment:{bag:"_commentable",mode:"id"},approvedComments:{bag:"_commentable",mode:"id"},pendingComments:{bag:"_commentable",mode:"id"},rejectedComments:{bag:"_commentable",mode:"id"},likes:{bag:"_likeable",mode:"id"},likeCount:{bag:"_likeable",mode:"id"},like:{bag:"_likeable",mode:"id"},unlike:{bag:"_likeable",mode:"id"},isLiked:{bag:"_likeable",mode:"id"},createStripeUser:{bag:"_billable",mode:"model"},updateStripeUser:{bag:"_billable",mode:"model"},deleteStripeUser:{bag:"_billable",mode:"model"},createOrGetStripeUser:{bag:"_billable",mode:"model"},retrieveStripeUser:{bag:"_billable",mode:"model"},defaultPaymentMethod:{bag:"_billable",mode:"model"},setDefaultPaymentMethod:{bag:"_billable",mode:"model"},addPaymentMethod:{bag:"_billable",mode:"model"},paymentMethods:{bag:"_billable",mode:"model"},newSubscription:{bag:"_billable",mode:"model"},updateSubscription:{bag:"_billable",mode:"model"},cancelSubscription:{bag:"_billable",mode:"model"},activeSubscription:{bag:"_billable",mode:"model"},checkout:{bag:"_billable",mode:"model"},createSetupIntent:{bag:"_billable",mode:"model"},subscriptionHistory:{bag:"_billable",mode:"model"},transactionHistory:{bag:"_billable",mode:"model"},connectAccount:{bag:"_billable",mode:"model"},createConnectAccount:{bag:"_billable",mode:"model"},connectOnboardLink:{bag:"_billable",mode:"model"},syncConnectStatus:{bag:"_billable",mode:"model"},chargeWithSplit:{bag:"_billable",mode:"model"},generateTwoFactorForModel:{bag:"_twoFactor",mode:"model"},verifyTwoFactorCode:{bag:"_twoFactor",mode:"model"}};function DH($,Z){if(!$||!Z)return null;let J=Z.split("."),Q=$;for(let X of J){if(Q==null||typeof Q!=="object")return null;let Y=Q;if("_attributes"in Y&&Y._attributes&&typeof Y._attributes==="object"){let G=Y._attributes;if(X in G){Q=G[X];continue}}if(X in Y){Q=Y[X];continue}return null}return Q??null}function m($,Z){if(!$||typeof $!=="object")return $;if($[y3])return $;let J=$._attributes;if(!J||typeof J!=="object")return $;if(Z&&Object.keys(Z).length>0){for(let[Q,X]of Object.entries(Z))if(Object.prototype.hasOwnProperty.call(J,Q))J[Q]=g3(X).get(J[Q])}return new Proxy($,{get(Q,X,Y){if(X===y3)return!0;if(X==="saveAsync")return async function(){let V=Q._definition,U=V?.set;if(U&&typeof Q.isDirty==="function"){for(let[B,z]of Object.entries(U)){if(typeof z!=="function")continue;if(!Q.isDirty(B))continue;let L=z(Q._attributes),H=L&&typeof L.then==="function"?await L:L;Q._attributes[B]=H}let W=V.set;V.set={};try{return Q.save()}finally{V.set=W}}return Q.save()};if(X==="save")return function(){let V=Q._definition,U=V?.set;if(U&&Object.keys(U).length>0&&typeof Q.isDirty==="function"){for(let[B,z]of Object.entries(U)){if(typeof z!=="function")continue;if(!Q.isDirty(B))continue;let L=z(Q._attributes);if(L&&typeof L.then==="function")throw Error(`Setter for "${B}" returned a Promise \u2014 use \`saveAsync()\` instead of \`save()\` when a model has async setters.`);Q._attributes[B]=L}let W=V.set;V.set={};try{return Q.save()}finally{V.set=W}}return Q.save()};if(X==="updateAsync")return async function(V){if(V&&typeof V==="object"&&!Array.isArray(V))for(let[U,W]of Object.entries(V))Y[U]=W;return Y.saveAsync()};if(X==="saveQuietly")return function(){return W0(()=>Q.save())};if(X==="saveAsyncQuietly")return function(){return W0(()=>Y.saveAsync())};if(X==="updateQuietly")return function(V){return W0(()=>Q.update(V))};if(X==="updateAsyncQuietly")return function(V){return W0(()=>Y.updateAsync(V))};if(X==="deleteQuietly")return function(){return W0(()=>Q.delete())};if(X==="toSearchableObject")return function(){let W=Q._definition?.traits?.useSearch;if(!W)return null;let B=Q._attributes;if(!B)return null;if(W===!0){let D={...B};if(B.id!=null)D.id=String(B.id);return D}let z={},L=W.displayable?.length?W.displayable:[...W.searchable??[],...W.filterable??[],...W.sortable??[],"id"],H=W.denormalize??{},T=Q._relations;for(let D of L){let q=Z$(D),O=B[q]??B[D];if(O!==void 0){z[q]=O;continue}let k=H[D]??H[q];if(k){z[q]=DH(T,k);continue}z[q]=void 0}if(B.id!=null)z.id=String(B.id);return z};if(typeof X==="string"&&!$$.has(X)){let V=Q._attributes;if(V&&Object.prototype.hasOwnProperty.call(V,X))return V[X];let U=Q._relations;if(U&&Object.prototype.hasOwnProperty.call(U,X)){let B=U[X];if(Array.isArray(B))return B.map((z)=>m(z,Z));return m(B,Z)}let W=TH[X];if(W){let L=Q._definition?.__traitMethods?.[W.bag]?.[X];if(typeof L==="function")return W.mode==="model"?(...H)=>L(Y,...H):(...H)=>L(Q.id,...H)}}let G=Reflect.get(Q,X,Q);return typeof G==="function"?G.bind(Q):G},set(Q,X,Y,G){if(typeof X==="string"&&!$$.has(X)){let{_attributes:V,set:U}=Q;if(V&&Object.prototype.hasOwnProperty.call(V,X)){if(typeof U==="function")U.call(Q,X,Y);else V[X]=Y;return!0}if(V&&!(X in Q)){if(typeof U==="function")U.call(Q,X,Y);else V[X]=Y;return!0}}return Reflect.set(Q,X,Y,G)},has(Q,X){if(typeof X==="string"&&!$$.has(X)){let Y=Q._attributes;if(Y&&Object.prototype.hasOwnProperty.call(Y,X))return!0;let G=Q._relations;if(G&&Object.prototype.hasOwnProperty.call(G,X))return!0}return Reflect.has(Q,X)},deleteProperty(Q,X){if(typeof X==="string"&&!$$.has(X)){let Y=Q._attributes;if(Y&&Object.prototype.hasOwnProperty.call(Y,X))return delete Y[X],!0}return Reflect.deleteProperty(Q,X)},ownKeys(Q){let X=Q._attributes;return X?Object.keys(X):[]},getOwnPropertyDescriptor(Q,X){if(typeof X==="string"){let Y=Q._attributes;if(Y&&Object.prototype.hasOwnProperty.call(Y,X))return{configurable:!0,enumerable:!0,value:Y[X],writable:!0}}return Object.getOwnPropertyDescriptor(Q,X)}})}var OH=new Set(["get","first","last","firstOrFail","find","findOrFail","all","paginate","simplePaginate","cursorPaginate"]),qH={paginate:w$,simplePaginate:T$,cursorPaginate:D$},b3=Symbol.for("stacks.queryBuilderProxy");function h3($,Z){if(!$||typeof $!=="object")return $;if($[b3])return $;return new Proxy($,{get(J,Q,X){if(Q===b3)return!0;let Y=Reflect.get(J,Q,X);if(typeof Y!=="function")return Y;return function(...G){let V=G,U=String(Q);if(U==="paginate"||U==="simplePaginate"){let{perPage:z,page:L}=q$(G[0],G[1]);V=[z,L]}else if(U==="cursorPaginate"){let{perPage:z,cursor:L}=E$(G[0],G[1]);V=[z,L,G[2],G[3]]}let W=Y.apply(J,V),B=(z)=>{if(OH.has(U)){if(Array.isArray(z))return z.map((H)=>m(H,Z));let L=qH[U];if(L&&z&&Array.isArray(z.data)){let H=z.data.map((D)=>m(D,Z)),T=L({...z,data:H});return F$(T)}if(z&&Array.isArray(z.data))return{...z,data:z.data.map((H)=>m(H,Z))};return m(z,Z)}if(z&&typeof z==="object"&&typeof z.get==="function")return h3(z,Z);return z};if(W&&typeof W.then==="function")return W.then(B);return B(W)}}})}function EH($,Z){let J=["find","first","last","all","firstOrFail","findOrFail","findMany"];for(let Y of J){let G=$[Y];if(typeof G!=="function")continue;$[Y]=function(...V){let U=G.apply(this,V),W=(B)=>Array.isArray(B)?B.map((z)=>m(z,Z)):m(B,Z);if(U&&typeof U.then==="function")return U.then(W);return W(U)}}let Q=["create","firstOrCreate","updateOrCreate","make"];for(let Y of Q){let G=$[Y];if(typeof G!=="function")continue;$[Y]=function(...V){let U=G.apply(this,V),W=(B)=>Array.isArray(B)?B.map((z)=>m(z,Z)):m(B,Z);if(U&&typeof U.then==="function")return U.then(W);return W(U)}}let X=["query","where","orWhere","whereIn","whereNotIn","whereNull","whereNotNull","whereLike","whereBetween","whereNotBetween","orderBy","orderByDesc","select","with","limit","take","skip","latest","oldest"];for(let Y of X){let G=$[Y];if(typeof G!=="function")continue;$[Y]=function(...V){let U=G.apply(this,V);return h3(U,Z)}}}class m3 extends Error{model;id;constructor($,Z){super(Z!=null?`[ORM] ${$} not found for id=${String(Z)}`:`[ORM] No matching ${$} row`);this.name="ModelNotFoundError",this.model=$,this.id=Z}}class K9 extends Error{model;attribute;reason;constructor($,Z,J){let Q=J==="guarded"?`'${Z}' is marked guarded`:`'${Z}' is not in the fillable allowlist`;super(`[ORM] Mass assignment to ${$} forbidden: ${Q}. Use ${$}.forceCreate(...) / .forceUpdate(...) to bypass.`);this.name="MassAssignmentException",this.model=$,this.attribute=Z,this.reason=J}}var FH=new Set(["id","created_at","updated_at","deleted_at","uuid"]);function z8($,Z,J={}){if(J.force)return Z;if(!Z||typeof Z!=="object"||Array.isArray(Z))return Z;let Q=$.attributes;if(!Q)return Z;let X=new Set,Y=new Set,G=new Set;for(let[U,W]of Object.entries(Q)){let B=Z$(U);if(X.add(B),W?.fillable===!0)Y.add(B);if(W?.guarded===!0)G.add(B)}let V=Y.size>0?Y:X;for(let U of Object.keys(Z)){if(FH.has(U))continue;if(G.has(U))throw new K9($.name,U,"guarded");if(U.endsWith("_id"))continue;if(!V.has(U))throw new K9($.name,U,"not-fillable")}return Z}async function H9($,Z){let J=$.set;if(!J||typeof J!=="object")return Z;let Q={...Z};for(let[X,Y]of Object.entries(J)){if(typeof Y!=="function"||!(X in Q))continue;try{Q[X]=await Y(Q)}catch(G){h.error(`[orm] ${$.name}.set.${X} threw \u2014 skipping setter`,G)}}return Q}function CH($,Z){let J=Z.primaryKey||"id",Q=$.create;function X(W){let B=$.where;if(typeof B!=="function")throw Error(`[ORM] ${Z.name}.${W} needs a working where(): the underlying query builder did not expose one`);return B}function Y(W){let B=$.find;if(typeof B!=="function")throw Error(`[ORM] ${Z.name}.${W} needs a working find(): the underlying query builder did not expose one`);return B}function G(W){let B=$.create;if(typeof B!=="function")throw Error(`[ORM] ${Z.name}.${W} cannot create: the underlying query builder did not expose create()`);return B}if(typeof $.update!=="function")$.update=async function(W,B){if(W==null)throw Error(`[ORM] ${Z.name}.update requires an id as the first argument`);if(!B||typeof B!=="object"||Array.isArray(B))throw Error(`[ORM] ${Z.name}.update requires a data object as the second argument`);if(Object.keys(B).length===0){h.debug(`[orm] ${Z.name}.update called with empty data \u2014 short-circuiting and returning current row`);let H=$.find;return typeof H==="function"?await H.call($,W):null}z8(Z,B);let z=await H9(Z,B);await X("update").call($,J,W).update(z);let L=$.find;return typeof L==="function"?await L.call($,W):null};if(typeof $.forceUpdate!=="function")$.forceUpdate=async function(W,B){if(W==null)throw Error(`[ORM] ${Z.name}.forceUpdate requires an id as the first argument`);if(!B||typeof B!=="object"||Array.isArray(B))throw Error(`[ORM] ${Z.name}.forceUpdate requires a data object as the second argument`);let z=await H9(Z,B);await X("forceUpdate").call($,J,W).update(z);let L=$.find;return typeof L==="function"?await L.call($,W):null};if(typeof $.forceCreate!=="function")$.forceCreate=async function(W){if(!W||typeof W!=="object"||Array.isArray(W))throw Error(`[ORM] ${Z.name}.forceCreate requires a data object`);if(typeof Q!=="function")throw Error(`[ORM] ${Z.name}.forceCreate cannot create: the underlying query builder did not expose create()`);return await Q.call($,W)};if(typeof $.delete!=="function")$.delete=async function(W){if(W==null)throw Error(`[ORM] ${Z.name}.delete requires an id as the first argument`);if(!await Y("delete").call($,W))return!1;return await X("delete").call($,J,W).delete(),!0};if(typeof $.findOrFail!=="function")$.findOrFail=async function(W){let B=await Y("findOrFail").call($,W);if(B==null)throw new m3(Z.name,W);return B};if(typeof $.exists!=="function")$.exists=async function(W){if(W==null)return!1;let B=X("exists").call($,J,W);if(typeof B.count==="function"){let L=await B.count();return Number(L)>0}let z=$.find;return typeof z==="function"?await z.call($,W)!=null:!1};if(typeof $.firstOrCreate!=="function")$.firstOrCreate=async function(W,B={}){if(!W||typeof W!=="object"||Array.isArray(W))throw Error(`[ORM] ${Z.name}.firstOrCreate requires a where-attrs object`);let z=X("firstOrCreate").call($,W),L=typeof z.first==="function"?await z.first():await z;if(L)return L;let H={...W,...B};return z8(Z,H),await G("firstOrCreate").call($,H)};if(typeof $.updateOrCreate!=="function")$.updateOrCreate=async function(W,B){if(!W||typeof W!=="object"||Array.isArray(W))throw Error(`[ORM] ${Z.name}.updateOrCreate requires a where-attrs object`);if(!B||typeof B!=="object"||Array.isArray(B))throw Error(`[ORM] ${Z.name}.updateOrCreate requires a values object`);let z=X("updateOrCreate").call($,W),L=typeof z.first==="function"?await z.first():await z;if(L){z8(Z,B);let T=L[J];await X("updateOrCreate").call($,J,T).update(B);let D=$.find;return typeof D==="function"?await D.call($,T):{...L,...B}}let H={...W,...B};return z8(Z,H),await G("updateOrCreate").call($,H)};if(typeof $.count!=="function")$.count=async function(){let W=$;if(typeof W.query==="function"){let L=W.query();if(typeof L?.count==="function"){let H=await L.count();return Number(H)||0}}let{all:B,get:z}=$;if(typeof B==="function")return(await B.call($)||[]).length;if(typeof z==="function")return(await z.call($)||[]).length;return 0};if(typeof $.pluck!=="function")$.pluck=async function(W){if(!W||typeof W!=="string")throw Error(`[ORM] ${Z.name}.pluck requires a column name`);let B=$.all;return((typeof B==="function"?await B.call($):[])||[]).map((L)=>L?.[W])};if(typeof $.whereIn!=="function")$.whereIn=async function(W,B){if(!W||typeof W!=="string")throw Error(`[ORM] ${Z.name}.whereIn requires a column name`);if(!Array.isArray(B))throw Error(`[ORM] ${Z.name}.whereIn requires an array of values`);if(B.length===0)return[];let z=$.where;if(typeof z!=="function")return[];let L=z.call($,W,"in",B);if(L&&typeof L.get==="function")return await L.get();return await L};let V=[["latest","desc"],["oldest","asc"]];for(let[W,B]of V)if(typeof $[W]!=="function")$[W]=async function(z="created_at"){let L=$,H=typeof L.query==="function"?L.query():L;if(typeof H?.orderBy==="function"){let O=H.orderBy(z,B);if(typeof O.first==="function")return await O.first();if(typeof O.get==="function")return(await O.get())?.[0]??null}let T=$.all;if(typeof T!=="function")return null;return[...await T.call($)||[]].sort((O,k)=>{let N=O?.[z],R=k?.[z];if(N===R)return 0;return(N>R?1:-1)*(B==="desc"?-1:1)})[0]??null};let U=u3(Z.traits?.useSearch);if(U){let W=U.index??Z.table??Z$(`${Z.name}s`);if(typeof $.search!=="function")$.search=function(B,z){return kH($,W,B,z)};if(typeof $.makeAllSearchable!=="function")$.makeAllSearchable=async function(B=500){let z=$.all;if(typeof z!=="function")throw Error(`[ORM] ${Z.name}.makeAllSearchable cannot run: the underlying query builder did not expose all()`);let{useSearchEngine:L}=await import("@stacksjs/search-engine"),H=L(),T=0,D=$.query;if(typeof D==="function")try{let k=D.call($);if(k&&typeof k.chunk==="function")return await k.chunk(B,async(N)=>{let R=N.map((M)=>j3(M,U)).filter(Boolean);if(R.length>0)await H.addDocuments(W,R);T+=R.length}),T}catch{}let O=(await z.call($)||[]).map((k)=>j3(k,U)).filter(Boolean);if(O.length>0)await H.addDocuments(W,O);return O.length};if(typeof $.removeAllFromSearch!=="function")$.removeAllFromSearch=async function(){let{useSearchEngine:B}=await import("@stacksjs/search-engine"),z=B();if(typeof z.deleteAllDocuments==="function"){await z.deleteAllDocuments(W);return}let L=$.all,H=typeof L==="function"?await L.call($)||[]:[],T=B();for(let D of H){let q=D?.id??D?._attributes?.id;if(q!=null)await T.deleteDocument(W,Number(q))}}}}function j3($,Z){if(typeof Z.shape==="function")try{return Z.shape($)}catch{return}let J=$?.toSearchableObject?.();if(J!==void 0)return J;return $?._attributes??(typeof $?.toJSON==="function"?$.toJSON():null)}function kH($,Z,J,Q){let X={q:J,...Q??{}},Y={with(G){return X={...X,...G},Y},where(G){return X={...X,filter:G},Y},async get(){let{useSearchEngine:G}=await import("@stacksjs/search-engine");return(await G().search(Z,X))?.hits??[]},async paginate(G,V=1){let{useSearchEngine:U}=await import("@stacksjs/search-engine"),B=await U().search(Z,{...X,limit:G,offset:(V-1)*G});return{hits:B.hits??[],total:Number(B.estimatedTotalHits??B.nbHits??B.total??0),page:V,perPage:G}},async raw(){let{useSearchEngine:G}=await import("@stacksjs/search-engine");return await G().search(Z,X)}};return Y}async function L9($,Z){if(!$||typeof $!=="object")return;let J=$._attributes??$;for(let Q of Z){if(!(Q in J))continue;let X=J[Q];if(!S0(X))continue;J[Q]=await Y$(X)}}function AH($,Z){if(Z.length===0)return;let J=async(G)=>{if(Array.isArray(G)){for(let V of G)await L9(V,Z);return G}if(G&&typeof G==="object"&&Array.isArray(G.data)){for(let V of G.data)await L9(V,Z);return G}if(G)await L9(G,Z);return G},Q=["find","first","last","all","firstOrFail","findOrFail","findMany"];for(let G of Q){let V=$[G];if(typeof V!=="function")continue;$[G]=async function(...U){let W=await V.apply(this,U);return await J(W)}}let X=["create","firstOrCreate","updateOrCreate","make"];for(let G of X){let V=$[G];if(typeof V!=="function")continue;$[G]=async function(...U){let W=await V.apply(this,U);return await J(W)}}let Y=$.update;if(typeof Y==="function")$.update=async function(G,V){let U=await Y.call(this,G,V);return await J(U)}}function NH($,Z){if(Z.length===0)return;let J=async(Y)=>{if(!Y||typeof Y!=="object"||Array.isArray(Y))return Y;let G={...Y};for(let V of Z)if(V in G)G[V]=await X$(G[V]);return G},Q=["create","firstOrCreate","updateOrCreate"];for(let Y of Q){let G=$[Y];if(typeof G!=="function")continue;$[Y]=async function(...V){if(V[0]=await J(V[0]),V[1])V[1]=await J(V[1]);return await G.apply(this,V)}}let X=$.update;if(typeof X==="function")$.update=async function(Y,G){let V=await J(G);return await X.call(this,Y,V)}}function xH($,Z){let J=$.create;if(typeof J==="function")$.create=async function(Q,...X){z8(Z,Q);let Y=await H9(Z,Q);return await J.call(this,Y,...X)};for(let Q of["firstOrCreate","updateOrCreate"]){let X=$[Q];if(typeof X!=="function")continue}}function IH($,Z){let J=["create","firstOrCreate","updateOrCreate"];for(let X of J){let Y=$[X];if(typeof Y==="function")$[X]=async function(...G){if(h.debug(`[orm] ${X.charAt(0).toUpperCase()+X.slice(1)} ${String($.name||"unknown")}`,G[0]),G[0]&&typeof G[0]==="object"&&!Array.isArray(G[0]))G[0]=v3(G[0],Z,"set");return await Y.apply(this,G)}}let Q=$.update;if(typeof Q==="function")$.update=async function(X,Y){let G=Y&&typeof Y==="object"&&!Array.isArray(Y)?v3(Y,Z,"set"):Y;return await Q.call(this,X,G)}}function FF($){h.debug(`[orm] Defining model: ${$.name} (table: ${$.table})`);let Z=PH($),J=RH($),Q=SH(Z,J),X=vH($);$.__traitMethods=X;let Y=Q?{...$,hooks:{...$.hooks,...Q}}:$,G=zH(Y);if(EH(G,$.casts),CH(G,Y),xH(G,Y),$.casts&&Object.keys($.casts).length>0)IH(G,$.casts);let V=G$($);if(V.length>0)NH(G,V),AH(G,V);let U=$.traits?.useSoftDeletes;if(U)yH(G,Y,U);let W=$.traits?.useAudit;if(W){let z=k9(W);A9(G,$.name,$.primaryKey||"id",z)}G.withoutEvents=function(z){return W0(z)};for(let z of["create","update","firstOrCreate","updateOrCreate","forceCreate","forceUpdate","delete","forceDelete","softDelete","restore"]){let L=G[z];if(typeof L!=="function")continue;let H=`${z}Quietly`;if(typeof G[H]==="function")continue;G[H]=function(...T){return W0(()=>L.apply(G,T))}}let B=Object.assign(G,X,{...$,getDefinition:()=>$,_isStacksModel:!0});return LH($.name,B),B}function PH($){let Z=$.traits?.observe;if(!Z)return;let J=$.name.toLowerCase(),Q=(L)=>{let H=L?.attributes;if(!H||typeof H!=="object")return L;let T=$.primaryKey||"id",D={...H};if(D[T]===void 0&&L[T]!==void 0)D[T]=L[T];return D},X=async(L,H)=>{if(U0())return;try{let{dispatch:T}=await import("@stacksjs/events");await T(L,H)}catch(T){if(T&&typeof T==="object"&&"code"in T&&T.code==="MODULE_NOT_FOUND")return;if(console.error(`[ORM] Event '${L}' handler error:`,T),process.env.STACKS_ORM_EVENT_ERRORS!=="swallow")throw T}},Y=$.traits?.broadcastOn,G=$.traits?.broadcastWith,V=typeof Y==="function"&&typeof G==="function",U=async(L,H)=>{if(!V)return;if(U0())return;try{let T=Y(H),D=Array.isArray(T)?T:[T],q=G(H),k=(await import("@stacksjs/realtime").catch(()=>null))?.broadcast;if(typeof k!=="function")return;for(let N of D){if(typeof N!=="string"||N.length===0)continue;await k(N,L,q)}}catch(T){if(T&&typeof T==="object"&&"code"in T&&T.code==="MODULE_NOT_FOUND")return;if(console.error(`[ORM] Broadcast '${L}' handler error:`,T),process.env.STACKS_ORM_BROADCAST_ERRORS==="throw")throw T}},W=async(L,H)=>{if(U0())return!0;try{let{dispatchAsync:T}=await import("@stacksjs/events"),D=await T(L,H);if(Array.isArray(D)&&D.some((q)=>q===!1))return!1}catch(T){if(T&&typeof T==="object"&&"code"in T&&T.code==="MODULE_NOT_FOUND")return!0;if(console.error(`[ORM] Before-event '${L}' handler error:`,T),process.env.STACKS_ORM_EVENT_ERRORS!=="swallow")throw T}return!0},B=Z===!0?["create","update","delete"]:Array.isArray(Z)?Z:[],z={};if(B.includes("create"))z.beforeCreate=async(L)=>{if(h.debug(`[orm] Create ${J}`,L),!await W(`${J}:saving`,L))throw Error(`[ORM] ${J}:saving event cancelled the operation`);if(!await W(`${J}:creating`,L))throw Error(`[ORM] ${J}:creating event cancelled the operation`)},z.afterCreate=async(L)=>{let H=Q(L);await X(`${J}:created`,H),await X(`${J}:saved`,H),await U(`${J}:created`,L)};if(B.includes("update"))z.beforeUpdate=async(L)=>{if(h.debug(`[orm] Update ${J}#${L?.id??"unknown"}`,L),!await W(`${J}:saving`,L))throw Error(`[ORM] ${J}:saving event cancelled the operation`);if(!await W(`${J}:updating`,L))throw Error(`[ORM] ${J}:updating event cancelled the operation`)},z.afterUpdate=async(L)=>{let H=Q(L);await X(`${J}:updated`,H),await X(`${J}:saved`,H),await U(`${J}:updated`,L)};if(B.includes("delete"))z.beforeDelete=async(L)=>{if(h.debug(`[orm] Delete ${J}#${L?.id??"unknown"}`),!await W(`${J}:deleting`,L))throw Error(`[ORM] ${J}:deleting event cancelled the operation`)},z.afterDelete=async(L)=>{await X(`${J}:deleted`,Q(L)),await U(`${J}:deleted`,L)};return z}function SH(...$){let Z={},J=new Set;for(let Q of $){if(!Q)continue;for(let X of Object.keys(Q))J.add(X)}for(let Q of J){let X=$.map((Y)=>Y?.[Q]).filter((Y)=>typeof Y==="function");if(!X.length)continue;Z[Q]=async(...Y)=>{for(let G of X)await G(...Y)}}return Object.keys(Z).length?Z:void 0}function u3($){if(!$)return null;if($===!0)return{};if(typeof $==="object")return $;return null}function RH($){let Z=u3($.traits?.useSearch);if(!Z)return;let J=Z.index??$.table??Z$(`${$.name}s`);function Q(G){if(typeof Z.shape==="function")try{return Z.shape(G)}catch(W){h.warn(`[orm/search] shape() threw for ${$.name}: ${W.message}`);return}let U=m(G).toSearchableObject?.();if(U!==void 0)return U;return G?._attributes??(typeof G?.toJSON==="function"?G.toJSON():null)}let X=async(G)=>{if(U0())return;let V=Q(G);if(!V)return;if(Z.queueable){try{let{Jobs:U}=await import("@stacksjs/queue");await U.dispatch("SyncSearchIndex",{index:J,op:"upsert",doc:V})}catch(U){h.warn(`[orm/search] queue dispatch failed for ${$.name}; falling back to inline: ${U.message}`),await f3(J,V,$.name)}return}await f3(J,V,$.name)};return{afterCreate:X,afterUpdate:X,afterDelete:async(G)=>{if(U0())return;let V=G?.id??G?._attributes?.id;if(V==null)return;if(Z.queueable){try{let{Jobs:U}=await import("@stacksjs/queue");await U.dispatch("SyncSearchIndex",{index:J,op:"delete",id:Number(V)})}catch(U){h.warn(`[orm/search] queue dispatch failed for ${$.name}#${V}; falling back to inline: ${U.message}`),await M3(J,Number(V),$.name)}return}await M3(J,Number(V),$.name)}}}async function f3($,Z,J){try{let{useSearchEngine:Q}=await import("@stacksjs/search-engine");await Q().addDocument($,Z)}catch(Q){h.warn(`[orm/search] Failed to index ${J}: ${Q.message}`)}}async function M3($,Z,J){try{let{useSearchEngine:Q}=await import("@stacksjs/search-engine");await Q().deleteDocument($,Z)}catch(Q){h.warn(`[orm/search] Failed to remove ${J}#${Z}: ${Q.message}`)}}function vH($){let Z={},J=$.table,Q=$.traits;if(!Q)return Z;if(Q.taggable)Z._taggable=f9(J);if(Q.categorizable)Z._categorizable=M9(J);if(Q.commentable)Z._commentable=g9(J);if(Q.billable)Z._billable=N3(J);if(Q.likeable){let Y=typeof Q.likeable==="object"?Q.likeable:void 0;Z._likeable=x3(J,Y)}let X=Q.useAuth||Q.authenticatable;if(typeof X==="object"&&X&&"useTwoFactor"in X&&X.useTwoFactor)Z._twoFactor=I3();return Z}function yH($,Z,J){let Q=P3($,Z.primaryKey||"id"),X=S3(J),Y=Z,G=Z.name.toLowerCase(),V=Z.traits?.observe!=null&&Z.traits?.observe!==!1,U=async(H)=>{if(!V||U0())return!0;try{let{dispatchAsync:T}=await import("@stacksjs/events"),D=await T(`${G}:restoring`,{id:H});if(Array.isArray(D)&&D.some((q)=>q===!1))return!1}catch(T){if(T?.code!=="MODULE_NOT_FOUND")console.error(`[ORM] Before-event '${G}:restoring' handler error:`,T)}return!0},W=async(H)=>{if(!V||U0())return;try{let{dispatch:T}=await import("@stacksjs/events");await T(`${G}:restored`,{id:H})}catch(T){if(T?.code!=="MODULE_NOT_FOUND")console.error(`[ORM] Event '${G}:restored' handler error:`,T)}},B=process.env.STACKS_ORM_CASCADE_SWALLOW!=="true",z=async(H)=>{if(!X.cascade?.length||!B){let D=await Q.softDelete(H);if(D&&X.cascade?.length)await U8(Y,X,H,"softDelete");return D}let{db:T}=await import("@stacksjs/database");return await T.transaction(async()=>{let D=await Q.softDelete(H);if(D)await U8(Y,X,H,"softDelete");return D})},L=async(H)=>{if(!await U(H))return!1;if(!X.cascade?.length||!B){let O=await Q.restore(H);if(O){if(X.cascade?.length)await U8(Y,X,H,"restore");await W(H)}return O}let{db:D}=await import("@stacksjs/database"),q=await D.transaction(async()=>{let O=await Q.restore(H);if(O)await U8(Y,X,H,"restore");return O});if(q)await W(H);return q};$.softDelete=z,$.restore=L,$.forceDelete=Q.forceDelete,$.withTrashed=Q.withTrashed,$.onlyTrashed=Q.onlyTrashed,$.delete=z}function bH($){if($==null)return $;if(Array.isArray($))return $.map(bH);if(typeof $!=="object")return $;if(typeof $.toJSON==="function")return $.toJSON();if($._attributes&&typeof $._attributes==="object")return $._attributes;return $}import{log as jH}from"@stacksjs/logging";import{path as z0}from"@stacksjs/path";import{fs as L8}from"@stacksjs/storage";function L0($){return $.replace(/([A-Z]+)([A-Z][a-z])/g,"$1_$2").replace(/([a-z\d])([A-Z])/g,"$1_$2").replace(/(\d)([A-Za-z])/g,"$1_$2").toLowerCase()}function fH($){let Z=typeof $.type==="string"?$.type.toLowerCase():"",J=(()=>{switch(Z){case"string":case"text":case"longtext":case"mediumtext":case"tinytext":case"char":case"varchar":case"enum":case"uuid":case"date":case"datetime":case"timestamp":case"timestamptz":case"time":case"year":return"string";case"integer":case"int":case"tinyint":case"smallint":case"mediumint":case"float":case"double":case"decimal":case"numeric":return"number";case"bigint":return"number | bigint";case"boolean":case"bool":return"boolean";case"json":case"jsonb":return"unknown";case"binary":case"blob":case"bytea":return"Uint8Array";default:return"unknown"}})();return $.nullable===!0?`${J} | null`:J}function MH($){let Z={},J=$.belongsTo;if(!J)return Z;let Q=Array.isArray(J)?J:Object.keys(J);for(let X of Q)Z[`${L0(X)}_id`]="number";return Z}function _H($,Z){let[J,Q]=[L0($),L0(Z)].sort();return`${J}_${Q}`}function gH($,Z){let J=Z.belongsToMany;if(!J)return[];let Q=[],X=Array.isArray(J)?J:[];for(let Y of X){let G,V,U,W;if(typeof Y==="string")G=Y;else if(Y&&typeof Y==="object"&&"model"in Y){let H=Y;G=H.model,V=H.pivotTable,U=H.firstForeignKey,W=H.secondForeignKey}else continue;let B=V??_H($,G),z=U??`${L0($)}_id`,L=W??`${L0(G)}_id`;Q.push({table:B,columns:{id:"number",[z]:"number",[L]:"number",created_at:"string",updated_at:"string | null"}})}return Q}function hH($){let Z={id:"number"},J=$.traits??{};if(J.useUuid)Z.uuid="string";if((J.useTimestamps??J.timestampable)!==!1)Z.created_at="string",Z.updated_at="string | null";if(J.useSoftDeletes??J.softDeletable)Z.deleted_at="string | null";return Z}function mH($){let Z={},J=$.attributes??{};for(let[Q,X]of Object.entries(J))Z[L0(Q)]=fH(X);return Z}function c3($,Z){let J=Object.entries(Z).map(([Q,X])=>` ${Q}: ${X}`).join(`
|
|
13
|
+
`);return` ${$}: {
|
|
14
|
+
// columns
|
|
15
|
+
${J}
|
|
16
|
+
}`}var n3=`/* eslint-disable */
|
|
17
|
+
// AUTO-GENERATED by \`buddy generate:db-types\` \u2014 do not edit.
|
|
18
|
+
// Regenerate after adding/removing a model or changing its attributes.
|
|
19
|
+
// See stacksjs/stacks#1923.
|
|
20
|
+
|
|
21
|
+
declare module '@stacksjs/database' {
|
|
22
|
+
interface DatabaseSchema {
|
|
23
|
+
`,l3=` }
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export {}
|
|
27
|
+
`;async function p3($,Z){let J=[];if(!L8.existsSync($))return J;let Q=L8.readdirSync($,{withFileTypes:!0});for(let X of Q){let Y=z0.join($,X.name);if(X.isDirectory()){if(Z){let G=await p3(Y,!0);J.push(...G)}continue}if(!X.name.endsWith(".ts"))continue;if(X.name.startsWith("_")||X.name.startsWith("index"))continue;try{let G=await import(Y),V=G.default||G;if(V?.name&&(V.attributes||V.table))J.push({filePath:Y,model:V})}catch{}}return J}async function uH($={}){let Z=$.modelsDir??z0.userModelsPath(),J=$.defaultsDir??z0.frameworkPath("defaults/app/Models"),Q=$.outFile??z0.projectPath("database/types.d.ts"),X=[],Y=[];for(let[z,L]of[[Z,!1],[J,!0]])try{let H=await p3(z,L);Y.push(...H)}catch(H){X.push({file:z,error:H.message})}let G=new Map;for(let z of Y)G.set(z.model.name??z0.basename(z.filePath,".ts"),z);for(let z of Y)if(z.filePath.startsWith(Z))G.set(z.model.name??z0.basename(z.filePath,".ts"),z);let V=[];for(let[z,{model:L}]of G){let H=L.table??`${L0(z)}s`,T={...hH(L),...mH(L),...MH(L)};V.push({table:H,model:z,columns:T})}let U=new Map;for(let[z,{model:L}]of G)for(let H of gH(z,L)){if(U.has(H.table))continue;U.set(H.table,{table:H.table,model:`(${H.table} pivot)`,columns:H.columns})}V.push(...U.values()),V.sort((z,L)=>z.table.localeCompare(L.table));let W=V.map((z)=>c3(z.table,z.columns)).join(`
|
|
28
|
+
`),B=`${n3}${W}
|
|
29
|
+
${l3}`;if(!$.dryRun){let z=z0.dirname(Q);if(!L8.existsSync(z))L8.mkdirSync(z,{recursive:!0});L8.writeFileSync(Q,B,"utf-8"),jH.success(`[generate:db-types] wrote ${V.length} table(s) to ${Q}`)}return{outFile:Q,tables:V,errors:X,content:B}}function cH($){let Z=[...$].sort((J,Q)=>J.table.localeCompare(Q.table)).map((J)=>c3(J.table,J.columns)).join(`
|
|
30
|
+
`);return`${n3}${Z}
|
|
31
|
+
${l3}`}import{configureOrm as nH}from"@stacksjs/query-builder";function lH(){try{let $=process.env.DB_DATABASE_PATH||"database/stacks.sqlite";if((process.env.DB_CONNECTION||"sqlite")==="sqlite")nH({database:$})}catch{}}lH();async function J$($,Z=[""]){let{path:J}=await import("@stacksjs/path"),Q=J.userModelsPath(`${$}.ts`);try{if(await Bun.file(Q).exists())return(await import(Q)).default}catch(X){console.error(`[orm] Failed to import userland model ${$} from ${Q} \u2014 falling back to framework default. Reason:`,X)}for(let X of Z){let Y=X?`${X}/`:"",G=J.frameworkPath(`defaults/app/Models/${Y}${$}.ts`);try{if(await Bun.file(G).exists())return(await import(G)).default}catch(V){console.error(`[orm] Failed to import framework default model ${$} from ${G} \u2014 trying next subdir. Reason:`,V)}}return null}var $0={},d3=()=>{},SF=new Promise(($)=>{d3=$});function F($){return new Proxy(function(){},{get(Z,J){if(J==="then")return;let Q=$0[$];if(Q==null)return;let X=Q[J];return typeof X==="function"?X.bind(Q):X},set(Z,J,Q){let X=$0[$];if(X==null)return!1;return X[J]=Q,!0},has(Z,J){let Q=$0[$];return Q==null?!1:(J in Q)},apply(Z,J,Q){let X=$0[$];if(X==null||typeof X!=="function")return;return X.apply(J,Q)}})}var pH=F("User"),dH=F("Job"),iH=F("FailedJob"),aH=[["Team",[""],"auth"],["Subscriber",[""],"auth"],["SubscriberEmail",[""],"auth"],["Subscription",[""],"auth"],["Post",["Content"],"cms"],["Page",["Content"],"cms"],["Author",["Content"],"cms"],["Comment",[""],"cms"],["Tag",[""],"cms"],["Activity",[""],"dashboard"],["Deployment",[""],"dashboard"],["Release",[""],"dashboard"],["Notification",[""],"dashboard"],["Log",[""],"dashboard"],["Request",[""],"dashboard"],["Error",[""],"monitoring"],["Websocket",["realtime"],"realtime"],["Campaign",[""],"marketing"],["CampaignSend",[""],"marketing"],["EmailList",[""],"marketing"],["EmailListSubscriber",[""],"marketing"],["SocialPost",[""],"marketing"],["PaymentMethod",[""],"commerce"],["PaymentProduct",[""],"commerce"],["PaymentTransaction",[""],"commerce"],["Order",["commerce"],"commerce"],["OrderItem",["commerce"],"commerce"],["Cart",["commerce"],"commerce"],["CartItem",["commerce"],"commerce"],["Customer",["commerce"],"commerce"],["Product",["commerce"],"commerce"],["ProductVariant",["commerce"],"commerce"],["ProductUnit",["commerce"],"commerce"],["Manufacturer",["commerce"],"commerce"],["Category",["commerce"],"commerce"],["Coupon",["commerce"],"commerce"],["GiftCard",["commerce"],"commerce"],["LicenseKey",["commerce"],"commerce"],["Review",["commerce"],"commerce"],["Receipt",["commerce"],"commerce"],["PrintDevice",["commerce"],"commerce"],["ShippingMethod",["commerce"],"commerce"],["ShippingRate",["commerce"],"commerce"],["ShippingZone",["commerce"],"commerce"],["DeliveryRoute",["commerce"],"commerce"],["DigitalDelivery",["commerce"],"commerce"],["Driver",["commerce"],"commerce"],["TaxRate",["commerce"],"commerce"],["WaitlistProduct",["commerce"],"commerce"],["WaitlistRestaurant",["commerce"],"commerce"],["LoyaltyPoint",["commerce"],"commerce"],["LoyaltyReward",["commerce"],"commerce"],["Payment",["commerce"],"commerce"],["Transaction",["commerce"],"commerce"]];queueMicrotask(async()=>{try{let{feature:$}=await import("@stacksjs/config"),Z=await J$("User");if(Z)$0.User=Z;if($("queue")){let J=await J$("Job");if(J)$0.Job=J;let Q=await J$("FailedJob");if(Q)$0.FailedJob=Q}for(let[J,Q,X]of aH){if(!$(X))continue;let Y=await J$(J,Q);if(Y)$0[J]=Y}}catch($){console.error("[orm] deferred model load failed:",$)}finally{d3()}});var oH=F("Activity"),sH=F("Author"),rH=F("Campaign"),tH=F("Cart"),eH=F("CartItem"),$w=F("Category"),Zw=F("Comment"),Jw=F("Coupon"),Qw=F("Customer"),Xw=F("DeliveryRoute"),Yw=F("Deployment"),Gw=F("DigitalDelivery"),Vw=F("Driver"),Bw=F("CampaignSend"),Ww=F("EmailList"),Uw=F("EmailListSubscriber"),zw=F("Error"),Lw=F("GiftCard"),Kw=F("LicenseKey"),Hw=F("Log"),ww=F("LoyaltyPoint"),Tw=F("LoyaltyReward"),Dw=F("Manufacturer"),Ow=F("Notification"),qw=F("Order"),Ew=F("OrderItem"),Fw=F("Page"),Cw=F("Payment"),kw=F("PaymentMethod"),Aw=F("PaymentProduct"),Nw=F("PaymentTransaction"),xw=F("Post"),Iw=F("PrintDevice"),Pw=F("Product"),Sw=F("ProductUnit"),Rw=F("ProductVariant"),vw=F("Receipt"),yw=F("Release"),bw=F("Request"),jw=F("Review"),fw=F("ShippingMethod"),Mw=F("ShippingRate"),_w=F("ShippingZone"),gw=F("SocialPost"),hw=F("Subscriber"),mw=F("SubscriberEmail"),uw=F("Subscription"),cw=F("Tag"),nw=F("TaxRate"),lw=F("Team"),pw=F("Transaction"),dw=F("WaitlistProduct"),iw=F("WaitlistRestaurant"),aw=F("Websocket"),ow={User:pH,Job:dH,FailedJob:iH,Activity:oH,Author:sH,Campaign:rH,CampaignSend:Bw,Cart:tH,CartItem:eH,Category:$w,Comment:Zw,Coupon:Jw,Customer:Qw,DeliveryRoute:Xw,Deployment:Yw,DigitalDelivery:Gw,Driver:Vw,EmailList:Ww,EmailListSubscriber:Uw,ErrorModel:zw,GiftCard:Lw,LicenseKey:Kw,Log:Hw,LoyaltyPoint:ww,LoyaltyReward:Tw,Manufacturer:Dw,Notification:Ow,Order:qw,OrderItem:Ew,Page:Fw,Payment:Cw,PaymentMethod:kw,PaymentProduct:Aw,PaymentTransaction:Nw,Post:xw,PrintDevice:Iw,Product:Pw,ProductUnit:Sw,ProductVariant:Rw,Receipt:vw,Release:yw,Request:bw,Review:jw,ShippingMethod:fw,ShippingRate:Mw,ShippingZone:_w,SocialPost:gw,Subscriber:hw,SubscriberEmail:mw,Subscription:uw,Tag:cw,TaxRate:nw,Team:lw,Transaction:pw,WaitlistProduct:dw,WaitlistRestaurant:iw,Websocket:aw},I0=globalThis;for(let[$,Z]of Object.entries(ow))if(Z&&I0[$]===void 0)I0[$]=Z;async function sw($){if(!$)return[];try{if(typeof $.all==="function"){let Z=await $.all();return Array.isArray(Z)?Z:[]}if(typeof $.get==="function"){let Z=await $.get();return Array.isArray(Z)?Z:[]}}catch{}return[]}function rw($,Z,J=""){if(!$)return J;try{if(typeof $.get==="function"){let X=$.get(Z);if(X!==void 0&&X!==null)return X}}catch{}let Q=$?.[Z];return Q!==void 0&&Q!==null?Q:J}if(I0.safeAll===void 0)I0.safeAll=sw;if(I0.safeGet===void 0)I0.safeGet=rw;export{W0 as withoutEvents,FT as transactional,qT as transactionBuilder,OT as transaction,cT as toTimestamp,T$ as toSimplePaginator,w$ as toPaginator,D$ as toCursorPaginator,bH as toAttrs,WB as setAuditUser,ET as savepoint,q$ as resolvePageArgs,E$ as resolveCursorArgs,cH as renderDatabaseTypeFile,JB as prunable,b9 as parseCursor,SF as ormReady,IT as modelTableName,ZT as massPrunable,zB as mapWriteError,_T as mapEntity,N9 as isUniqueViolation,FB as isSimplePaginator,EB as isPaginator,S0 as isEncrypted,CB as isCursorPaginator,PT as hasRelations,u as getTableName,TB as getRelations,ST as getRelationType,RT as getRelationCount,JT as getPrunableConfig,vT as getPivotTables,wB as getPivotTableName,y0 as getModelName,bT as getHiddenAttributes,jT as getGuardedAttributes,fT as getFillableAttributes,mT as formatDate,K$ as findUserModel,L$ as findCoreModel,yT as fetchOtherModelRelations,gT as extractImports,MT as extractFields,uT as extractDate,hT as extractAttributesFromModel,F$ as enrichPaginatorUrls,X$ as encryptValue,FF as defineModel,Y$ as decryptValue,wT as db,C9 as createAuditMethods,G$ as collectEncryptedAttributes,uH as buildDatabaseSchema,zT as batchLoad,aw as Websocket,iw as WaitlistRestaurant,dw as WaitlistProduct,pH as User,pw as Transaction,lw as Team,nw as TaxRate,cw as Tag,uw as Subscription,mw as SubscriberEmail,hw as Subscriber,KB as SubqueryBuilder,gw as SocialPost,_w as ShippingZone,Mw as ShippingRate,fw as ShippingMethod,jw as Review,bw as Request,yw as Release,vw as Receipt,Rw as ProductVariant,Sw as ProductUnit,Pw as Product,Iw as PrintDevice,xw as Post,Nw as PaymentTransaction,Aw as PaymentProduct,kw as PaymentMethod,Cw as Payment,Fw as Page,Ew as OrderItem,qw as Order,Ow as Notification,m3 as ModelNotFoundError,K9 as MassAssignmentException,Dw as Manufacturer,Tw as LoyaltyReward,ww as LoyaltyPoint,Hw as Log,Kw as LicenseKey,dH as Job,Lw as GiftCard,iH as FailedJob,zw as ErrorModel,Uw as EmailListSubscriber,Ww as EmailList,Vw as Driver,Gw as DigitalDelivery,Yw as Deployment,Xw as DeliveryRoute,Qw as Customer,Jw as Coupon,Zw as Comment,$w as Category,eH as CartItem,tH as Cart,Bw as CampaignSend,rH as Campaign,sH as Author,oH as Activity};
|