trigger_system 1.0.2 → 1.0.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/browser/index.browser.js +23 -23
- package/dist/browser/index.browser.js.map +14 -14
- package/dist/core/base-engine.d.ts +3 -3
- package/dist/core/base-engine.d.ts.map +1 -1
- package/dist/core/context-adapter.d.ts +8 -4
- package/dist/core/context-adapter.d.ts.map +1 -1
- package/dist/core/dependency-graph.d.ts.map +1 -1
- package/dist/core/engine.d.ts +2 -2
- package/dist/core/engine.d.ts.map +1 -1
- package/dist/core/expression-engine.d.ts +2 -2
- package/dist/core/expression-engine.d.ts.map +1 -1
- package/dist/core/persistence.d.ts +4 -4
- package/dist/core/persistence.d.ts.map +1 -1
- package/dist/core/rule-engine-new.d.ts +5 -4
- package/dist/core/rule-engine-new.d.ts.map +1 -1
- package/dist/core/rule-engine.d.ts +1 -1
- package/dist/core/rule-engine.d.ts.map +1 -1
- package/dist/core/state-manager.d.ts +3 -3
- package/dist/core/state-manager.d.ts.map +1 -1
- package/dist/core/trigger-engine.d.ts +10 -7
- package/dist/core/trigger-engine.d.ts.map +1 -1
- package/dist/domain/validator.d.ts +1 -1
- package/dist/domain/validator.d.ts.map +1 -1
- package/dist/index.browser.d.ts +1 -1
- package/dist/index.browser.d.ts.map +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/lsp/completions.d.ts.map +1 -1
- package/dist/lsp/data-context.d.ts +4 -4
- package/dist/lsp/data-context.d.ts.map +1 -1
- package/dist/node/index.js +107 -107
- package/dist/node/index.js.map +15 -15
- package/dist/node/node.js +103 -103
- package/dist/node/node.js.map +16 -16
- package/dist/sdk/builder.d.ts +5 -5
- package/dist/sdk/builder.d.ts.map +1 -1
- package/dist/types.d.ts +47 -17
- package/dist/types.d.ts.map +1 -1
- package/dist/utils/emitter.d.ts +9 -3
- package/dist/utils/emitter.d.ts.map +1 -1
- package/dist/utils/utils.d.ts +3 -3
- package/dist/utils/utils.d.ts.map +1 -1
- package/package.json +1 -1
|
@@ -1,48 +1,48 @@
|
|
|
1
|
-
var ZU=Object.defineProperty;var WU=(Q,X)=>{for(var Y in X)ZU(Q,Y,{get:X[Y],enumerable:!0,configurable:!0,set:(U)=>X[Y]=()=>U})};var gQ=(Q,X)=>()=>(Q&&(X=Q(Q=0)),X);class i{static evaluate(Q,X){try{if(Q.includes("${")){let Y=this.interpolate(Q,X);if(!isNaN(Number(Y))&&Y.trim()!=="")return Number(Y);return Y}return this.evaluateExpression(Q,X)}catch(Y){return console.error(`Error evaluating expression: ${Q}`,Y),null}}static interpolate(Q,X){return Q.replace(/\$\{([^}]+)\}/g,(Y,U)=>{try{let Z=this.evaluateExpression(U,X);if(Z===void 0||Z===null)return"undefined";return String(Z)}catch(Z){return console.error(`Error en interpolación: ${Y}`,Z),Y}})}static evaluateMathExpression(Q){try{return Function("Math",`return ${Q}`)(Math)}catch(X){throw Error(`Error evaluando expresión matemática: ${Q}`)}}static evaluateExpression(Q,X){if(/^(data|globals|request|computed)(\.[a-zA-Z0-9_]+)+$/.test(Q))return this.getNestedValue(Q,X);try{return Function("context","with(context) { return "+Q+" }")(X)}catch(Y){return console.error(`ERROR evaluating expression '${Q}':`,Y),Q}}static getNestedValue(Q,X){let Y=Q.split("."),U=X;for(let Z of Y){if(U===null||U===void 0||!(Z in U))return;U=U[Z]}return U}static evaluateMath(Q,X){let Y=Q;Y=Y.replace(/\b[a-zA-Z_][a-zA-Z0-9_]*\b/g,(U)=>{if(["Math","random","floor","ceil","round","sqrt","abs","pow","min","max","sin","cos","tan"].includes(U))return U;let Z=this.getNestedValue(U,X);if(Z!==void 0)return typeof Z==="string"?`"${Z}"`:String(Z);return U});try{return this.evaluateMathExpression(Y)}catch(U){return console.error(`Error en evaluación matemática: ${Q}`,U),NaN}}}class V6{store=new Map;async loadState(){return new Map(this.store)}async saveState(Q,X){this.store.set(Q,X)}async deleteState(Q){this.store.delete(Q)}async clearState(){this.store.clear()}}class Q1{static instance;state;persistence;constructor(){this.state=new Map,this.persistence=new V6}static getInstance(){if(!Q1.instance)Q1.instance=new Q1;return Q1.instance}setPersistence(Q){this.persistence=Q}async initialize(){let Q=await this.persistence.loadState();this.state=Q,console.log(`[StateManager] Initialized with ${this.state.size} keys.`)}get(Q){return this.state.get(Q)}async set(Q,X){this.state.set(Q,X),await this.persistence.saveState(Q,X)}async increment(Q,X=1){let Y=this.get(Q)||0,U=Number(Y)+X;return await this.set(Q,U),U}async decrement(Q,X=1){return this.increment(Q,-X)}async delete(Q){let X=this.state.delete(Q);if(X)await this.persistence.deleteState(Q);return X}async clear(){this.state.clear(),await this.persistence.clearState()}getAll(){return Object.fromEntries(this.state)}}var U2=()=>{};var hQ={};WU(hQ,{ActionRegistry:()=>v1});class v1{static instance;handlers=new Map;constructor(){this.registerDefaults()}static getInstance(){if(!this.instance)this.instance=new v1;return this.instance}register(Q,X){this.handlers.set(Q.toUpperCase(),X)}get(Q){return this.handlers.get(Q.toUpperCase())}registerDefaults(){this.register("log",(Q,X)=>{let Y=Q.params?.message||Q.params?.content||"Log Trigger",U=i.interpolate(Y,X);return console.log(`[TriggerLog] ${U}`),{message:U}}),this.register("response",(Q,X)=>{let Y=Q.params?.content||Q.params?.body||"",U=i.interpolate(Y,X);return{statusCode:Q.params?.statusCode||200,headers:Q.params?.headers||{"Content-Type":"application/json"},body:U}}),this.register("execute",async(Q,X)=>{let Y=Q.params?.command||Q.params?.content||"",U=i.interpolate(Y,X);if(!Q.params?.safe)console.warn(`[Trigger] Ejecutando comando no seguro: ${U}`);try{let Z=Bun.spawn(U.split(" "),{stdout:"pipe",stderr:"pipe"}),[W,G]=await Promise.all([new Response(Z.stdout).text(),new Response(Z.stderr).text()]);return{command:U,stdout:W,stderr:G,exitCode:await Z.exited}}catch(Z){return{command:U,error:String(Z)}}}),this.register("forward",async(Q,X)=>{let Y=Q.params?.url||"",U=i.interpolate(Y,X),Z=Q.params?.method||"POST";try{let W=await fetch(U,{method:Z,headers:{"Content-Type":"application/json",...Q.params?.headers},body:JSON.stringify(X.data)});return{url:U,method:Z,status:W.status,headers:(()=>{let G={};return W.headers.forEach((_,H)=>G[H]=_),G})(),body:await W.text()}}catch(W){return{url:U,method:Z,error:String(W)}}}),this.register("STATE_SET",async(Q,X)=>{let Y=Q.params?.key,U=Q.params?.value;if(!Y)return{error:"Missing key for STATE_SET"};let Z=U;if(typeof U==="string"&&U.includes("${"))Z=i.interpolate(U,X);return await Q1.getInstance().set(Y,Z),{key:Y,value:Z}}),this.register("STATE_INCREMENT",async(Q,X)=>{let Y=Q.params?.key,U=Number(Q.params?.amount)||1;if(!Y)return{error:"Missing key for STATE_INCREMENT"};let Z=await Q1.getInstance().increment(Y,U);return{key:Y,newValue:Z}}),this.register("EMIT_EVENT",(Q,X)=>{return{event:Q.params?.event,payload:Q.params?.data||{}}})}}var Z2=gQ(()=>{U2()});class GU{queue=[];engine;config;timer=null;isProcessing=!1;constructor(Q,X={maxBatchSize:10,flushIntervalMs:100}){this.engine=Q,this.config=X}push(Q){if(this.queue.push(Q),this.queue.length>=this.config.maxBatchSize)this.processQueue();else if(!this.timer)this.timer=setTimeout(()=>this.processQueue(),this.config.flushIntervalMs)}async processQueue(){if(this.isProcessing)return;if(this.isProcessing=!0,this.timer)clearTimeout(this.timer),this.timer=null;let Q=this.queue.splice(0,this.config.maxBatchSize);if(Q.length===0){this.isProcessing=!1;return}console.debug(`[EventQueue] Processing batch of ${Q.length} events.`);for(let X of Q)try{await this.engine.evaluateContext(X)}catch(Y){console.error(`[EventQueue] Error processing event ${X.event}:`,Y)}if(this.queue.length>0)setTimeout(()=>this.processQueue(),0);this.isProcessing=!1}getQueueLength(){return this.queue.length}}class xQ{keyPrefix;cache=new Map;isLoaded=!1;constructor(Q="trigger_system:"){this.keyPrefix=Q}isAvailable(){return typeof window<"u"&&typeof window.localStorage<"u"}ensureLoaded(){if(this.isLoaded)return;if(this.isAvailable())try{let Q=window.localStorage.getItem(this.keyPrefix+"state");if(Q){let X=JSON.parse(Q);this.cache=new Map(Object.entries(X))}}catch(Q){console.error("[BrowserPersistence] Failed to load from localStorage:",Q)}this.isLoaded=!0}persist(){if(this.isAvailable())try{let Q=Object.fromEntries(this.cache);window.localStorage.setItem(this.keyPrefix+"state",JSON.stringify(Q))}catch(Q){console.error("[BrowserPersistence] Failed to save to localStorage:",Q)}}async loadState(){return this.ensureLoaded(),new Map(this.cache)}async saveState(Q,X){this.ensureLoaded(),this.cache.set(Q,X),this.persist()}async deleteState(Q){this.ensureLoaded(),this.cache.delete(Q),this.persist()}async clearState(){this.cache.clear(),this.persist()}}class Y2{static getNestedValue(Q,X){let Y=Q.split("."),U=X;for(let Z of Y){if(U===null||U===void 0)return;U=U[Z]}return U}static interpolate(Q,X){if(typeof Q!=="string")return Q;return Q.replace(/\$\{([^}]+)\}/g,(Y,U)=>{let Z=this.getNestedValue(U,X);if(Z!==void 0)return String(Z);return Y})}static compare(Q,X,Y){switch(X){case"EQ":case"==":return Q==Y;case"NEQ":case"!=":return Q!=Y;case"GT":case">":return Number(Q)>Number(Y);case"GTE":case">=":return Number(Q)>=Number(Y);case"LT":case"<":return Number(Q)<Number(Y);case"LTE":case"<=":return Number(Q)<=Number(Y);case"IN":return Array.isArray(Y)&&Y.includes(Q);case"NOT_IN":return Array.isArray(Y)&&!Y.includes(Q);case"CONTAINS":if(Array.isArray(Q)||typeof Q==="string")return Q.includes(Y);return!1;case"MATCHES":return new RegExp(Y).test(String(Q));case"RANGE":if(Array.isArray(Y)&&Y.length===2){let U=Number(Q);return U>=Y[0]&&U<=Y[1]}return!1;default:return console.warn(`Unknown operator: ${X}`),!1}}}class W2{_rules=[];actionHandlers=new Map;lastExecution=new Map;_config;constructor(Q=[]){if(Array.isArray(Q))this._rules=Q;else this._config=Q,this._rules=[...Q.rules];this.sortRules()}sortRules(){this._rules.sort((Q,X)=>(X.priority||0)-(Q.priority||0))}registerAction(Q,X){this.actionHandlers.set(Q,X)}async processEvent(Q){let X=[],Y=this._rules.filter((U)=>U.enabled!==!1&&U.on===Q.event);for(let U of Y){if(U.cooldown&&this.checkCooldown(U.id,U.cooldown))continue;if(this.evaluateConditions(U.if,Q)){let Z=await this.executeRuleActions(U.do,Q);if(this.lastExecution.set(U.id,Date.now()),X.push({ruleId:U.id,success:!0,executedActions:Z}),!this.shouldEvaluateAll())break}}return X}async processEventSimple(Q,X={},Y={}){let U={event:Q,data:X,globals:Y,timestamp:Date.now(),state:this.getStateContext?this.getStateContext():{}};return this.processEvent(U)}updateRules(Q){this.rules=[...Q],this.sortRules()}getRules(){return[...this.rules]}checkCooldown(Q,X){let Y=this.lastExecution.get(Q);if(!Y)return!1;return Date.now()-Y<X}shouldEvaluateAll(){return this.config?.globalSettings?.evaluateAll??!0}getStateContext(){return{}}evaluateConditions(Q,X){if(!Q)return!0;if(Array.isArray(Q))return Q.every((Y)=>this.evaluateSingleCondition(Y,X));return this.evaluateSingleCondition(Q,X)}evaluateSingleCondition(Q,X){if("operator"in Q&&"conditions"in Q){let W=Q;if(W.operator==="OR")return W.conditions.some((G)=>this.evaluateSingleCondition(G,X));else return W.conditions.every((G)=>this.evaluateSingleCondition(G,X))}let Y=Q,U=Y2.getNestedValue(Y.field,X),Z=Y.value;if(typeof Z==="string"&&Z.includes("${"))Z=i.interpolate(Z,X);return Y2.compare(U,Y.operator,Z)}async executeRuleActions(Q,X){let Y=[],U=[],Z="ALL";if(Array.isArray(Q))U=Q;else if("mode"in Q&&"actions"in Q){let W=Q;Z=W.mode,U=W.actions}else U=[Q];if(Z==="EITHER"&&U.length>0){let W=U.reduce((H,J)=>H+(J.probability||1),0),G=Math.random()*W,_;for(let H of U){let J=H.probability||1;if(G-=J,G<=0){_=H;break}}if(!_&&U.length>0)_=U[U.length-1];if(_)U=[_];else U=[]}for(let W of U){let G=await this.executeSingleAction(W,X);Y.push(G)}return Y}async executeSingleAction(Q,X){if(Q.probability!==void 0&&Math.random()>Q.probability)return{type:Q.type,timestamp:Date.now(),result:{skipped:"probability check failed"}};if(Q.delay&&Q.delay>0)await new Promise((Y)=>setTimeout(Y,Q.delay));try{let Y;try{let{ActionRegistry:Z}=await Promise.resolve().then(() => (Z2(),hQ));Y=Z.getInstance().get(Q.type)}catch{Y=this.actionHandlers.get(Q.type)}let U;if(Y)U=await Y(Q.params||{},X);else{let Z=`No handler registered for action type: ${Q.type}`;console.warn(Z),U={warning:Z}}return{type:Q.type,result:U,timestamp:Date.now()}}catch(Y){return console.error(`Error executing action ${Q.type}:`,Y),{type:Q.type,error:String(Y),timestamp:Date.now()}}}interpolateParams(Q,X){let Y={};for(let[U,Z]of Object.entries(Q))if(typeof Z==="string")Y[U]=i.interpolate(Z,X);else if(typeof Z==="object"&&Z!==null)Y[U]=this.interpolateDeep(Z,X);else Y[U]=Z;return Y}interpolateDeep(Q,X){if(typeof Q==="string")return i.interpolate(Q,X);if(Array.isArray(Q))return Q.map((Y)=>this.interpolateDeep(Y,X));if(typeof Q==="object"&&Q!==null){let Y={};for(let U in Q)Y[U]=this.interpolateDeep(Q[U],X);return Y}return Q}get rules(){return[...this._rules]}get config(){return this._config}set rules(Q){this._rules=[...Q],this.sortRules()}}Z2();U2();class T6{static instance;handlers=new Map;constructor(){}static getInstance(){if(!this.instance)this.instance=new T6;return this.instance}on(Q,X){let Y=Q;if(!this.handlers.has(Y))this.handlers.set(Y,new Set);return this.handlers.get(Y).add(X),()=>this.off(Y,X)}off(Q,X){let Y=Q,U=this.handlers.get(Y);if(U)U.delete(X)}emit(Q,X){let Y=Q,U=this.handlers.get(Y);if(U)U.forEach((Z)=>{try{Z(X)}catch(W){console.error(`Error in event handler for ${Y}:`,W)}})}}var K1=T6.getInstance();class B6 extends W2{actionRegistry;stateManager;constructor(Q){super(Q);this.actionRegistry=v1.getInstance(),this.stateManager=Q1.getInstance()}async processEvent(Q){let X=[];if(Q.state=this.stateManager.getAll(),K1.emit("engine:start",{context:Q,rulesCount:this.rules.length}),this.config?.globalSettings?.debugMode)console.log(`[RuleEngine] Evaluating context with ${this.rules.length} rules for event: ${Q.event}`);let Y=this.rules.filter((U)=>U.enabled!==!1&&U.on===Q.event);for(let U of Y){if(U.cooldown&&this.checkCooldown(U.id,U.cooldown)){if(this.config?.globalSettings?.debugMode)console.log(`[RuleEngine] Rule ${U.id} in cooldown`);continue}if(this.evaluateConditions(U.if,Q)){if(this.config?.globalSettings?.debugMode)console.log(`[RuleEngine] Executing rule: ${U.name||U.id}`);K1.emit("rule:match",{rule:U,context:Q});let W=await this.executeRuleActionsWithRegistry(U.do,Q);if(X.push({ruleId:U.id,executedActions:W,success:!0}),this.updateLastExecution(U.id),!this.shouldEvaluateAll())break}}return K1.emit("engine:done",{results:X,context:Q}),X}async processEventSimple(Q,X={},Y={}){let U={event:Q,data:X,globals:Y,timestamp:Date.now(),state:this.stateManager.getAll()};return this.processEvent(U)}async executeRuleActionsWithRegistry(Q,X){let Y=[],U=[],Z="ALL";if(Array.isArray(Q))U=Q;else if(Q.mode&&Q.actions){let W=Q;Z=W.mode,U=W.actions}else U=[Q];if(Z==="EITHER"&&U.length>0){let W=Math.floor(Math.random()*U.length),G=U[W];if(G)U=[G]}if(Z==="SEQUENCE")for(let W of U){let G=await this.executeSingleActionWithRegistry(W,X);Y.push(G)}else for(let W of U){let G=await this.executeSingleActionWithRegistry(W,X);Y.push(G)}return Y}async executeSingleActionWithRegistry(Q,X){if(Q.probability!==void 0&&Math.random()>Q.probability)return{type:Q.type,timestamp:Date.now(),result:{skipped:"probability check failed"}};if(Q.delay&&Q.delay>0)await new Promise((Y)=>setTimeout(Y,Q.delay));try{let Y=this.actionRegistry.get(Q.type),U;if(Y)U=await Y(Q,X);else{let Z=`Generic or unknown action type: ${Q.type}`;if(this.config?.globalSettings?.strictActions)throw Error(Z);console.warn(Z),U={warning:`Generic action executed: ${Q.type}`}}return K1.emit("action:success",{action:Q,context:X,result:U}),{type:Q.type,result:U,timestamp:Date.now()}}catch(Y){return console.error("Error executing action:",Q,Y),K1.emit("action:error",{action:Q,context:X,error:String(Y)}),{type:Q.type,error:String(Y),timestamp:Date.now()}}}updateLastExecution(Q){this.lastExecution.set(Q,Date.now())}getStateContext(){return this.stateManager.getAll()}shouldEvaluateAll(){return this.config?.globalSettings?.evaluateAll??!0}async executeRuleActions(Q,X){return this.executeRuleActionsWithRegistry(Q,X)}async executeSingleAction(Q,X){return this.executeSingleActionWithRegistry(Q,X)}}Z2();class JU{static create(Q,X,Y={}){return{event:Q,timestamp:Date.now(),data:typeof X==="object"?X:{value:X},globals:Y,helpers:this.getDefaultHelpers()}}static fromRequest(Q,X,Y={}){let U=new URL(Q.url);return{event:"HTTP_REQUEST",timestamp:Date.now(),data:{method:Q.method,path:U.pathname,query:Object.fromEntries(U.searchParams),headers:(()=>{let Z={};return Q.headers.forEach((W,G)=>Z[G]=W),Z})(),body:X||{}},globals:{...Y,ip:Q.headers.get("x-forwarded-for")||"unknown"},helpers:this.getDefaultHelpers()}}static fromWebhook(Q,X,Y,U={}){return{event:`WEBHOOK_${Q.toUpperCase()}_${X.toUpperCase()}`,timestamp:Date.now(),data:Y,globals:{...U,provider:Q},helpers:this.getDefaultHelpers()}}static getDefaultHelpers(){return{now:()=>Date.now(),uuid:()=>crypto.randomUUID(),jsonParse:(Q)=>JSON.parse(Q),jsonStringify:(Q)=>JSON.stringify(Q)}}}U2();Z2();U2();var V1=(Q)=>Array.isArray(Q)?Q:[Q],pQ=(Q,X)=>{let Y=[[],[]];for(let U of Q)if(X(U))Y[0].push(U);else Y[1].push(U);return Y},k2=Array,n=(Q,X)=>Q.includes(X),uQ=(Q,X=0)=>[...Array(Q)].map((Y,U)=>U+X),R=(Q,X,Y)=>{if(Q===void 0)return X===void 0?[]:Array.isArray(X)?X:[X];if(Y?.prepend)if(Array.isArray(X))Q.unshift(...X);else Q.unshift(X);else if(Array.isArray(X))Q.push(...X);else Q.push(X);return Q},F1=(Q,X)=>{if(X===void 0||X===null)return Q??[];if(Q===void 0||Q===null)return V1(X);return Q.concat(X)},mQ=(...Q)=>Q.reduce(F1,[]),G1=(Q,X,Y)=>{if(Q===void 0)return Array.isArray(X)?X:[X];let U=Y?.isEqual??((Z,W)=>Z===W);for(let Z of V1(X))if(!Q.some((W)=>U(W,Z)))Q.push(Z);return Q},lQ=(Q,X)=>Q.reduce((Y,U)=>{let Z=U[X];return Y[Z]=R(Y[Z],U),Y},{}),q1=(Q,X,Y)=>Q.length===X.length&&Q.every(Y?.isEqual?(U,Z)=>Y.isEqual(U,X[Z]):(U,Z)=>U===X[Z]);var p=(Q,X)=>y(Q)===X,y=(Q)=>{let X=typeof Q;return X==="object"?Q===null?"null":"object":X==="function"?"object":X},u={boolean:"boolean",null:"null",undefined:"undefined",bigint:"a bigint",number:"a number",object:"an object",string:"a string",symbol:"a symbol"},dQ={...u,function:"a function"};class cQ extends Error{}var C=(Q)=>N1(Q,cQ),N1=(Q,X=Error)=>{throw new X(Q)};class G2 extends Error{name="ParseError"}var L=(Q)=>N1(Q,G2),X1=(Q)=>` ${Q}`,oQ="";var V=(Q,X)=>{let Y={},U=Array.isArray(Q),Z=!1;for(let[W,G]of Object.entries(Q).entries()){let _=U?X(W,G[1]):X(...G,W);Z||=typeof _[0]==="number";let H=Array.isArray(_[0])||_.length===0?_:[_];for(let[J,$]of H)if(typeof J==="object")Y[J.group]=R(Y[J.group],$);else Y[J]=$}return Z?Object.values(Y):Y};var M6=Object.entries;var f=(Q,X)=>(Q in X),k1=(Q,X)=>(X in Q);class R6{constructor(Q){Object.assign(this,Q)}}var iQ=class{};class _2 extends iQ{}var LU=(Q,X)=>{let Y={},U={},Z;for(Z in Q)if(Z in X)Y[Z]=Q[Z];else U[Z]=Q[Z];return[Y,U]};var g2=(Q,X)=>LU(Q,X)[1],_1=(Q)=>Object.keys(Q).length===0,P1=(Q)=>[...Object.entries(Q),...Object.getOwnPropertySymbols(Q).map((X)=>[X,Q[X]])],sQ=(Q,X)=>Object.defineProperties(Q,Object.getOwnPropertyDescriptors(X)),nQ=(Q)=>{let X=Object.keys(Q).sort(),Y={};for(let U=0;U<X.length;U++)Y[X[U]]=Q[X[U]];return Y};var m=X1(`unset${oQ}`),rQ=(Q)=>Object.values(Q).filter((X)=>{if(typeof X==="number")return!0;return typeof Q[X]!=="number"});var D6={Array,Boolean,Date,Error,Function,Map,Number,Promise,RegExp,Set,String,WeakMap,WeakSet},C6=globalThis.File??Blob,w6={ArrayBuffer,Blob,File:C6,FormData,Headers,Request,Response,URL},HU={Int8Array,Uint8Array,Uint8ClampedArray,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array},E1={...D6,...w6,...HU,String,Number,Boolean},J2=(Q)=>{let X=Object.getPrototypeOf(Q);while(X?.constructor&&(!f(X.constructor.name,E1)||!(Q instanceof E1[X.constructor.name])))X=Object.getPrototypeOf(X);let Y=X?.constructor?.name;if(Y===void 0||Y==="Object")return;return Y},L2=(Q)=>typeof Q==="object"&&Q!==null?J2(Q)??"object":y(Q);var K=Array.isArray,FU={Array:"an array",Function:"a function",Date:"a Date",RegExp:"a RegExp",Error:"an Error",Map:"a Map",Set:"a Set",String:"a String object",Number:"a Number object",Boolean:"a Boolean object",Promise:"a Promise",WeakMap:"a WeakMap",WeakSet:"a WeakSet"},qU={ArrayBuffer:"an ArrayBuffer instance",Blob:"a Blob instance",File:"a File instance",FormData:"a FormData instance",Headers:"a Headers instance",Request:"a Request instance",Response:"a Response instance",URL:"a URL instance"},$U={Int8Array:"an Int8Array",Uint8Array:"a Uint8Array",Uint8ClampedArray:"a Uint8ClampedArray",Int16Array:"an Int16Array",Uint16Array:"a Uint16Array",Int32Array:"an Int32Array",Uint32Array:"a Uint32Array",Float32Array:"a Float32Array",Float64Array:"a Float64Array",BigInt64Array:"a BigInt64Array",BigUint64Array:"a BigUint64Array"},tQ={...FU,...qU,...$U},H2=(Q)=>{let X=Object(Q).name??null;return X&&f(X,E1)&&E1[X]===Q?X:null};var K6=(Q,X)=>{let Y=Q.prototype;while(Y!==null){if(Y===X.prototype)return!0;Y=Object.getPrototypeOf(Y)}return!1};var aQ=(Q)=>eQ(Q,new Map),eQ=(Q,X)=>{if(typeof Q!=="object"||Q===null)return Q;if(X?.has(Q))return X.get(Q);let Y=H2(Q.constructor);if(Y==="Date")return new Date(Q.getTime());if(Y&&Y!=="Array")return Q;let U=Array.isArray(Q)?Q.slice():Object.create(Object.getPrototypeOf(Q)),Z=Object.getOwnPropertyDescriptors(Q);if(X){X.set(Q,U);for(let W in Z){let G=Z[W];if("get"in G||"set"in G)continue;G.value=eQ(G.value,X)}}return Object.defineProperties(U,Z),U};var AU=(Q)=>{let X=m;return()=>X===m?X=Q():X},T1=(Q)=>typeof Q==="function"&&Q.length===0;var Q4=class extends Function{constructor(...Q){let X=Q.slice(0,-1),Y=Q[Q.length-1];try{super(...X,Y)}catch(U){return C(`Encountered an unexpected error while compiling your definition:
|
|
1
|
+
var GU=Object.defineProperty;var _U=(Q,X)=>{for(var Y in X)GU(Q,Y,{get:X[Y],enumerable:!0,configurable:!0,set:(U)=>X[Y]=()=>U})};var xQ=(Q,X)=>()=>(Q&&(X=Q(Q=0)),X);class i{static evaluate(Q,X){try{if(Q.includes("${")){let Y=this.interpolate(Q,X);if(!isNaN(Number(Y))&&Y.trim()!=="")return Number(Y);return Y}return this.evaluateExpression(Q,X)}catch(Y){return console.error(`Error evaluating expression: ${Q}`,Y),null}}static interpolate(Q,X){return Q.replace(/\$\{([^}]+)\}/g,(Y,U)=>{try{let Z=this.evaluateExpression(U,X);if(Z===void 0||Z===null)return"undefined";return String(Z)}catch(Z){return console.error(`Error en interpolación: ${Y}`,Z),Y}})}static evaluateMathExpression(Q){try{return Function("Math",`return ${Q}`)(Math)}catch(X){throw Error(`Error evaluando expresión matemática: ${Q}`)}}static evaluateExpression(Q,X){if(/^(data|globals|request|computed)(\.[a-zA-Z0-9_]+)+$/.test(Q))return this.getNestedValue(Q,X);try{return Function("context","with(context) { return "+Q+" }")(X)}catch(Y){return console.error(`ERROR evaluating expression '${Q}':`,Y),Q}}static getNestedValue(Q,X){let Y=Q.split("."),U=X;for(let Z of Y){if(U===null||U===void 0||typeof U!=="object"||!(Z in U))return;U=U[Z]}return U}static evaluateMath(Q,X){let Y=Q;Y=Y.replace(/\b[a-zA-Z_][a-zA-Z0-9_]*\b/g,(U)=>{if(["Math","random","floor","ceil","round","sqrt","abs","pow","min","max","sin","cos","tan"].includes(U))return U;let Z=this.getNestedValue(U,X);if(Z!==void 0)return typeof Z==="string"?`"${Z}"`:String(Z);return U});try{return this.evaluateMathExpression(Y)}catch(U){return console.error(`Error en evaluación matemática: ${Q}`,U),NaN}}}class B6{store=new Map;async loadState(){return new Map(this.store)}async saveState(Q,X){this.store.set(Q,X)}async deleteState(Q){this.store.delete(Q)}async clearState(){this.store.clear()}}class Q1{static instance;state;persistence;constructor(){this.state=new Map,this.persistence=new B6}static getInstance(){if(!Q1.instance)Q1.instance=new Q1;return Q1.instance}setPersistence(Q){this.persistence=Q}async initialize(){let Q=await this.persistence.loadState();this.state=Q,console.log(`[StateManager] Initialized with ${this.state.size} keys.`)}get(Q){return this.state.get(Q)}async set(Q,X){this.state.set(Q,X),await this.persistence.saveState(Q,X)}async increment(Q,X=1){let Y=this.get(Q)||0,U=Number(Y)+X;return await this.set(Q,U),U}async decrement(Q,X=1){return this.increment(Q,-X)}async delete(Q){let X=this.state.delete(Q);if(X)await this.persistence.deleteState(Q);return X}async clear(){this.state.clear(),await this.persistence.clearState()}getAll(){return Object.fromEntries(this.state)}}var U2=()=>{};var uQ={};_U(uQ,{ActionRegistry:()=>v1});class v1{static instance;handlers=new Map;constructor(){this.registerDefaults()}static getInstance(){if(!this.instance)this.instance=new v1;return this.instance}register(Q,X){this.handlers.set(Q.toUpperCase(),X)}get(Q){return this.handlers.get(Q.toUpperCase())}registerDefaults(){this.register("log",(Q,X)=>{let Y=Q.params?.message||Q.params?.content||"Log Trigger",U=typeof Y==="string"?i.interpolate(Y,X):String(Y);return console.log(`[TriggerLog] ${U}`),{message:U}}),this.register("response",(Q,X)=>{let Y=Q.params?.content||Q.params?.body||"",U=typeof Y==="string"?i.interpolate(Y,X):String(Y);return{statusCode:Q.params?.statusCode||200,headers:Q.params?.headers||{"Content-Type":"application/json"},body:U}}),this.register("execute",async(Q,X)=>{let Y=Q.params?.command||Q.params?.content||"",U=typeof Y==="string"?i.interpolate(Y,X):String(Y);if(!Q.params?.safe)console.warn(`[Trigger] Ejecutando comando no seguro: ${U}`);try{let Z=Bun.spawn(U.split(" "),{stdout:"pipe",stderr:"pipe"}),[W,G]=await Promise.all([new Response(Z.stdout).text(),new Response(Z.stderr).text()]);return{command:U,stdout:W,stderr:G,exitCode:await Z.exited}}catch(Z){return{command:U,error:String(Z)}}}),this.register("forward",async(Q,X)=>{let Y=Q.params?.url||"",U=typeof Y==="string"?i.interpolate(Y,X):String(Y),Z=String(Q.params?.method||"POST");try{let W=await fetch(U,{method:Z,headers:{"Content-Type":"application/json",...typeof Q.params?.headers==="object"&&Q.params.headers!==null&&!Array.isArray(Q.params.headers)?Q.params.headers:{}},body:JSON.stringify(X.data)});return{url:U,method:Z,status:W.status,headers:(()=>{let G={};return W.headers.forEach((_,H)=>G[H]=_),G})(),body:await W.text()}}catch(W){return{url:U,method:Z,error:String(W)}}}),this.register("STATE_SET",async(Q,X)=>{let Y=String(Q.params?.key||""),U=Q.params?.value;if(!Y)return{error:"Missing key for STATE_SET"};let Z=U;if(typeof U==="string"&&U.includes("${"))Z=i.interpolate(U,X);return await Q1.getInstance().set(Y,Z),{key:Y,value:Z}}),this.register("STATE_INCREMENT",async(Q,X)=>{let Y=String(Q.params?.key||""),U=Number(Q.params?.amount)||1;if(!Y)return{error:"Missing key for STATE_INCREMENT"};let Z=await Q1.getInstance().increment(Y,U);return{key:Y,newValue:Z}}),this.register("EMIT_EVENT",(Q,X)=>{return{event:Q.params?.event,payload:Q.params?.data||{}}})}}var Z2=xQ(()=>{U2()});class JU{queue=[];engine;config;timer=null;isProcessing=!1;constructor(Q,X={maxBatchSize:10,flushIntervalMs:100}){this.engine=Q,this.config=X}push(Q){if(this.queue.push(Q),this.queue.length>=this.config.maxBatchSize)this.processQueue();else if(!this.timer)this.timer=setTimeout(()=>this.processQueue(),this.config.flushIntervalMs)}async processQueue(){if(this.isProcessing)return;if(this.isProcessing=!0,this.timer)clearTimeout(this.timer),this.timer=null;let Q=this.queue.splice(0,this.config.maxBatchSize);if(Q.length===0){this.isProcessing=!1;return}console.debug(`[EventQueue] Processing batch of ${Q.length} events.`);for(let X of Q)try{await this.engine.evaluateContext(X)}catch(Y){console.error(`[EventQueue] Error processing event ${X.event}:`,Y)}if(this.queue.length>0)setTimeout(()=>this.processQueue(),0);this.isProcessing=!1}getQueueLength(){return this.queue.length}}class hQ{keyPrefix;cache=new Map;isLoaded=!1;constructor(Q="trigger_system:"){this.keyPrefix=Q}isAvailable(){return typeof window<"u"&&typeof window.localStorage<"u"}ensureLoaded(){if(this.isLoaded)return;if(this.isAvailable())try{let Q=window.localStorage.getItem(this.keyPrefix+"state");if(Q){let X=JSON.parse(Q);this.cache=new Map(Object.entries(X))}}catch(Q){console.error("[BrowserPersistence] Failed to load from localStorage:",Q)}this.isLoaded=!0}persist(){if(this.isAvailable())try{let Q=Object.fromEntries(this.cache);window.localStorage.setItem(this.keyPrefix+"state",JSON.stringify(Q))}catch(Q){console.error("[BrowserPersistence] Failed to save to localStorage:",Q)}}async loadState(){return this.ensureLoaded(),new Map(this.cache)}async saveState(Q,X){this.ensureLoaded(),this.cache.set(Q,X),this.persist()}async deleteState(Q){this.ensureLoaded(),this.cache.delete(Q),this.persist()}async clearState(){this.cache.clear(),this.persist()}}class Y2{static getNestedValue(Q,X){let Y=Q.split("."),U=X;for(let Z of Y){if(U===null||U===void 0)return;if(typeof U==="object"&&U!==null&&Z in U)U=U[Z];else return}return U}static interpolate(Q,X){if(typeof Q!=="string")return Q;return Q.replace(/\$\{([^}]+)\}/g,(Y,U)=>{let Z=this.getNestedValue(U,X);if(Z!==void 0)return String(Z);return Y})}static compare(Q,X,Y){switch(X){case"EQ":case"==":return Q==Y;case"NEQ":case"!=":return Q!=Y;case"GT":case">":return Number(Q)>Number(Y);case"GTE":case">=":return Number(Q)>=Number(Y);case"LT":case"<":return Number(Q)<Number(Y);case"LTE":case"<=":return Number(Q)<=Number(Y);case"IN":return Array.isArray(Y)&&Y.some((U)=>U===Q);case"NOT_IN":return Array.isArray(Y)&&!Y.some((U)=>U===Q);case"CONTAINS":if(Array.isArray(Q)||typeof Q==="string")return Q.includes(Y);return!1;case"MATCHES":if(typeof Y==="string")return new RegExp(Y).test(String(Q));return!1;case"RANGE":if(Array.isArray(Y)&&Y.length===2){let U=Number(Q),Z=Number(Y[0]),W=Number(Y[1]);return!isNaN(U)&&!isNaN(Z)&&!isNaN(W)&&U>=Z&&U<=W}return!1;default:return console.warn(`Unknown operator: ${X}`),!1}}}var pQ;((U)=>{U.RULE_ADDED="rule:added";U.RULE_REMOVED="rule:removed";U.RULE_UPDATED="rule:updated"})(pQ||={});var k2=pQ;class M6{static instance;handlers=new Map;constructor(){}static getInstance(){if(!this.instance)this.instance=new M6;return this.instance}on(Q,X){let Y=Q;if(!this.handlers.has(Y))this.handlers.set(Y,new Set);return this.handlers.get(Y).add(X),()=>this.off(Y,X)}off(Q,X){let Y=Q,U=this.handlers.get(Y);if(U)U.delete(X)}emit(Q,X){let Y=Q,U=this.handlers.get(Y);if(U)U.forEach((Z)=>{try{Z(X)}catch(W){console.error(`Error in event handler for ${Y}:`,W)}})}}var G1=M6.getInstance();class W2{_rules=[];actionHandlers=new Map;lastExecution=new Map;_config;constructor(Q=[]){if(Array.isArray(Q))this._rules=Q;else this._config=Q,this._rules=[...Q.rules];this.sortRules()}sortRules(){this._rules.sort((Q,X)=>(X.priority||0)-(Q.priority||0))}registerAction(Q,X){this.actionHandlers.set(Q,X)}async processEvent(Q){let X=[],Y=this._rules.filter((U)=>U.enabled!==!1&&U.on===Q.event);for(let U of Y){if(U.cooldown&&this.checkCooldown(U.id,U.cooldown))continue;if(this.evaluateConditions(U.if,Q)){let Z=await this.executeRuleActions(U.do,Q);if(this.lastExecution.set(U.id,Date.now()),X.push({ruleId:U.id,success:!0,executedActions:Z}),!this.shouldEvaluateAll())break}}return X}async processEventSimple(Q,X={},Y={}){let U={event:Q,data:X,globals:Y,timestamp:Date.now(),state:this.getStateContext?this.getStateContext():{}};return this.processEvent(U)}updateRules(Q){let X=this.getRules(),Y=new Set(X.map((G)=>G.id)),U=new Set(Q.map((G)=>G.id)),Z=Q.filter((G)=>!Y.has(G.id)),W=X.filter((G)=>!U.has(G.id));this.rules=[...Q],this.sortRules(),Z.forEach((G)=>{this.emitRuleEvent(k2.RULE_ADDED,{ruleId:G.id,timestamp:Date.now()})}),W.forEach((G)=>{this.emitRuleEvent(k2.RULE_REMOVED,{ruleId:G.id,timestamp:Date.now()})}),this.emitRuleEvent(k2.RULE_UPDATED,{count:Q.length,added:Z.length,removed:W.length,unchanged:Q.length-Z.length,timestamp:Date.now()})}emitRuleEvent(Q,X){try{if(G1)G1.emit(Q,{...X,timestamp:Date.now()})}catch(Y){console.warn(`Could not emit event ${Q}:`,Y)}}getRules(){return[...this.rules]}checkCooldown(Q,X){let Y=this.lastExecution.get(Q);if(!Y)return!1;return Date.now()-Y<X}shouldEvaluateAll(){return this.config?.globalSettings?.evaluateAll??!0}getStateContext(){return{}}evaluateConditions(Q,X){if(!Q)return!0;if(Array.isArray(Q))return Q.every((Y)=>this.evaluateSingleCondition(Y,X));return this.evaluateSingleCondition(Q,X)}evaluateSingleCondition(Q,X){if("operator"in Q&&"conditions"in Q){let W=Q;if(W.operator==="OR")return W.conditions.some((G)=>this.evaluateSingleCondition(G,X));else return W.conditions.every((G)=>this.evaluateSingleCondition(G,X))}let Y=Q,U=Y2.getNestedValue(Y.field,X),Z=Y.value;if(typeof Z==="string"&&Z.includes("${"))Z=i.interpolate(Z,X);return Y2.compare(U,Y.operator,Z)}async executeRuleActions(Q,X){let Y=[],U=[],Z="ALL";if(Array.isArray(Q))U=Q;else if("mode"in Q&&"actions"in Q){let W=Q;Z=W.mode,U=W.actions}else U=[Q];if(Z==="EITHER"&&U.length>0){let W=U.reduce((H,J)=>H+(J.probability||1),0),G=Math.random()*W,_;for(let H of U){let J=H.probability||1;if(G-=J,G<=0){_=H;break}}if(!_&&U.length>0)_=U[U.length-1];if(_)U=[_];else U=[]}for(let W of U){let G=await this.executeSingleAction(W,X);Y.push(G)}return Y}async executeSingleAction(Q,X){if(Q.probability!==void 0&&Math.random()>Q.probability)return{type:Q.type,timestamp:Date.now(),result:{skipped:"probability check failed"}};if(Q.delay&&Q.delay>0)await new Promise((Y)=>setTimeout(Y,Q.delay));try{let Y;try{let{ActionRegistry:Z}=await Promise.resolve().then(() => (Z2(),uQ)),W=Z.getInstance().get(Q.type);if(W)Y=(G)=>W({...Q,params:G},X)}catch{Y=this.actionHandlers.get(Q.type)}let U;if(Y)U=await Y(Q.params||{},X);else{let Z=`No handler registered for action type: ${Q.type}`;console.warn(Z),U={warning:Z}}return{type:Q.type,result:U,timestamp:Date.now()}}catch(Y){return console.error(`Error executing action ${Q.type}:`,Y),{type:Q.type,error:String(Y),timestamp:Date.now()}}}interpolateParams(Q,X){let Y={};for(let[U,Z]of Object.entries(Q))if(typeof Z==="string")Y[U]=i.interpolate(Z,X);else if(typeof Z==="object"&&Z!==null&&!Array.isArray(Z))Y[U]=this.interpolateDeep(Z,X);else Y[U]=Z;return Y}interpolateDeep(Q,X){if(typeof Q==="string")return i.interpolate(Q,X);if(Array.isArray(Q))return Q.map((Y)=>this.interpolateDeep(Y,X));if(typeof Q==="object"&&Q!==null){let Y={};for(let U in Q)Y[U]=this.interpolateDeep(Q[U],X);return Y}return Q}get rules(){return[...this._rules]}get config(){return this._config}set rules(Q){this._rules=[...Q],this.sortRules()}}Z2();U2();class T6 extends W2{actionRegistry;stateManager;constructor(Q){super(Q);this.actionRegistry=v1.getInstance(),this.stateManager=Q1.getInstance()}async processEvent(Q){let X=[];if(Q.state=this.stateManager.getAll(),G1.emit("engine:start",{context:Q,rulesCount:this.rules.length}),this.config?.globalSettings?.debugMode)console.log(`[RuleEngine] Evaluating context with ${this.rules.length} rules for event: ${Q.event}`);let Y=this.rules.filter((U)=>U.enabled!==!1&&U.on===Q.event);for(let U of Y){if(U.cooldown&&this.checkCooldown(U.id,U.cooldown)){if(this.config?.globalSettings?.debugMode)console.log(`[RuleEngine] Rule ${U.id} in cooldown`);continue}if(this.evaluateConditions(U.if,Q)){if(this.config?.globalSettings?.debugMode)console.log(`[RuleEngine] Executing rule: ${U.name||U.id}`);G1.emit("rule:match",{rule:U,context:Q});let W=await this.executeRuleActionsWithRegistry(U.do,Q);if(X.push({ruleId:U.id,executedActions:W,success:!0}),this.updateLastExecution(U.id),!this.shouldEvaluateAll())break}}return G1.emit("engine:done",{results:X,context:Q}),X}async processEventSimple(Q,X={},Y={}){let U={event:Q,data:X,globals:Y,timestamp:Date.now(),state:this.stateManager.getAll()};return this.processEvent(U)}async executeRuleActionsWithRegistry(Q,X){let Y=[],U=[],Z="ALL";if(Array.isArray(Q))U=Q;else if(this.isActionGroup(Q)){let W=Q;Z=W.mode,U=W.actions}else U=[Q];if(Z==="EITHER"&&U.length>0){let W=Math.floor(Math.random()*U.length),G=U[W];if(G)U=[G]}if(Z==="SEQUENCE")for(let W of U){let G=await this.executeSingleActionWithRegistry(W,X);Y.push(G)}else for(let W of U){let G=await this.executeSingleActionWithRegistry(W,X);Y.push(G)}return Y}isActionGroup(Q){return typeof Q==="object"&&Q!==null&&"mode"in Q&&"actions"in Q}async executeSingleActionWithRegistry(Q,X){if(Q.probability!==void 0&&Math.random()>Q.probability)return{type:Q.type,timestamp:Date.now(),result:{skipped:"probability check failed"}};if(Q.delay&&Q.delay>0)await new Promise((Y)=>setTimeout(Y,Q.delay));try{let Y=this.actionRegistry.get(Q.type),U;if(Y)U=await Y(Q,X);else{let Z=`Generic or unknown action type: ${Q.type}`;if(this.config?.globalSettings?.strictActions)throw Error(Z);console.warn(Z),U={warning:`Generic action executed: ${Q.type}`}}return G1.emit("action:success",{action:Q,context:X,result:U}),{type:Q.type,result:U,timestamp:Date.now()}}catch(Y){return console.error("Error executing action:",Q,Y),G1.emit("action:error",{action:Q,context:X,error:String(Y)}),{type:Q.type,error:String(Y),timestamp:Date.now()}}}updateLastExecution(Q){this.lastExecution.set(Q,Date.now())}getStateContext(){return this.stateManager.getAll()}shouldEvaluateAll(){return this.config?.globalSettings?.evaluateAll??!0}async executeRuleActions(Q,X){return this.executeRuleActionsWithRegistry(Q,X)}async executeSingleAction(Q,X){return this.executeSingleActionWithRegistry(Q,X)}}Z2();class HU{static create(Q,X,Y={}){return{event:Q,timestamp:Date.now(),data:typeof X==="object"&&X!==null?X:{value:X},globals:Y,helpers:this.getDefaultHelpers()}}static fromRequest(Q,X,Y={}){let U=new URL(Q.url);return{event:"HTTP_REQUEST",timestamp:Date.now(),data:{method:Q.method,path:U.pathname,query:Object.fromEntries(U.searchParams),headers:(()=>{let Z={};return Q.headers.forEach((W,G)=>Z[G]=W),Z})(),body:X||{}},globals:{...Y,ip:Q.headers.get("x-forwarded-for")||"unknown"},helpers:this.getDefaultHelpers()}}static fromWebhook(Q,X,Y,U={}){return{event:`WEBHOOK_${Q.toUpperCase()}_${X.toUpperCase()}`,timestamp:Date.now(),data:Y,globals:{...U,provider:Q},helpers:this.getDefaultHelpers()}}static getDefaultHelpers(){return{now:()=>Date.now(),uuid:()=>crypto.randomUUID(),jsonParse:(Q)=>typeof Q==="string"?JSON.parse(Q):null,jsonStringify:(Q)=>JSON.stringify(Q)}}}U2();Z2();U2();var B1=(Q)=>Array.isArray(Q)?Q:[Q],mQ=(Q,X)=>{let Y=[[],[]];for(let U of Q)if(X(U))Y[0].push(U);else Y[1].push(U);return Y},g2=Array,n=(Q,X)=>Q.includes(X),lQ=(Q,X=0)=>[...Array(Q)].map((Y,U)=>U+X),D=(Q,X,Y)=>{if(Q===void 0)return X===void 0?[]:Array.isArray(X)?X:[X];if(Y?.prepend)if(Array.isArray(X))Q.unshift(...X);else Q.unshift(X);else if(Array.isArray(X))Q.push(...X);else Q.push(X);return Q},q1=(Q,X)=>{if(X===void 0||X===null)return Q??[];if(Q===void 0||Q===null)return B1(X);return Q.concat(X)},dQ=(...Q)=>Q.reduce(q1,[]),_1=(Q,X,Y)=>{if(Q===void 0)return Array.isArray(X)?X:[X];let U=Y?.isEqual??((Z,W)=>Z===W);for(let Z of B1(X))if(!Q.some((W)=>U(W,Z)))Q.push(Z);return Q},cQ=(Q,X)=>Q.reduce((Y,U)=>{let Z=U[X];return Y[Z]=D(Y[Z],U),Y},{}),$1=(Q,X,Y)=>Q.length===X.length&&Q.every(Y?.isEqual?(U,Z)=>Y.isEqual(U,X[Z]):(U,Z)=>U===X[Z]);var p=(Q,X)=>y(Q)===X,y=(Q)=>{let X=typeof Q;return X==="object"?Q===null?"null":"object":X==="function"?"object":X},u={boolean:"boolean",null:"null",undefined:"undefined",bigint:"a bigint",number:"a number",object:"an object",string:"a string",symbol:"a symbol"},oQ={...u,function:"a function"};class iQ extends Error{}var C=(Q)=>P1(Q,iQ),P1=(Q,X=Error)=>{throw new X(Q)};class G2 extends Error{name="ParseError"}var L=(Q)=>P1(Q,G2),X1=(Q)=>` ${Q}`,sQ="";var V=(Q,X)=>{let Y={},U=Array.isArray(Q),Z=!1;for(let[W,G]of Object.entries(Q).entries()){let _=U?X(W,G[1]):X(...G,W);Z||=typeof _[0]==="number";let H=Array.isArray(_[0])||_.length===0?_:[_];for(let[J,$]of H)if(typeof J==="object")Y[J.group]=D(Y[J.group],$);else Y[J]=$}return Z?Object.values(Y):Y};var D6=Object.entries;var f=(Q,X)=>(Q in X),k1=(Q,X)=>(X in Q);class R6{constructor(Q){Object.assign(this,Q)}}var nQ=class{};class _2 extends nQ{}var FU=(Q,X)=>{let Y={},U={},Z;for(Z in Q)if(Z in X)Y[Z]=Q[Z];else U[Z]=Q[Z];return[Y,U]};var x2=(Q,X)=>FU(Q,X)[1],J1=(Q)=>Object.keys(Q).length===0,N1=(Q)=>[...Object.entries(Q),...Object.getOwnPropertySymbols(Q).map((X)=>[X,Q[X]])],rQ=(Q,X)=>Object.defineProperties(Q,Object.getOwnPropertyDescriptors(X)),tQ=(Q)=>{let X=Object.keys(Q).sort(),Y={};for(let U=0;U<X.length;U++)Y[X[U]]=Q[X[U]];return Y};var m=X1(`unset${sQ}`),aQ=(Q)=>Object.values(Q).filter((X)=>{if(typeof X==="number")return!0;return typeof Q[X]!=="number"});var C6={Array,Boolean,Date,Error,Function,Map,Number,Promise,RegExp,Set,String,WeakMap,WeakSet},w6=globalThis.File??Blob,K6={ArrayBuffer,Blob,File:w6,FormData,Headers,Request,Response,URL},qU={Int8Array,Uint8Array,Uint8ClampedArray,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array},E1={...C6,...K6,...qU,String,Number,Boolean},J2=(Q)=>{let X=Object.getPrototypeOf(Q);while(X?.constructor&&(!f(X.constructor.name,E1)||!(Q instanceof E1[X.constructor.name])))X=Object.getPrototypeOf(X);let Y=X?.constructor?.name;if(Y===void 0||Y==="Object")return;return Y},L2=(Q)=>typeof Q==="object"&&Q!==null?J2(Q)??"object":y(Q);var K=Array.isArray,$U={Array:"an array",Function:"a function",Date:"a Date",RegExp:"a RegExp",Error:"an Error",Map:"a Map",Set:"a Set",String:"a String object",Number:"a Number object",Boolean:"a Boolean object",Promise:"a Promise",WeakMap:"a WeakMap",WeakSet:"a WeakSet"},AU={ArrayBuffer:"an ArrayBuffer instance",Blob:"a Blob instance",File:"a File instance",FormData:"a FormData instance",Headers:"a Headers instance",Request:"a Request instance",Response:"a Response instance",URL:"a URL instance"},zU={Int8Array:"an Int8Array",Uint8Array:"a Uint8Array",Uint8ClampedArray:"a Uint8ClampedArray",Int16Array:"an Int16Array",Uint16Array:"a Uint16Array",Int32Array:"an Int32Array",Uint32Array:"a Uint32Array",Float32Array:"a Float32Array",Float64Array:"a Float64Array",BigInt64Array:"a BigInt64Array",BigUint64Array:"a BigUint64Array"},eQ={...$U,...AU,...zU},H2=(Q)=>{let X=Object(Q).name??null;return X&&f(X,E1)&&E1[X]===Q?X:null};var P6=(Q,X)=>{let Y=Q.prototype;while(Y!==null){if(Y===X.prototype)return!0;Y=Object.getPrototypeOf(Y)}return!1};var Q4=(Q)=>X4(Q,new Map),X4=(Q,X)=>{if(typeof Q!=="object"||Q===null)return Q;if(X?.has(Q))return X.get(Q);let Y=H2(Q.constructor);if(Y==="Date")return new Date(Q.getTime());if(Y&&Y!=="Array")return Q;let U=Array.isArray(Q)?Q.slice():Object.create(Object.getPrototypeOf(Q)),Z=Object.getOwnPropertyDescriptors(Q);if(X){X.set(Q,U);for(let W in Z){let G=Z[W];if("get"in G||"set"in G)continue;G.value=X4(G.value,X)}}return Object.defineProperties(U,Z),U};var OU=(Q)=>{let X=m;return()=>X===m?X=Q():X},M1=(Q)=>typeof Q==="function"&&Q.length===0;var Y4=class extends Function{constructor(...Q){let X=Q.slice(0,-1),Y=Q[Q.length-1];try{super(...X,Y)}catch(U){return C(`Encountered an unexpected error while compiling your definition:
|
|
2
2
|
Message: ${U}
|
|
3
3
|
Source: (${Q.slice(0,-1)}) => {
|
|
4
4
|
${Q[Q.length-1]}
|
|
5
|
-
}`)}}};class l{constructor(Q,...[X]){return Object.assign(Object.setPrototypeOf(Q.bind(X?.bind??this),this.constructor.prototype),X?.attach)}}var
|
|
6
|
-
`)[2]?.trim()||"").match(/\(?(.+?)(?::\d+:\d+)?\)?$/)?.[1]||"unknown").replace(/^file:\/\//,"")}catch{return"unknown"}},
|
|
5
|
+
}`)}}};class l{constructor(Q,...[X]){return Object.assign(Object.setPrototypeOf(Q.bind(X?.bind??this),this.constructor.prototype),X?.attach)}}var U4=OU(()=>{try{return Function("return false")()}catch{return!0}});var D0=X1("brand");var Z4=X1("arkInferred");var w0=X1("args");class k{constructor(){}}var VU=()=>{try{return((Error().stack?.split(`
|
|
6
|
+
`)[2]?.trim()||"").match(/\(?(.+?)(?::\d+:\d+)?\)?$/)?.[1]||"unknown").replace(/^file:\/\//,"")}catch{return"unknown"}},BU=globalThis.process?.env??{},W4={fileName:VU,env:BU};var G4=(Q)=>Q[0].toUpperCase()+Q.slice(1),_4=(Q)=>Q[0].toLowerCase()+Q.slice(1),N6=(Q)=>new RegExp(MU(Q),typeof Q==="string"?"":Q.flags);var MU=(Q)=>{return`^(?:${typeof Q==="string"?Q:Q.source})$`};var A1={negativeLookahead:(Q)=>`(?!${Q})`,nonCapturingGroup:(Q)=>`(?:${Q})`},I1="\\",T1={" ":1,"\n":1,"\t":1};var TU=/^-0\.?0*$/.source,L4=/[1-9]\d*/.source,DU=/\.\d+/.source,RU=/\.\d*[1-9]/.source,H4=(Q)=>N6(A1.negativeLookahead(TU)+A1.nonCapturingGroup("-?"+A1.nonCapturingGroup(A1.nonCapturingGroup("0|"+L4)+A1.nonCapturingGroup(Q.decimalPattern)+"?")+(Q.allowDecimalOnly?"|"+Q.decimalPattern:"")+"?")),J4=H4({decimalPattern:RU,allowDecimalOnly:!1}),CU=J4.test.bind(J4),h2=H4({decimalPattern:DU,allowDecimalOnly:!0}),j0=h2.test.bind(h2),wU=/^-?\d*\.?\d*$/,KU=(Q)=>Q.length!==0&&wU.test(Q),F2=N6(A1.negativeLookahead("^-0$")+"-?"+A1.nonCapturingGroup(A1.nonCapturingGroup("0|"+L4))),PU=F2.test.bind(F2),E6=/^-?\d+$/,NU=E6.test.bind(E6),F4={number:"a number",bigint:"a bigint",integer:"an integer"},q4=(Q,X)=>`'${Q}' was parsed as ${F4[X]} but could not be narrowed to a literal value. Avoid unnecessary leading or trailing zeros and other abnormal notation`,EU=(Q,X)=>X==="number"?CU(Q):PU(Q),IU=(Q,X)=>X==="number"?Number(Q):Number.parseInt(Q),SU=(Q,X)=>X==="number"?KU(Q):NU(Q),$4=(Q,X)=>I6(Q,"number",X),A4=(Q,X)=>I6(Q,"number",{...X,strict:!0}),z4=(Q,X)=>I6(Q,"integer",X),I6=(Q,X,Y)=>{let U=IU(Q,X);if(!Number.isNaN(U)){if(SU(Q,X)){if(Y?.strict)return EU(Q,X)?U:L(q4(Q,X));return U}}return Y?.errorOnFail?L(Y?.errorOnFail===!0?`Failed to parse ${F4[X]} from '${Q}'`:Y?.errorOnFail):void 0},O4=(Q)=>{if(Q[Q.length-1]!=="n")return;let X=Q.slice(0,-1),Y;try{Y=BigInt(X)}catch{return}if(F2.test(X))return Y;if(E6.test(X))return L(q4(Q,"bigint"))};var jU="0.56.0",bU={version:jU,filename:W4.fileName(),FileConstructor:w6},S1=bU,V4=new Map,S6=Object.create(null),q2=(Q)=>{let X=V4.get(Q);if(X)return X;let Y=yU(Q);if(S6[Y])Y=`${Y}${S6[Y]++}`;else S6[Y]=1;return S1[Y]=Q,V4.set(Q,Y),Y},D1=(Q)=>/^[$A-Z_a-z][\w$]*$/.test(Q),yU=(Q)=>{switch(typeof Q){case"object":{if(Q===null)break;let X=J2(Q)??"object";return X[0].toLowerCase()+X.slice(1)}case"function":return D1(Q.name)?Q.name:"fn";case"symbol":return Q.description&&D1(Q.description)?Q.description:"symbol"}return C(`Unexpected attempt to register serializable value of type ${y(Q)}`)};var $2=(Q)=>typeof Q==="string"?JSON.stringify(Q):typeof Q==="bigint"?`${Q}n`:`${Q}`;var B4=(Q,X={})=>A2(Q,{onUndefined:"$ark.undefined",onBigInt:(Y)=>`$ark.bigint-${Y}`,...X},[]);var B=(Q,X)=>{switch(y(Q)){case"object":let Y=Q,U=Y.constructor?.name??"Object";return U==="Object"||U==="Array"?X?.quoteKeys===!1?p2(Y,X?.indent??0,""):JSON.stringify(A2(Y,g1,[]),null,X?.indent):p2(Y,X?.indent??0,"");case"symbol":return g1.onSymbol(Q);default:return $2(Q)}},p2=(Q,X,Y)=>{if(typeof Q==="function")return g1.onFunction(Q);if(typeof Q!=="object"||Q===null)return $2(Q);let U=Y+" ".repeat(X);if(Array.isArray(Q)){if(Q.length===0)return"[]";let W=Q.map((G)=>p2(G,X,U)).join(`,
|
|
7
7
|
`+U);return X?`[
|
|
8
8
|
${U}${W}
|
|
9
|
-
${Y}]`:`[${W}]`}let Z=Q.constructor?.name??"Object";if(Z==="Object"){let W=
|
|
9
|
+
${Y}]`:`[${W}]`}let Z=Q.constructor?.name??"Object";if(Z==="Object"){let W=N1(Q).map(([G,_])=>{let H=typeof G==="symbol"?g1.onSymbol(G):D1(G)?G:JSON.stringify(G),J=p2(_,X,U);return`${U}${H}: ${J}`});if(W.length===0)return"{}";return X?`{
|
|
10
10
|
${W.join(`,
|
|
11
11
|
`)}
|
|
12
|
-
${Y}}`:`{${W.join(", ")}}`}if(Q instanceof Date)return j1(Q);if("expression"in Q&&typeof Q.expression==="string")return Q.expression;return Z},g1={onCycle:()=>"(cycle)",onSymbol:(Q)=>`Symbol(${q2(Q)})`,onFunction:(Q)=>`Function(${q2(Q)})`},A2=(Q,X,Y)=>{switch(y(Q)){case"object":{let U=Q;if("toJSON"in U&&typeof U.toJSON==="function")return U.toJSON();if(typeof U==="function")return g1.onFunction(U);if(Y.includes(U))return"(cycle)";let Z=[...Y,U];if(Array.isArray(U))return U.map((G)=>A2(G,X,Z));if(U instanceof Date)return U.toDateString();let W={};for(let G in U)W[G]=A2(U[G],X,Z);for(let G of Object.getOwnPropertySymbols(U))W[X.onSymbol?.(G)??G.toString()]=A2(U[G],X,Z);return W}case"symbol":return g1.onSymbol(Q);case"bigint":return X.onBigInt?.(Q)??`${Q}n`;case"undefined":return X.onUndefined??"undefined";case"string":return Q.replace(/\\/g,"\\\\");default:return Q}},j1=(Q)=>{let X=Q.getFullYear(),Y=Q.getMonth(),U=Q.getDate(),Z=Q.getHours(),W=Q.getMinutes(),G=Q.getSeconds(),_=Q.getMilliseconds();if(Y===0&&U===1&&Z===0&&W===0&&G===0&&_===0)return`${X}`;let H=`${
|
|
12
|
+
${Y}}`:`{${W.join(", ")}}`}if(Q instanceof Date)return j1(Q);if("expression"in Q&&typeof Q.expression==="string")return Q.expression;return Z},g1={onCycle:()=>"(cycle)",onSymbol:(Q)=>`Symbol(${q2(Q)})`,onFunction:(Q)=>`Function(${q2(Q)})`},A2=(Q,X,Y)=>{switch(y(Q)){case"object":{let U=Q;if("toJSON"in U&&typeof U.toJSON==="function")return U.toJSON();if(typeof U==="function")return g1.onFunction(U);if(Y.includes(U))return"(cycle)";let Z=[...Y,U];if(Array.isArray(U))return U.map((G)=>A2(G,X,Z));if(U instanceof Date)return U.toDateString();let W={};for(let G in U)W[G]=A2(U[G],X,Z);for(let G of Object.getOwnPropertySymbols(U))W[X.onSymbol?.(G)??G.toString()]=A2(U[G],X,Z);return W}case"symbol":return g1.onSymbol(Q);case"bigint":return X.onBigInt?.(Q)??`${Q}n`;case"undefined":return X.onUndefined??"undefined";case"string":return Q.replace(/\\/g,"\\\\");default:return Q}},j1=(Q)=>{let X=Q.getFullYear(),Y=Q.getMonth(),U=Q.getDate(),Z=Q.getHours(),W=Q.getMinutes(),G=Q.getSeconds(),_=Q.getMilliseconds();if(Y===0&&U===1&&Z===0&&W===0&&G===0&&_===0)return`${X}`;let H=`${fU[Y]} ${U}, ${X}`;if(Z===0&&W===0&&G===0&&_===0)return H;let J=Q.toLocaleTimeString(),$=J.endsWith(" AM")||J.endsWith(" PM")?J.slice(-3):"";if($)J=J.slice(0,-$.length);if(_)J+=`.${kU(_,3)}`;else if(vU.test(J))J=J.slice(0,-3);return`${J+$}, ${H}`},fU=["January","February","March","April","May","June","July","August","September","October","November","December"],vU=/:\d\d:00$/,kU=(Q,X)=>String(Q).padStart(X,"0");var M4=(Q,X,...[Y])=>{let U=Y?.stringifySymbol??B,Z=Q;switch(typeof X){case"string":Z=D1(X)?Q===""?X:`${Q}.${X}`:`${Q}[${JSON.stringify(X)}]`;break;case"number":Z=`${Q}[${X}]`;break;case"symbol":Z=`${Q}[${U(X)}]`;break;default:if(Y?.stringifyNonKey)Z=`${Q}[${Y.stringifyNonKey(X)}]`;else L(`${B(X)} must be a PropertyKey or stringifyNonKey must be passed to options`)}return Z},z1=(Q,...X)=>Q.reduce((Y,U)=>M4(Y,U,...X),"");class z2 extends g2{cache={};constructor(...Q){super();this.push(...Q)}toJSON(){if(this.cache.json)return this.cache.json;this.cache.json=[];for(let Q=0;Q<this.length;Q++)this.cache.json.push(typeof this[Q]==="symbol"?B(this[Q]):this[Q]);return this.cache.json}stringify(){if(this.cache.stringify)return this.cache.stringify;return this.cache.stringify=z1(this)}stringifyAncestors(){if(this.cache.stringifyAncestors)return this.cache.stringifyAncestors;let Q="",X=[Q];for(let Y of this)Q=M4(Q,Y),X.push(Q);return this.cache.stringifyAncestors=X}}class O2{chars;i;def;constructor(Q){this.def=Q,this.chars=[...Q],this.i=0}shift(){return this.chars[this.i++]??""}get lookahead(){return this.chars[this.i]??""}get nextLookahead(){return this.chars[this.i+1]??""}get length(){return this.chars.length}shiftUntil(Q){let X="";while(this.lookahead)if(Q(this,X))break;else X+=this.shift();return X}shiftUntilEscapable(Q){let X="";while(this.lookahead)if(this.lookahead===I1)if(this.shift(),Q(this,X))X+=this.shift();else if(this.lookahead===I1)X+=this.shift();else X+=`${I1}${this.shift()}`;else if(Q(this,X))break;else X+=this.shift();return X}shiftUntilLookahead(Q){return typeof Q==="string"?this.shiftUntil((X)=>X.lookahead===Q):this.shiftUntil((X)=>(X.lookahead in Q))}shiftUntilNonWhitespace(){return this.shiftUntil(()=>!(this.lookahead in T1))}jumpToIndex(Q){this.i=Q<0?this.length+Q:Q}jumpForward(Q){this.i+=Q}get location(){return this.i}get unscanned(){return this.chars.slice(this.i,this.length).join("")}get scanned(){return this.chars.slice(0,this.i).join("")}sliceChars(Q,X){return this.chars.slice(Q,X).join("")}lookaheadIs(Q){return this.lookahead===Q}lookaheadIsIn(Q){return this.lookahead in Q}}var T4=(Q,X)=>`Unmatched ${Q}${X===""?"":` before ${X}`}`,u2=(Q)=>`Missing ${Q}`;var YW=X1("implementedTraits");var j6="$ark",gU=2;while(j6 in globalThis)j6=`$ark${gU++}`;var D4=j6;globalThis[D4]=S1;var F=S1,xU=(Q)=>`${D4}.${Q}`,S=(Q)=>xU(q2(Q));class m2 extends _2{argNames;body="";constructor(...Q){super();this.argNames=Q;for(let X of Q){if(X in this)throw Error(`Arg name '${X}' would overwrite an existing property on FunctionBody`);this[X]=X}}indentation=0;indent(){return this.indentation+=4,this}dedent(){return this.indentation-=4,this}prop(Q,X=!1){return b6(Q,X)}index(Q,X=!1){return R4(`${Q}`,X)}line(Q){return this.body+=`${" ".repeat(this.indentation)}${Q}
|
|
13
13
|
`,this}const(Q,X){return this.line(`const ${Q} = ${X}`),this}let(Q,X){return this.line(`let ${Q} = ${X}`)}set(Q,X){return this.line(`${Q} = ${X}`)}if(Q,X){return this.block(`if (${Q})`,X)}elseIf(Q,X){return this.block(`else if (${Q})`,X)}else(Q){return this.block("else",Q)}for(Q,X,Y=0){return this.block(`for (let i = ${Y}; ${Q}; i++)`,X)}forIn(Q,X){return this.block(`for (const k in ${Q})`,X)}block(Q,X,Y=""){return this.line(`${Q} {`),this.indent(),X(this),this.dedent(),this.line(`}${Y}`)}return(Q=""){return this.line(`return ${Q}`)}write(Q="anonymous",X=0){return`${Q}(${this.argNames.join(", ")}) { ${X?this.body.split(`
|
|
14
14
|
`).map((Y)=>" ".repeat(X)+`${Y}`).join(`
|
|
15
|
-
`):this.body} }`}compile(){return new
|
|
16
|
-
`)}addAncestorPaths(Q){for(let X of Q.path.stringifyAncestors())this.byAncestorPath[X]=
|
|
17
|
-
`+Q.map((X)=>` • ${
|
|
18
|
-
`));Object.defineProperty(this,"arkErrors",{value:Q,enumerable:!1})}}var
|
|
15
|
+
`):this.body} }`}compile(){return new Y4(...this.argNames,this.body)}}var Y1=(Q)=>p(Q,"object")||typeof Q==="symbol"?S(Q):$2(Q),b6=(Q,X=!1)=>{if(typeof Q==="string"&&D1(Q))return`${X?"?":""}.${Q}`;return R4(hU(Q),X)},hU=(Q)=>typeof Q==="symbol"?S(Q):JSON.stringify(Q),R4=(Q,X=!1)=>`${X?"?.":""}[${Q}]`;class V2 extends m2{traversalKind;optimistic;constructor(Q){super("data","ctx");this.traversalKind=Q.kind,this.optimistic=Q.optimistic===!0}invoke(Q,X){let Y=X?.arg??this.data,U=typeof Q==="string"?!0:this.requiresContextFor(Q),Z=typeof Q==="string"?Q:Q.id;if(U)return`${this.referenceToId(Z,X)}(${Y}, ${this.ctx})`;return`${this.referenceToId(Z,X)}(${Y})`}referenceToId(Q,X){let Y=X?.kind??this.traversalKind,U=`this.${Q}${Y}`;return X?.bind?`${U}.bind(${X?.bind})`:U}requiresContextFor(Q){return this.traversalKind==="Apply"||Q.allowsRequiresContext}initializeErrorCount(){return this.const("errorCount","ctx.currentErrorCount")}returnIfFail(){return this.if("ctx.currentErrorCount > errorCount",()=>this.return())}returnIfFailFast(){return this.if("ctx.failFast && ctx.currentErrorCount > errorCount",()=>this.return())}traverseKey(Q,X,Y){let U=this.requiresContextFor(Y);if(U)this.line(`${this.ctx}.path.push(${Q})`);if(this.check(Y,{arg:X}),U)this.line(`${this.ctx}.path.pop()`);return this}check(Q,X){return this.traversalKind==="Allows"?this.if(`!${this.invoke(Q,X)}`,()=>this.return(!1)):this.line(this.invoke(Q,X))}}var l2=(Q)=>V(Q,(X,Y)=>[X,K(Y)?[...Y]:Y]),x=X1("arkKind"),A=(Q,X)=>Q?.[x]===X,P=(Q)=>A(Q,"root")||A(Q,"constraint");var C4=["unit","proto","domain"],x1=["required","optional","index","sequence"],y6=["pattern","divisor","exactLength","max","min","maxLength","minLength","before","after"],f6=[...y6,"structure","predicate"],d2=[...f6,...x1],h1=["alias","union","morph","unit","intersection","proto","domain"],pU=[...h1,...d2],c2=V(d2,(Q,X)=>[X,1]),w4=V([...x1,"undeclared"],(Q,X)=>[X,1]),K4=V(pU,(Q,X)=>[X,Q]),p1=(Q)=>typeof Q==="string"&&(Q in K4);var u1=(Q)=>K4[Q],o2=(Q)=>h1.slice(u1(Q)+1),hW=[...o2("union"),"alias"],pW=[...o2("morph"),"alias"],r=(Q)=>{if(typeof Q==="string"||typeof Q==="boolean"||Q===null)return Q;if(typeof Q==="number"){if(Number.isNaN(Q))return"NaN";if(Q===Number.POSITIVE_INFINITY)return"Infinity";if(Q===Number.NEGATIVE_INFINITY)return"-Infinity";return Q}return Y1(Q)},R1=(Q)=>{let X="{ ";for(let[Y,U]of Object.entries(Q))X+=`${Y}: ${Y1(U)}, `;return X+" }"},M=(Q)=>{let X=Q;if(X.hasAssociatedError)X.defaults.expected??=(Y)=>("description"in Y)?Y.description:X.defaults.description(Y),X.defaults.actual??=(Y)=>B(Y),X.defaults.problem??=(Y)=>`must be ${Y.expected}${Y.actual?` (was ${Y.actual})`:""}`,X.defaults.message??=(Y)=>{if(Y.path.length===0)return Y.problem;let U=`${Y.propString} ${Y.problem}`;if(U[0]==="[")return`value at ${U}`;return U};return X};class P4 extends Error{name="ToJsonSchemaError";code;context;constructor(Q,X){super(B(X,{quoteKeys:!1,indent:4}));this.code=Q,this.context=X}hasCode(Q){return this.code===Q}}var uU={target:"draft-2020-12",dialect:"https://json-schema.org/draft/2020-12/schema",useRefs:!1,fallback:{arrayObject:(Q)=>E.throw("arrayObject",Q),arrayPostfix:(Q)=>E.throw("arrayPostfix",Q),defaultValue:(Q)=>E.throw("defaultValue",Q),domain:(Q)=>E.throw("domain",Q),morph:(Q)=>E.throw("morph",Q),patternIntersection:(Q)=>E.throw("patternIntersection",Q),predicate:(Q)=>E.throw("predicate",Q),proto:(Q)=>E.throw("proto",Q),symbolKey:(Q)=>E.throw("symbolKey",Q),unit:(Q)=>E.throw("unit",Q),date:(Q)=>E.throw("date",Q)}},E={Error:P4,throw:(...Q)=>{throw new E.Error(...Q)},throwInternalOperandError:(Q,X)=>C(`Unexpected JSON Schema input for ${Q}: ${B(X)}`),defaultConfig:uU};F.config??={};var B2=(Q,X)=>{if(!X)return Q;let Y={...Q},U;for(U in X){let Z={...Q.keywords};if(U==="keywords"){for(let W in X[U]){let G=X.keywords[W];if(G===void 0)continue;Z[W]=typeof G==="string"?{description:G}:G}Y.keywords=Z}else if(U==="toJsonSchema")Y[U]=v6(Q.toJsonSchema,X.toJsonSchema);else if(p1(U))Y[U]={...Q[U],...X[U]};else Y[U]=X[U]}return Y},mU={"draft-2020-12":"https://json-schema.org/draft/2020-12/schema","draft-07":"http://json-schema.org/draft-07/schema#"},v6=(Q,X)=>{if(!Q)return N4(X??{},void 0);if(!X)return Q;let Y={...Q},U;for(U in X)if(U==="fallback")Y.fallback=lU(Q.fallback,X.fallback);else Y[U]=X[U];return N4(Y,X)},N4=(Q,X)=>{if(X?.dialect!==void 0)return Q;if(X?.target!==void 0)return{...Q,dialect:mU[X.target]};return Q},lU=(Q,X)=>{Q=E4(Q),X=E4(X);let Y={},U;for(U in E.defaultConfig.fallback)Y[U]=X[U]??X.default??Q[U]??Q.default??E.defaultConfig.fallback[U];return Y},E4=(Q)=>typeof Q==="function"?{default:Q}:Q??{};class C1 extends _2{[x]="error";path;data;nodeConfig;input;ctx;constructor({prefixPath:Q,relativePath:X,...Y},U){super();this.input=Y,this.ctx=U,rQ(this,Y);let Z=U.data;if(Y.code==="union")Y.errors=Y.errors.flatMap((G)=>{let _=G.hasCode("union")?G.errors:[G];if(!Q&&!X)return _;return _.map((H)=>H.transform((J)=>({...J,path:dQ(Q,J.path,X)})))});this.nodeConfig=U.config[this.code];let W=[...Y.path??U.path];if(X)W.push(...X);if(Q)W.unshift(...Q);this.path=new z2(...W),this.data="data"in Y?Y.data:Z}transform(Q){return new C1(Q({data:this.data,path:this.path,...this.input}),this.ctx)}hasCode(Q){return this.code===Q}get propString(){return z1(this.path)}get expected(){if(this.input.expected)return this.input.expected;let Q=this.meta?.expected??this.nodeConfig.expected;return typeof Q==="function"?Q(this.input):Q}get actual(){if(this.input.actual)return this.input.actual;let Q=this.meta?.actual??this.nodeConfig.actual;return typeof Q==="function"?Q(this.data):Q}get problem(){if(this.input.problem)return this.input.problem;let Q=this.meta?.problem??this.nodeConfig.problem;return typeof Q==="function"?Q(this):Q}get message(){if(this.input.message)return this.input.message;let Q=this.meta?.message??this.nodeConfig.message;return typeof Q==="function"?Q(this):Q}get flat(){return this.hasCode("intersection")?[...this.errors]:[this]}toJSON(){return{data:this.data,path:this.path,...this.input,expected:this.expected,actual:this.actual,problem:this.problem,message:this.message}}toString(){return this.message}throw(){throw this}}class d extends g2{[x]="errors";ctx;constructor(Q){super();this.ctx=Q}byPath=Object.create(null);get flatByPath(){return V(this.byPath,(Q,X)=>[Q,X.flat])}get flatProblemsByPath(){return V(this.byPath,(Q,X)=>[Q,X.flat.map((Y)=>Y.problem)])}byAncestorPath=Object.create(null);count=0;mutable=this;throw(){throw this.toTraversalError()}toTraversalError(){return new k6(this)}add(Q){let X=this.byPath[Q.propString];if(X){if(Q===X)return;if(X.hasCode("union")&&X.errors.length===0)return;let Y=Q.hasCode("union")&&Q.errors.length===0?Q:new C1({code:"intersection",errors:X.hasCode("intersection")?[...X.errors,Q]:[X,Q]},this.ctx),U=this.indexOf(X);this.mutable[U===-1?this.length:U]=Y,this.byPath[Q.propString]=Y,this.addAncestorPaths(Q)}else this.byPath[Q.propString]=Q,this.addAncestorPaths(Q),this.mutable.push(Q);this.count++}transform(Q){let X=new d(this.ctx);for(let Y of this)X.add(Q(Y));return X}merge(Q){for(let X of Q)this.add(new C1({...X,path:[...this.ctx.path,...X.path]},this.ctx))}affectsPath(Q){if(this.length===0)return!1;return Q.stringifyAncestors().some((X)=>(X in this.byPath))||Q.stringify()in this.byAncestorPath}get summary(){return this.toString()}get issues(){return this}toJSON(){return[...this.map((Q)=>Q.toJSON())]}toString(){return this.join(`
|
|
16
|
+
`)}addAncestorPaths(Q){for(let X of Q.path.stringifyAncestors())this.byAncestorPath[X]=D(this.byAncestorPath[X],Q)}}class k6 extends Error{name="TraversalError";constructor(Q){if(Q.length===1)super(Q.summary);else super(`
|
|
17
|
+
`+Q.map((X)=>` • ${dU(X)}`).join(`
|
|
18
|
+
`));Object.defineProperty(this,"arkErrors",{value:Q,enumerable:!1})}}var dU=(Q)=>Q.toString().split(`
|
|
19
19
|
`).join(`
|
|
20
|
-
`);class U1{path=[];errors=new d(this);root;config;queuedMorphs=[];branches=[];seen={};constructor(Q,X){this.root=Q,this.config=X}get data(){let Q=this.root;for(let X of this.path)Q=Q?.[X];return Q}get propString(){return A1(this.path)}reject(Q){return this.error(Q),!1}mustBe(Q){return this.error(Q),!1}error(Q){let X=typeof Q==="object"?Q.code?Q:{...Q,code:"predicate"}:{code:"predicate",expected:Q};return this.errorFromContext(X)}hasError(){return this.currentErrorCount!==0}get currentBranch(){return this.branches[this.branches.length-1]}queueMorphs(Q){let X={path:new z2(...this.path),morphs:Q};if(this.currentBranch)this.currentBranch.queuedMorphs.push(X);else this.queuedMorphs.push(X)}finalize(Q){if(this.queuedMorphs.length){if(typeof this.root==="object"&&this.root!==null&&this.config.clone)this.root=this.config.clone(this.root);this.applyQueuedMorphs()}if(this.hasError())return Q?Q(this.errors):this.errors;return this.root}get currentErrorCount(){return this.currentBranch?this.currentBranch.error?1:0:this.errors.count}get failFast(){return this.branches.length!==0}pushBranch(){this.branches.push({error:void 0,queuedMorphs:[]})}popBranch(){return this.branches.pop()}get external(){return this}errorFromNodeContext(Q){return this.errorFromContext(Q)}errorFromContext(Q){let X=new D1(Q,this);if(this.currentBranch)this.currentBranch.error=X;else this.errors.add(X);return X}applyQueuedMorphs(){while(this.queuedMorphs.length){let Q=this.queuedMorphs;this.queuedMorphs=[];for(let{path:X,morphs:Y}of Q){if(this.errors.affectsPath(X))continue;this.applyMorphsAtPath(X,Y)}}}applyMorphsAtPath(Q,X){let Y=Q[Q.length-1],U;if(Y!==void 0){U=this.root;for(let Z=0;Z<Q.length-1;Z++)U=U[Q[Z]]}for(let Z of X){this.path=[...Q];let W=N(Z),G=Z(U===void 0?this.root:U[Y],this);if(G instanceof D1){if(!this.errors.includes(G))this.errors.add(G);break}if(G instanceof d){if(!W)this.errors.merge(G);this.queuedMorphs=[];break}if(U===void 0)this.root=G;else U[Y]=G;this.applyQueuedMorphs()}}}var c=(Q,X,Y)=>{if(!Y)return X();Y.path.push(Q);let U=X();return Y.path.pop(),U};class M2 extends l{attachments;$;onFail;includesTransform;includesContextualPredicate;isCyclic;allowsRequiresContext;rootApplyStrategy;contextFreeMorph;rootApply;referencesById;shallowReferences;flatRefs;flatMorphs;allows;get shallowMorphs(){return[]}constructor(Q,X){super((U,Z,W=this.onFail)=>{if(Z)return this.traverseApply(U,Z),Z.hasError()?Z.errors:Z.data;return this.rootApply(U,W)},{attach:Q});this.attachments=Q,this.$=X,this.onFail=this.meta.onFail??this.$.resolvedConfig.onFail,this.includesTransform=this.hasKind("morph")||this.hasKind("structure")&&this.structuralMorph!==void 0||this.hasKind("sequence")&&this.inner.defaultables!==void 0,this.includesContextualPredicate=this.hasKind("predicate")&&this.inner.predicate.length!==1,this.isCyclic=this.kind==="alias",this.referencesById={[this.id]:this},this.shallowReferences=this.hasKind("structure")?[this,...this.children]:this.children.reduce((U,Z)=>oU(U,Z.shallowReferences),[this]);let Y=this.isStructural();this.flatRefs=[],this.flatMorphs=[];for(let U=0;U<this.children.length;U++){if(this.includesTransform||=this.children[U].includesTransform,this.includesContextualPredicate||=this.children[U].includesContextualPredicate,this.isCyclic||=this.children[U].isCyclic,!Y){let Z=this.children[U].flatRefs;for(let W=0;W<Z.length;W++){let G=Z[W];if(!this.flatRefs.some((_)=>E4(_,G))){this.flatRefs.push(G);for(let _ of G.node.branches)if(_.hasKind("morph")||_.hasKind("intersection")&&_.structure?.structuralMorph!==void 0)this.flatMorphs.push({path:G.path,propString:G.propString,node:_})}}}Object.assign(this.referencesById,this.children[U].referencesById)}this.flatRefs.sort((U,Z)=>U.path.length>Z.path.length?1:U.path.length<Z.path.length?-1:U.propString>Z.propString?1:U.propString<Z.propString?-1:U.node.expression<Z.node.expression?-1:1),this.allowsRequiresContext=this.includesContextualPredicate||this.isCyclic,this.rootApplyStrategy=!this.allowsRequiresContext&&this.flatMorphs.length===0?this.shallowMorphs.length===0?"allows":this.shallowMorphs.every((U)=>U.length===1||U.name==="$arkStructuralMorph")?this.hasKind("union")?this.branches.some((U)=>U.shallowMorphs.length>1)?"contextual":"branchedOptimistic":this.shallowMorphs.length>1?"contextual":"optimistic":"contextual":"contextual",this.rootApply=this.createRootApply(),this.allows=this.allowsRequiresContext?(U)=>this.traverseAllows(U,new U1(U,this.$.resolvedConfig)):(U)=>this.traverseAllows(U)}createRootApply(){switch(this.rootApplyStrategy){case"allows":return(X,Y)=>{if(this.allows(X))return X;let U=new U1(X,this.$.resolvedConfig);return this.traverseApply(X,U),U.finalize(Y)};case"contextual":return(X,Y)=>{let U=new U1(X,this.$.resolvedConfig);return this.traverseApply(X,U),U.finalize(Y)};case"optimistic":this.contextFreeMorph=this.shallowMorphs[0];let Q=this.$.resolvedConfig.clone;return(X,Y)=>{if(this.allows(X))return this.contextFreeMorph(Q&&(typeof X==="object"&&X!==null||typeof X==="function")?Q(X):X);let U=new U1(X,this.$.resolvedConfig);return this.traverseApply(X,U),U.finalize(Y)};case"branchedOptimistic":return this.createBranchedOptimisticRootApply();default:return this.rootApplyStrategy,C(`Unexpected rootApplyStrategy ${this.rootApplyStrategy}`)}}compiledMeta=cU(this.metaJson);cacheGetter(Q,X){return Object.defineProperty(this,Q,{value:X}),X}get description(){return this.cacheGetter("description",this.meta?.description??this.$.resolvedConfig[this.kind].description(this))}get references(){return Object.values(this.referencesById)}precedence=u1(this.kind);precompilation;assert=(Q,X)=>this(Q,X,(Y)=>Y.throw());traverse(Q,X){return this(Q,X,null)}get in(){return this.cacheGetter("in",this.rawIn.isRoot()?this.$.finalize(this.rawIn):this.rawIn)}get rawIn(){return this.cacheGetter("rawIn",this.getIo("in"))}get out(){return this.cacheGetter("out",this.rawOut.isRoot()?this.$.finalize(this.rawOut):this.rawOut)}get rawOut(){return this.cacheGetter("rawOut",this.getIo("out"))}getIo(Q){if(!this.includesTransform)return this;let X={};for(let[Y,U]of this.innerEntries){let Z=this.impl.keys[Y];if(Z.reduceIo)Z.reduceIo(Q,X,U);else if(Z.child){let W=U;X[Y]=K(W)?W.map((G)=>Q==="in"?G.rawIn:G.rawOut):Q==="in"?W.rawIn:W.rawOut}else X[Y]=U}return this.$.node(this.kind,X)}toJSON(){return this.json}toString(){return`Type<${this.expression}>`}equals(Q){let X=N(Q)?Q:this.$.parseDefinition(Q);return this.innerHash===X.innerHash}ifEquals(Q){return this.equals(Q)?this:void 0}hasKind(Q){return this.kind===Q}assertHasKind(Q){if(this.kind!==Q)N1(`${this.kind} node was not of asserted kind ${Q}`);return this}hasKindIn(...Q){return Q.includes(this.kind)}assertHasKindIn(...Q){if(!n(Q,this.kind))N1(`${this.kind} node was not one of asserted kinds ${Q}`);return this}isBasis(){return n(R4,this.kind)}isConstraint(){return n(l2,this.kind)}isStructural(){return n(x1,this.kind)}isRefinement(){return n(y6,this.kind)}isRoot(){return n(h1,this.kind)}isUnknown(){return this.hasKind("intersection")&&this.children.length===0}isNever(){return this.hasKind("union")&&this.children.length===0}hasUnit(Q){return this.hasKind("unit")&&this.allows(Q)}hasOpenIntersection(){return this.impl.intersectionIsOpen}get nestableExpression(){return this.expression}select(Q){let X=B2.normalize(Q);return this._select(X)}_select(Q){let X=B2.applyBoundary[Q.boundary??"references"](this);if(Q.kind)X=X.filter((Y)=>Y.kind===Q.kind);if(Q.where)X=X.filter(Q.where);return B2.applyMethod[Q.method??"filter"](X,this,Q)}transform(Q,X){return this._transform(Q,this._createTransformContext(X))}_createTransformContext(Q){return{root:this,selected:void 0,seen:{},path:[],parseOptions:{prereduced:Q?.prereduced??!1},undeclaredKeyHandling:void 0,...Q}}_transform(Q,X){let Y=X.bindScope??this.$;if(X.seen[this.id])return this.$.lazilyResolve(X.seen[this.id]);if(X.shouldTransform?.(this,X)===!1)return this;let U;if(X.seen[this.id]=()=>U,this.hasKind("structure")&&this.undeclared!==X.undeclaredKeyHandling)X={...X,undeclaredKeyHandling:this.undeclared};let Z=V(this.inner,(J,$)=>{if(!this.impl.keys[J].child)return[J,$];let O=$;if(!K(O)){let b=O._transform(Q,X);return b?[J,b]:[]}if(O.length===0)return[J,$];let D=O.flatMap((b)=>{return b._transform(Q,X)??[]});return D.length?[J,D]:[]});delete X.seen[this.id];let W=Object.assign(Z,{meta:this.meta}),G=X.selected&&!X.selected.includes(this)?W:Q(this.kind,W,X);if(G===null)return null;if(N(G))return U=G;let _=Object.keys(G);if((_.length===0||_.length===1&&_[0]==="meta")&&!_1(this.inner))return null;if((this.kind==="required"||this.kind==="optional"||this.kind==="index")&&!("value"in G))return X.undeclaredKeyHandling?{...G,value:F.intrinsic.unknown}:null;if(this.kind==="morph")G.in??=F.intrinsic.unknown;return U=Y.node(this.kind,G,X.parseOptions)}configureReferences(Q,X="references"){let Y=B2.normalize(X),U=typeof Q==="string"?(_,H)=>({...H,meta:{...H.meta,description:Q}}):typeof Q==="function"?(_,H)=>({...H,meta:Q(H.meta)}):(_,H)=>({...H,meta:{...H.meta,...Q}});if(Y.boundary==="self")return this.$.node(this.kind,U(this.kind,{...this.inner,meta:this.meta}));let Z=this._select(Y),W=Z&&V1(Z),G=Y.boundary==="child"?(_,H)=>H.root.children.includes(_):Y.boundary==="shallow"?(_)=>_.kind!=="structure":()=>!0;return this.$.finalize(this.transform(U,{shouldTransform:G,selected:W}))}}var B2={applyBoundary:{self:(Q)=>[Q],child:(Q)=>[...Q.children],shallow:(Q)=>[...Q.shallowReferences],references:(Q)=>[...Q.references]},applyMethod:{filter:(Q)=>Q,assertFilter:(Q,X,Y)=>{if(Q.length===0)N1(P4(X,Y));return Q},find:(Q)=>Q[0],assertFind:(Q,X,Y)=>{if(Q.length===0)N1(P4(X,Y));return Q[0]}},normalize:(Q)=>typeof Q==="function"?{boundary:"references",method:"filter",where:Q}:typeof Q==="string"?f(Q,B2.applyBoundary)?{method:"filter",boundary:Q}:{boundary:"references",method:"filter",kind:Q}:{boundary:"references",method:"filter",...Q}},P4=(Q,X)=>`${Q} had no references matching ${T(X)}.`,lU=(Q)=>A1(Q,{stringifyNonKey:(X)=>X.expression}),dU=/"(\$ark\.[^"]+)"/g,cU=(Q)=>JSON.stringify(Q).replace(dU,"$1"),Z1=(Q,X)=>({path:Q,node:X,propString:lU(Q)}),E4=(Q,X)=>Q.propString===X.propString&&Q.node.equals(X.node),k6=(Q,X)=>G1(Q,X,{isEqual:E4}),oU=(Q,X)=>G1(Q,X,{isEqual:(Y,U)=>Y.equals(U)});class q extends Array{static init(Q,X,Y,U){return new q({kind:Q,l:X,r:Y,path:U?.path??[],optional:U?.optional??!1})}add(Q,X,Y,U){return this.push({kind:Q,l:X,r:Y,path:U?.path??[],optional:U?.optional??!1}),this}get summary(){return this.describeReasons()}describeReasons(){if(this.length===1){let{path:Q,l:X,r:Y}=this[0],U=A1(Q);return x6(`Intersection${U&&` at ${U}`} of ${I4(X,Y)}`)}return`The following intersections result in unsatisfiable types:
|
|
21
|
-
• ${this.map(({path:Q,l:X,r:Y})=>`${Q}: ${
|
|
22
|
-
• `)}`}throw(){return L(this.describeReasons())}invert(){let Q=this.map((X)=>({...X,l:X.r,r:X.l}));if(!(Q instanceof q))return new q(...Q);return Q}withPrefixKey(Q,X){return this.map((Y)=>({...Y,path:[Q,...Y.path],optional:Y.optional||X==="optional"}))}toNeverIfDisjoint(){return F.intrinsic.never}}var I4=(Q,X)=>`${g6(Q)} and ${g6(X)}`,g6=(Q)=>N(Q)?Q.expression:K(Q)?Q.map(g6).join(" | ")||"never":String(Q),x6=(Q)=>`${Q} results in an unsatisfiable type`;var m1={},o=(Q,X,Y)=>P(Q,X,{$:Y,invert:!1,pipe:!1}),R2=(Q,X,Y)=>P(Q,X,{$:Y,invert:!1,pipe:!0}),P=(Q,X,Y)=>{let U=Y.pipe?"|>":"&",Z=`${Q.hash}${U}${X.hash}`;if(m1[Z]!==void 0)return m1[Z];if(!Y.pipe){let _=`${X.hash}${U}${Q.hash}`;if(m1[_]!==void 0){let H=m1[_],J=H instanceof q?H.invert():H;return m1[Z]=J,J}}let W=!Y.pipe||!Q.includesTransform&&!X.includesTransform;if(W&&Q.equals(X))return Q;let G=W?h6(Q,X,Y):Q.hasKindIn(...h1)?iU(Q,X,Y):h6(Q,X,Y);if(N(G)){if(Q.equals(G))G=Q;else if(X.equals(G))G=X}return m1[Z]=G,G},h6=(Q,X,Y)=>{let U=Q.precedence<X.precedence?Q.kind:X.kind,Z=Q.impl.intersections[X.kind]??X.impl.intersections[Q.kind];if(Z===void 0)return null;else if(U===Q.kind)return Z(Q,X,Y);else{let W=Z(X,Q,{...Y,invert:!Y.invert});if(W instanceof q)W=W.invert();return W}},iU=(Q,X,Y)=>Q.includesTransform||X.includesTransform?Y.invert?S4(X,Q,Y):S4(Q,X,Y):h6(Q,X,Y),S4=(Q,X,Y)=>Q.distribute((U)=>sU(U,X,Y),(U)=>{let Z=U.filter(N);if(Z.length===0)return q.init("union",Q.branches,X.branches);if(Z.length<Q.branches.length||!Q.branches.every((_,H)=>_.rawIn.equals(Z[H].rawIn)))return Y.$.parseSchema(Z);let W;if(Z.length===1){let _=Z[0];if(!W)return _;return Y.$.node("morph",{..._.inner,in:_.rawIn.configure(W,"self")})}let G={branches:Z};if(W)G.meta=W;return Y.$.parseSchema(G)}),sU=(Q,X,Y)=>{if(Q.hasKind("morph")){let Z=[...Q.morphs];if(Q.lastMorphIfNode){let W=P(Q.lastMorphIfNode,X,Y);if(W instanceof q)return W;Z[Z.length-1]=W}else Z.push(X);return Y.$.node("morph",{morphs:Z,in:Q.inner.in})}if(X.hasKind("morph")){let Z=P(Q,X.rawIn,Y);if(Z instanceof q)return Z;return Y.$.node("morph",{morphs:[X],in:Z})}return Y.$.node("morph",{morphs:[X],in:Q})};class t extends M2{constructor(Q,X){super(Q,X);Object.defineProperty(this,x,{value:"constraint",enumerable:!1})}impliedSiblings;intersect(Q){return o(this,Q,this.$)}}class z1 extends t{traverseApply=(Q,X)=>{if(!this.traverseAllows(Q,X))X.errorFromNodeContext(this.errorContext)};compile(Q){if(Q.traversalKind==="Allows")Q.return(this.compiledCondition);else Q.if(this.compiledNegation,()=>Q.line(`ctx.errorFromNodeContext(${this.compiledErrorContext})`))}get errorContext(){return{code:this.kind,description:this.description,meta:this.meta,...this.inner}}get compiledErrorContext(){return R1(this.errorContext)}}var g=(Q)=>(X,Y)=>{if(K(X)){if(X.length===0)return;let Z=X.map((W)=>Y.$.node(Q,W));if(Q==="predicate")return Z;return Z.sort((W,G)=>W.hash<G.hash?-1:1)}let U=Y.$.node(Q,X);return U.hasOpenIntersection()?[U]:U},l1=(Q)=>{let X=Q.r.shift();if(!X){let U=Q.l.length===0&&Q.kind==="structure"?F.intrinsic.unknown.internal:Q.ctx.$.node(Q.kind,Object.assign(Q.baseInner,nU(Q.l)),{prereduced:!0});for(let Z of Q.roots){if(U instanceof q)return U;U=P(Z,U,Q.ctx)}return U}let Y=!1;for(let U=0;U<Q.l.length;U++){let Z=P(Q.l[U],X,Q.ctx);if(Z===null)continue;if(Z instanceof q)return Z;if(Z.isRoot())return Q.roots.push(Z),Q.l.splice(U),l1(Q);if(!Y)Q.l[U]=Z,Y=!0;else if(!Q.l.includes(Z))return C(`Unexpectedly encountered multiple distinct intersection results for refinement ${X}`)}if(!Y)Q.l.push(X);if(Q.kind==="intersection"){if(X.impliedSiblings)for(let U of X.impliedSiblings)G1(Q.r,U)}return l1(Q)},d1=(Q)=>{return Object.entries(Q).flatMap(([Y,U])=>(Y in d2)?U:[]).sort((Y,U)=>Y.precedence<U.precedence?-1:Y.precedence>U.precedence?1:Y.kind==="predicate"&&U.kind==="predicate"?0:Y.hash<U.hash?-1:1)},nU=(Q)=>{let X={};for(let Y of Q)if(Y.hasOpenIntersection())X[Y.kind]=R(X[Y.kind],Y);else{if(X[Y.kind])return C(`Unexpected intersection of closed refinements of kind ${Y.kind}`);X[Y.kind]=Y}return X},j4=(...Q)=>L(b4(...Q)),b4=(Q,X,Y)=>{let U=Y.hasKind("morph")?"a morph":Y.isUnknown()?"unknown":Y.exclude(X).defaultShortDescription;return`${Z4(Q)} operand must be ${X.description} (was ${U})`};var y4=(Q,X,Y)=>new C1(Q,X,Y,Y,null);class o2 extends l{}class C1 extends l{[x]="generic";paramDefs;bodyDef;$;arg$;baseInstantiation;hkt;description;constructor(Q,X,Y,U,Z){super((...W)=>{let G=V(this.names,(_,H)=>{let J=this.arg$.parse(W[_]);if(!J.extends(this.constraints[_]))L(rU(H,this.constraints[_].expression,J.expression));return[H,J]});if(this.defIsLazy()){let _=this.bodyDef(G);return this.$.parse(_)}return this.$.parse(X,{args:G})});this.paramDefs=Q,this.bodyDef=X,this.$=Y,this.arg$=U,this.hkt=Z,this.description=Z?new Z().description??`a generic type for ${Z.constructor.name}`:"a generic type",this.baseInstantiation=this(...this.constraints)}defIsLazy(){return this.bodyDef instanceof o2}cacheGetter(Q,X){return Object.defineProperty(this,Q,{value:X}),X}get json(){return this.cacheGetter("json",{params:this.params.map((Q)=>Q[1].isUnknown()?Q[0]:[Q[0],Q[1].json]),body:O4(this.bodyDef)})}get params(){return this.cacheGetter("params",this.paramDefs.map((Q)=>typeof Q==="string"?[Q,F.intrinsic.unknown]:[Q[0],this.$.parse(Q[1])]))}get names(){return this.cacheGetter("names",this.params.map((Q)=>Q[0]))}get constraints(){return this.cacheGetter("constraints",this.params.map((Q)=>Q[1]))}get internal(){return this}get referencesById(){return this.baseInstantiation.internal.referencesById}get references(){return this.baseInstantiation.internal.references}}var rU=(Q,X,Y)=>`${Q} must be assignable to ${X} (was ${Y})`;var tU=B({kind:"predicate",hasAssociatedError:!0,collapsibleKey:"predicate",keys:{predicate:{}},normalize:(Q)=>typeof Q==="function"?{predicate:Q}:Q,defaults:{description:(Q)=>`valid according to ${Q.predicate.name||"an anonymous predicate"}`},intersectionIsOpen:!0,intersections:{predicate:()=>null}});class f4 extends t{serializedPredicate=S(this.predicate);compiledCondition=`${this.serializedPredicate}(data, ctx)`;compiledNegation=`!${this.compiledCondition}`;impliedBasis=null;expression=this.serializedPredicate;traverseAllows=this.predicate;errorContext={code:"predicate",description:this.description,meta:this.meta};compiledErrorContext=R1(this.errorContext);traverseApply=(Q,X)=>{let Y=X.currentErrorCount;if(!this.predicate(Q,X.external)&&X.currentErrorCount===Y)X.errorFromNodeContext(this.errorContext)};compile(Q){if(Q.traversalKind==="Allows"){Q.return(this.compiledCondition);return}Q.initializeErrorCount(),Q.if(`${this.compiledNegation} && ctx.currentErrorCount === errorCount`,()=>Q.line(`ctx.errorFromNodeContext(${this.compiledErrorContext})`))}reduceJsonSchema(Q,X){return X.fallback.predicate({code:"predicate",base:Q,predicate:this.predicate})}}var p6={implementation:tU,Node:f4};var aU=B({kind:"divisor",collapsibleKey:"rule",keys:{rule:{parse:(Q)=>Number.isInteger(Q)?Q:L(eU(Q))}},normalize:(Q)=>typeof Q==="number"?{rule:Q}:Q,hasAssociatedError:!0,defaults:{description:(Q)=>Q.rule===1?"an integer":Q.rule===2?"even":`a multiple of ${Q.rule}`},intersections:{divisor:(Q,X,Y)=>Y.$.node("divisor",{rule:Math.abs(Q.rule*X.rule/QZ(Q.rule,X.rule))})},obviatesBasisDescription:!0});class v4 extends z1{traverseAllows=(Q)=>Q%this.rule===0;compiledCondition=`data % ${this.rule} === 0`;compiledNegation=`data % ${this.rule} !== 0`;impliedBasis=F.intrinsic.number.internal;expression=`% ${this.rule}`;reduceJsonSchema(Q){if(Q.type="integer",this.rule===1)return Q;return Q.multipleOf=this.rule,Q}}var u6={implementation:aU,Node:v4};var eU=(Q)=>`divisor must be an integer (was ${Q})`,QZ=(Q,X)=>{let Y,U=Q,Z=X;while(Z!==0)Y=Z,Z=U%Z,U=Y;return U};class s extends z1{boundOperandKind=ZZ[this.kind];compiledActual=this.boundOperandKind==="value"?"data":this.boundOperandKind==="length"?"data.length":"data.valueOf()";comparator=WZ(this.kind,this.exclusive);numericLimit=this.rule.valueOf();expression=`${this.comparator} ${this.rule}`;compiledCondition=`${this.compiledActual} ${this.comparator} ${this.numericLimit}`;compiledNegation=`${this.compiledActual} ${XZ[this.comparator]} ${this.numericLimit}`;stringLimit=this.boundOperandKind==="date"?GZ(this.numericLimit):`${this.numericLimit}`;limitKind=this.comparator["0"]==="<"?"upper":"lower";isStricterThan(Q){return(this.limitKind==="upper"?this.numericLimit<Q.numericLimit:this.numericLimit>Q.numericLimit)||this.numericLimit===Q.numericLimit&&this.exclusive===!0&&!Q.exclusive}overlapsRange(Q){if(this.isStricterThan(Q))return!1;if(this.numericLimit===Q.numericLimit&&(this.exclusive||Q.exclusive))return!1;return!0}overlapIsUnit(Q){return this.numericLimit===Q.numericLimit&&!this.exclusive&&!Q.exclusive}}var XZ={"<":">=","<=":">",">":"<=",">=":"<"},YZ={min:"max",minLength:"maxLength",after:"before"},i2={parse:(Q)=>Q||void 0},s2=(Q)=>(X)=>{if(typeof X==="number")return{rule:X};let{exclusive:Y,...U}=X;return Y?{...U,rule:Q==="minLength"?U.rule+1:U.rule-1}:U},n2=(Q)=>(X)=>{if(typeof X==="number"||typeof X==="string"||X instanceof Date)return{rule:X};let{exclusive:Y,...U}=X;if(!Y)return U;let Z=typeof U.rule==="number"?U.rule:typeof U.rule==="string"?new Date(U.rule).valueOf():U.rule.valueOf();return Y?{...U,rule:Q==="after"?Z+1:Z-1}:U},r2=(Q)=>typeof Q==="string"||typeof Q==="number"?new Date(Q):Q,UZ=(Q,X)=>`${Q} bound must be a positive integer (was ${X})`,c1=(Q)=>(X)=>{if(!Number.isInteger(X)||X<0)L(UZ(Q,X));return X},ZZ={min:"value",max:"value",minLength:"length",maxLength:"length",after:"date",before:"date"},WZ=(Q,X)=>`${f(Q,YZ)?">":"<"}${X?"":"="}`,GZ=(Q)=>typeof Q==="string"?Q:new Date(Q).toLocaleString(),k4=(Q)=>`Bounded expression ${Q} must be exactly one of number, string, Array, or Date`;var _Z=B({kind:"after",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{parse:r2,serialize:(Q)=>Q.toISOString()}},normalize:n2("after"),defaults:{description:(Q)=>`${Q.collapsibleLimitString} or later`,actual:j1},intersections:{after:(Q,X)=>Q.isStricterThan(X)?Q:X}});class g4 extends s{impliedBasis=F.intrinsic.Date.internal;collapsibleLimitString=j1(this.rule);traverseAllows=(Q)=>Q>=this.rule;reduceJsonSchema(Q,X){return X.fallback.date({code:"date",base:Q,after:this.rule})}}var m6={implementation:_Z,Node:g4};var JZ=B({kind:"before",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{parse:r2,serialize:(Q)=>Q.toISOString()}},normalize:n2("before"),defaults:{description:(Q)=>`${Q.collapsibleLimitString} or earlier`,actual:j1},intersections:{before:(Q,X)=>Q.isStricterThan(X)?Q:X,after:(Q,X,Y)=>Q.overlapsRange(X)?Q.overlapIsUnit(X)?Y.$.node("unit",{unit:Q.rule}):null:q.init("range",Q,X)}});class x4 extends s{collapsibleLimitString=j1(this.rule);traverseAllows=(Q)=>Q<=this.rule;impliedBasis=F.intrinsic.Date.internal;reduceJsonSchema(Q,X){return X.fallback.date({code:"date",base:Q,before:this.rule})}}var l6={implementation:JZ,Node:x4};var LZ=B({kind:"exactLength",collapsibleKey:"rule",keys:{rule:{parse:c1("exactLength")}},normalize:(Q)=>typeof Q==="number"?{rule:Q}:Q,hasAssociatedError:!0,defaults:{description:(Q)=>`exactly length ${Q.rule}`,actual:(Q)=>`${Q.length}`},intersections:{exactLength:(Q,X,Y)=>q.init("unit",Y.$.node("unit",{unit:Q.rule}),Y.$.node("unit",{unit:X.rule}),{path:["length"]}),minLength:(Q,X)=>Q.rule>=X.rule?Q:q.init("range",Q,X),maxLength:(Q,X)=>Q.rule<=X.rule?Q:q.init("range",Q,X)}});class h4 extends z1{traverseAllows=(Q)=>Q.length===this.rule;compiledCondition=`data.length === ${this.rule}`;compiledNegation=`data.length !== ${this.rule}`;impliedBasis=F.intrinsic.lengthBoundable.internal;expression=`== ${this.rule}`;reduceJsonSchema(Q){switch(Q.type){case"string":return Q.minLength=this.rule,Q.maxLength=this.rule,Q;case"array":return Q.minItems=this.rule,Q.maxItems=this.rule,Q;default:return E.throwInternalOperandError("exactLength",Q)}}}var d6={implementation:LZ,Node:h4};var HZ=B({kind:"max",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{},exclusive:i2},normalize:(Q)=>typeof Q==="number"?{rule:Q}:Q,defaults:{description:(Q)=>{if(Q.rule===0)return Q.exclusive?"negative":"non-positive";return`${Q.exclusive?"less than":"at most"} ${Q.rule}`}},intersections:{max:(Q,X)=>Q.isStricterThan(X)?Q:X,min:(Q,X,Y)=>Q.overlapsRange(X)?Q.overlapIsUnit(X)?Y.$.node("unit",{unit:Q.rule}):null:q.init("range",Q,X)},obviatesBasisDescription:!0});class p4 extends s{impliedBasis=F.intrinsic.number.internal;traverseAllows=this.exclusive?(Q)=>Q<this.rule:(Q)=>Q<=this.rule;reduceJsonSchema(Q){if(this.exclusive)Q.exclusiveMaximum=this.rule;else Q.maximum=this.rule;return Q}}var c6={implementation:HZ,Node:p4};var FZ=B({kind:"maxLength",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{parse:c1("maxLength")}},reduce:(Q,X)=>Q.rule===0?X.node("exactLength",Q):void 0,normalize:s2("maxLength"),defaults:{description:(Q)=>`at most length ${Q.rule}`,actual:(Q)=>`${Q.length}`},intersections:{maxLength:(Q,X)=>Q.isStricterThan(X)?Q:X,minLength:(Q,X,Y)=>Q.overlapsRange(X)?Q.overlapIsUnit(X)?Y.$.node("exactLength",{rule:Q.rule}):null:q.init("range",Q,X)}});class u4 extends s{impliedBasis=F.intrinsic.lengthBoundable.internal;traverseAllows=(Q)=>Q.length<=this.rule;reduceJsonSchema(Q){switch(Q.type){case"string":return Q.maxLength=this.rule,Q;case"array":return Q.maxItems=this.rule,Q;default:return E.throwInternalOperandError("maxLength",Q)}}}var o6={implementation:FZ,Node:u4};var qZ=B({kind:"min",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{},exclusive:i2},normalize:(Q)=>typeof Q==="number"?{rule:Q}:Q,defaults:{description:(Q)=>{if(Q.rule===0)return Q.exclusive?"positive":"non-negative";return`${Q.exclusive?"more than":"at least"} ${Q.rule}`}},intersections:{min:(Q,X)=>Q.isStricterThan(X)?Q:X},obviatesBasisDescription:!0});class m4 extends s{impliedBasis=F.intrinsic.number.internal;traverseAllows=this.exclusive?(Q)=>Q>this.rule:(Q)=>Q>=this.rule;reduceJsonSchema(Q){if(this.exclusive)Q.exclusiveMinimum=this.rule;else Q.minimum=this.rule;return Q}}var i6={implementation:qZ,Node:m4};var $Z=B({kind:"minLength",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{parse:c1("minLength")}},reduce:(Q)=>Q.rule===0?F.intrinsic.unknown:void 0,normalize:s2("minLength"),defaults:{description:(Q)=>Q.rule===1?"non-empty":`at least length ${Q.rule}`,actual:(Q)=>Q.length===0?"":`${Q.length}`},intersections:{minLength:(Q,X)=>Q.isStricterThan(X)?Q:X}});class l4 extends s{impliedBasis=F.intrinsic.lengthBoundable.internal;traverseAllows=(Q)=>Q.length>=this.rule;reduceJsonSchema(Q){switch(Q.type){case"string":return Q.minLength=this.rule,Q;case"array":return Q.minItems=this.rule,Q;default:return E.throwInternalOperandError("minLength",Q)}}}var s6={implementation:$Z,Node:l4};var d4={min:i6.implementation,max:c6.implementation,minLength:s6.implementation,maxLength:o6.implementation,exactLength:d6.implementation,after:m6.implementation,before:l6.implementation},c4={min:i6.Node,max:c6.Node,minLength:s6.Node,maxLength:o6.Node,exactLength:d6.Node,after:m6.Node,before:l6.Node};var AZ=B({kind:"pattern",collapsibleKey:"rule",keys:{rule:{},flags:{}},normalize:(Q)=>typeof Q==="string"?{rule:Q}:Q instanceof RegExp?Q.flags?{rule:Q.source,flags:Q.flags}:{rule:Q.source}:Q,obviatesBasisDescription:!0,obviatesBasisExpression:!0,hasAssociatedError:!0,intersectionIsOpen:!0,defaults:{description:(Q)=>`matched by ${Q.rule}`},intersections:{pattern:()=>null}});class o4 extends z1{instance=new RegExp(this.rule,this.flags);expression=`${this.instance}`;traverseAllows=this.instance.test.bind(this.instance);compiledCondition=`${this.expression}.test(data)`;compiledNegation=`!${this.compiledCondition}`;impliedBasis=F.intrinsic.string.internal;reduceJsonSchema(Q,X){if(Q.pattern)return X.fallback.patternIntersection({code:"patternIntersection",base:Q,pattern:this.rule});return Q.pattern=this.rule,Q}}var n6={implementation:AZ,Node:o4};var D2=(Q,X)=>{let Y=zZ(Q);if(X&&!X.includes(Y))return L(`Root of kind ${Y} should be one of ${X}`);return Y},zZ=(Q)=>{if(A(Q,"root"))return Q.kind;if(typeof Q==="string")return Q[0]==="$"?"alias":(Q in u)?"domain":"proto";if(typeof Q==="function")return"proto";if(typeof Q!=="object"||Q===null)return L(i4(Q));if("morphs"in Q)return"morph";if("branches"in Q||K(Q))return"union";if("unit"in Q)return"unit";if("reference"in Q)return"alias";let X=Object.keys(Q);if(X.length===0||X.some((Y)=>(Y in d2)))return"intersection";if("proto"in Q)return"proto";if("domain"in Q)return"domain";return L(i4(Q))},i4=(Q)=>`${T(Q)} is not a valid type schema`,s4={},OZ=(Q)=>K(Q)?Q.map((X)=>X.collapsibleJson):Q.collapsibleJson,h={};F.nodesByRegisteredId=h;var r6=(Q)=>{return s4[Q]??=0,`${Q}${++s4[Q]}`},t6=(Q)=>{let X=o1[Q.kind],Y=X.applyConfig?.(Q.def,Q.$.resolvedConfig)??Q.def,U={},{meta:Z,...W}=Y,G=Z===void 0?{}:typeof Z==="string"?{description:Z}:Z,_=M6(W).sort(([J],[$])=>p1(J)?p1($)?u1(J)-u1($):1:p1($)?-1:J<$?-1:1).filter(([J,$])=>{if(J.startsWith("meta.")){let O=J.slice(5);return G[O]=$,!1}return!0});for(let J of _){let $=J[0],O=X.keys[$];if(!O)return L(`Key ${$} is not valid on ${Q.kind} schema`);let D=O.parse?O.parse(J[1],Q):J[1];if(D!==m&&(D!==void 0||O.preserveUndefined))U[$]=D}if(X.reduce&&!Q.prereduced){let J=X.reduce(U,Q.$);if(J){if(J instanceof q)return J.throw();return VZ(J,G)}}return a6({id:Q.id,kind:Q.kind,inner:U,meta:G,$:Q.$})},a6=({id:Q,kind:X,inner:Y,meta:U,$:Z,ignoreCache:W})=>{let G=o1[X],_=M6(Y),H=[],J={};for(let[W1,f1]of _){let X2=G.keys[W1],UU=X2.serialize??(X2.child?OZ:r);if(J[W1]=UU(f1),X2.child===!0){let z6=f1;if(K(z6))H.push(...z6);else H.push(z6)}else if(typeof X2.child==="function")H.push(...X2.child(f1))}if(G.finalizeInnerJson)J=G.finalizeInnerJson(J);let $={...J},O={};if(!_1(U))O=V(U,(W1,f1)=>[W1,W1==="examples"?f1:r(f1)]),$.meta=t2(O,"description",!0);J=t2(J,G.collapsibleKey,!1);let D=JSON.stringify({kind:X,...J});$=t2($,G.collapsibleKey,!1);let b=t2($,G.collapsibleKey,!0),H1=JSON.stringify({kind:X,...$});if(Z.nodesByHash[H1]&&!W)return Z.nodesByHash[H1];let kQ={id:Q,kind:X,impl:G,inner:Y,innerEntries:_,innerJson:J,innerHash:D,meta:U,metaJson:O,json:$,hash:H1,collapsibleJson:b,children:H};if(X!=="intersection"){for(let W1 in Y)if(W1!=="in"&&W1!=="out")kQ[W1]=Y[W1]}let YU=new r4[X](kQ,Z);return Z.nodesByHash[H1]=YU},n4=(Q,X)=>{if(Q.id===X)return Q;if(N(h[X]))C(`Unexpected attempt to overwrite node id ${X}`);return a6({id:X,kind:Q.kind,inner:Q.inner,meta:Q.meta,$:Q.$,ignoreCache:!0})},VZ=(Q,X,Y)=>{if(Y&&N(h[Y]))C(`Unexpected attempt to overwrite node id ${Y}`);return a6({id:Y??r6(X.alias??Q.kind),kind:Q.kind,inner:Q.inner,meta:X,$:Q.$})},t2=(Q,X,Y)=>{let U=Object.keys(Q);if(U.length===1&&U[0]===X){let Z=Q[X];if(Y)return Z;if(p(Z,"object")&&(Object.keys(Z).length===1||Array.isArray(Z)))return Z}return Q};var C2=(Q,X,Y)=>{if(Q.key!==X.key)return null;let U=Q.key,Z=P(Q.value,X.value,Y),W=Q.required||X.required?"required":"optional";if(Z instanceof q)if(W==="optional")Z=F.intrinsic.never.internal;else return Z.withPrefixKey(Q.key,Q.required&&X.required?"required":"optional");if(W==="required")return Y.$.node("required",{key:U,value:Z});let G=Q.hasDefault()?X.hasDefault()?Q.default===X.default?Q.default:L(e6(Q.default,X.default)):Q.default:X.hasDefault()?X.default:m;return Y.$.node("optional",{key:U,value:Z,default:G})};class w2 extends t{required=this.kind==="required";optional=this.kind==="optional";impliedBasis=F.intrinsic.object.internal;serializedKey=Y1(this.key);compiledKey=typeof this.key==="string"?this.key:this.serializedKey;flatRefs=R(this.value.flatRefs.map((Q)=>Z1([this.key,...Q.path],Q.node)),Z1([this.key],this.value));_transform(Q,X){X.path.push(this.key);let Y=super._transform(Q,X);return X.path.pop(),Y}hasDefault(){return"default"in this.inner}traverseAllows=(Q,X)=>{if(this.key in Q)return c(this.key,()=>this.value.traverseAllows(Q[this.key],X),X);return this.optional};traverseApply=(Q,X)=>{if(this.key in Q)c(this.key,()=>this.value.traverseApply(Q[this.key],X),X);else if(this.hasKind("required"))X.errorFromNodeContext(this.errorContext)};compile(Q){if(Q.if(`${this.serializedKey} in data`,()=>Q.traverseKey(this.serializedKey,`data${Q.prop(this.key)}`,this.value)),this.hasKind("required"))Q.else(()=>Q.traversalKind==="Apply"?Q.line(`ctx.errorFromNodeContext(${this.compiledErrorContext})`):Q.return(!1));if(Q.traversalKind==="Allows")Q.return(!0)}}var e6=(Q,X)=>`Invalid intersection of default values ${T(Q)} & ${T(X)}`;var TZ=B({kind:"optional",hasAssociatedError:!1,intersectionIsOpen:!0,keys:{key:{},value:{child:!0,parse:(Q,X)=>X.$.parseSchema(Q)},default:{preserveUndefined:!0}},normalize:(Q)=>Q,reduce:(Q,X)=>{if(X.resolvedConfig.exactOptionalPropertyTypes===!1){if(!Q.value.allows(void 0))return X.node("optional",{...Q,value:Q.value.or(z.undefined)},{prereduced:!0})}},defaults:{description:(Q)=>`${Q.compiledKey}?: ${Q.value.description}`},intersections:{optional:C2}});class t4 extends w2{constructor(...Q){super(...Q);if("default"in this.inner)N2(this.value,this.inner.default,this.key)}get rawIn(){let Q=super.rawIn;if(!this.hasDefault())return Q;return this.$.node("optional",g2(Q.inner,{default:!0}),{prereduced:!0})}get outProp(){if(!this.hasDefault())return this;let{default:Q,...X}=this.inner;return this.cacheGetter("outProp",this.$.node("required",X,{prereduced:!0}))}expression=this.hasDefault()?`${this.compiledKey}: ${this.value.expression} = ${T(this.inner.default)}`:`${this.compiledKey}?: ${this.value.expression}`;defaultValueMorph=MZ(this);defaultValueMorphRef=this.defaultValueMorph&&S(this.defaultValueMorph)}var K2={implementation:TZ,Node:t4},BZ={},MZ=(Q)=>{if(!Q.hasDefault())return;let X=`{${Q.compiledKey}: ${Q.value.id} = ${r(Q.default)}}`;return BZ[X]??=QQ(Q.key,Q.value,Q.default)},QQ=(Q,X,Y)=>{if(typeof Y==="function")return X.includesTransform?(Z,W)=>{return c(Q,()=>X(Z[Q]=Y(),W),W),Z}:(Z)=>{return Z[Q]=Y(),Z};let U=X.includesTransform?X.assert(Y):Y;return p(U,"object")?(Z,W)=>{return c(Q,()=>X(Z[Q]=Y,W),W),Z}:(Z)=>{return Z[Q]=U,Z}},N2=(Q,X,Y)=>{let U=T1(X);if(p(X,"object")&&!U)L(RZ(Y));let Z=Q.in(U?X():X);if(Z instanceof d){if(Y===null)L(`Default ${Z.summary}`);let W=Z.transform((G)=>G.transform((_)=>({..._,prefixPath:[Y]})));L(`Default for ${W.summary}`)}return X},RZ=(Q)=>{return`Non-primitive default ${Q===null?"":typeof Q==="number"?`for value at [${Q}] `:`for ${Y1(Q)} `}must be specified as a function like () => ({my: 'object'})`};class a extends M2{constructor(Q,X){super(Q,X);Object.defineProperty(this,x,{value:"root",enumerable:!1})}get rawIn(){return super.rawIn}get rawOut(){return super.rawOut}get internal(){return this}get "~standard"(){return{vendor:"arktype",version:1,validate:(Q)=>{let X=this(Q);if(X instanceof d)return X;return{value:X}},jsonSchema:{input:(Q)=>this.rawIn.toJsonSchema({target:a4(Q.target),...Q.libraryOptions}),output:(Q)=>this.rawOut.toJsonSchema({target:a4(Q.target),...Q.libraryOptions})}}}as(){return this}brand(Q){if(Q==="")return L(DZ);return this}readonly(){return this}branches=this.hasKind("union")?this.inner.branches:[this];distribute(Q,X){let Y=this.branches.map(Q);return X?.(Y)??Y}get shortDescription(){return this.meta.description??this.defaultShortDescription}toJsonSchema(Q={}){let X=f6(this.$.resolvedConfig.toJsonSchema,Q);X.useRefs||=this.isCyclic;let Y=typeof X.dialect==="string"?{$schema:X.dialect}:{};if(Object.assign(Y,this.toJsonSchemaRecurse(X)),X.useRefs){let U=V(this.references,(Z,W)=>W.isRoot()&&!W.alwaysExpandJsonSchema?[W.id,W.toResolvedJsonSchema(X)]:[]);if(X.target==="draft-07")Object.assign(Y,{definitions:U});else Y.$defs=U}return Y}toJsonSchemaRecurse(Q){if(Q.useRefs&&!this.alwaysExpandJsonSchema)return{$ref:`#/${Q.target==="draft-07"?"definitions":"$defs"}/${this.id}`};return this.toResolvedJsonSchema(Q)}get alwaysExpandJsonSchema(){return this.isBasis()||this.kind==="alias"||this.hasKind("union")&&this.isBoolean}toResolvedJsonSchema(Q){let X=this.innerToJsonSchema(Q);return Object.assign(X,this.metaJson)}intersect(Q){let X=this.$.parseDefinition(Q),Y=this.rawIntersect(X);if(Y instanceof q)return Y;return this.$.finalize(Y)}rawIntersect(Q){return o(this,Q,this.$)}toNeverIfDisjoint(){return this}and(Q){let X=this.intersect(Q);return X instanceof q?X.throw():X}rawAnd(Q){let X=this.rawIntersect(Q);return X instanceof q?X.throw():X}or(Q){let X=this.$.parseDefinition(Q);return this.$.finalize(this.rawOr(X))}rawOr(Q){let X=[...this.branches,...Q.branches];return this.$.node("union",X)}map(Q){return this.$.schema(this.applyStructuralOperation("map",[Q]))}pick(...Q){return this.$.schema(this.applyStructuralOperation("pick",Q))}omit(...Q){return this.$.schema(this.applyStructuralOperation("omit",Q))}required(){return this.$.schema(this.applyStructuralOperation("required",[]))}partial(){return this.$.schema(this.applyStructuralOperation("partial",[]))}_keyof;keyof(){if(this._keyof)return this._keyof;let Q=this.applyStructuralOperation("keyof",[]).reduce((X,Y)=>X.intersect(Y).toNeverIfDisjoint(),F.intrinsic.unknown.internal);if(Q.branches.length===0)L(x6(`keyof ${this.expression}`));return this._keyof=this.$.finalize(Q)}get props(){if(this.branches.length!==1)return L(wZ(this.expression));return[...this.applyStructuralOperation("props",[])[0]]}merge(Q){let X=this.$.parseDefinition(Q);return this.$.schema(X.distribute((Y)=>this.applyStructuralOperation("merge",[e4(Y)??L(QX("merge",Y.expression))])))}applyStructuralOperation(Q,X){return this.distribute((Y)=>{if(Y.equals(F.intrinsic.object)&&Q!=="merge")return Y;let U=e4(Y);if(!U)L(QX(Q,Y.expression));if(Q==="keyof")return U.keyof();if(Q==="get")return U.get(...X);if(Q==="props")return U.props;let Z=Q==="required"?"require":Q==="partial"?"optionalize":Q;return this.$.node("intersection",{domain:"object",structure:U[Z](...X)})})}get(...Q){if(Q[0]===void 0)return this;return this.$.schema(this.applyStructuralOperation("get",Q))}extract(Q){let X=this.$.parseDefinition(Q);return this.$.schema(this.branches.filter((Y)=>Y.extends(X)))}exclude(Q){let X=this.$.parseDefinition(Q);return this.$.schema(this.branches.filter((Y)=>!Y.extends(X)))}array(){return this.$.schema(this.isUnknown()?{proto:Array}:{proto:Array,sequence:this},{prereduced:!0})}overlaps(Q){return!(this.intersect(Q)instanceof q)}extends(Q){if(this.isNever())return!0;let X=this.intersect(Q);return!(X instanceof q)&&this.equals(X)}ifExtends(Q){return this.extends(Q)?this:void 0}subsumes(Q){return this.$.parseDefinition(Q).extends(this)}configure(Q,X="shallow"){return this.configureReferences(Q,X)}describe(Q,X="shallow"){return this.configure({description:Q},X)}optional(){return[this,"?"]}default(Q){return N2(this,Q,null),[this,"=",Q]}from(Q){return this.assert(Q)}_pipe(...Q){let X=Q.reduce((Y,U)=>Y.rawPipeOnce(U),this);return this.$.finalize(X)}tryPipe(...Q){let X=Q.reduce((Y,U)=>Y.rawPipeOnce(A(U,"root")?U:(Z,W)=>{try{return U(Z,W)}catch(G){return W.error({code:"predicate",predicate:U,actual:`aborted due to error:
|
|
20
|
+
`);class U1{path=[];errors=new d(this);root;config;queuedMorphs=[];branches=[];seen={};constructor(Q,X){this.root=Q,this.config=X}get data(){let Q=this.root;for(let X of this.path)Q=Q?.[X];return Q}get propString(){return z1(this.path)}reject(Q){return this.error(Q),!1}mustBe(Q){return this.error(Q),!1}error(Q){let X=typeof Q==="object"?Q.code?Q:{...Q,code:"predicate"}:{code:"predicate",expected:Q};return this.errorFromContext(X)}hasError(){return this.currentErrorCount!==0}get currentBranch(){return this.branches[this.branches.length-1]}queueMorphs(Q){let X={path:new z2(...this.path),morphs:Q};if(this.currentBranch)this.currentBranch.queuedMorphs.push(X);else this.queuedMorphs.push(X)}finalize(Q){if(this.queuedMorphs.length){if(typeof this.root==="object"&&this.root!==null&&this.config.clone)this.root=this.config.clone(this.root);this.applyQueuedMorphs()}if(this.hasError())return Q?Q(this.errors):this.errors;return this.root}get currentErrorCount(){return this.currentBranch?this.currentBranch.error?1:0:this.errors.count}get failFast(){return this.branches.length!==0}pushBranch(){this.branches.push({error:void 0,queuedMorphs:[]})}popBranch(){return this.branches.pop()}get external(){return this}errorFromNodeContext(Q){return this.errorFromContext(Q)}errorFromContext(Q){let X=new C1(Q,this);if(this.currentBranch)this.currentBranch.error=X;else this.errors.add(X);return X}applyQueuedMorphs(){while(this.queuedMorphs.length){let Q=this.queuedMorphs;this.queuedMorphs=[];for(let{path:X,morphs:Y}of Q){if(this.errors.affectsPath(X))continue;this.applyMorphsAtPath(X,Y)}}}applyMorphsAtPath(Q,X){let Y=Q[Q.length-1],U;if(Y!==void 0){U=this.root;for(let Z=0;Z<Q.length-1;Z++)U=U[Q[Z]]}for(let Z of X){this.path=[...Q];let W=P(Z),G=Z(U===void 0?this.root:U[Y],this);if(G instanceof C1){if(!this.errors.includes(G))this.errors.add(G);break}if(G instanceof d){if(!W)this.errors.merge(G);this.queuedMorphs=[];break}if(U===void 0)this.root=G;else U[Y]=G;this.applyQueuedMorphs()}}}var c=(Q,X,Y)=>{if(!Y)return X();Y.path.push(Q);let U=X();return Y.path.pop(),U};class T2 extends l{attachments;$;onFail;includesTransform;includesContextualPredicate;isCyclic;allowsRequiresContext;rootApplyStrategy;contextFreeMorph;rootApply;referencesById;shallowReferences;flatRefs;flatMorphs;allows;get shallowMorphs(){return[]}constructor(Q,X){super((U,Z,W=this.onFail)=>{if(Z)return this.traverseApply(U,Z),Z.hasError()?Z.errors:Z.data;return this.rootApply(U,W)},{attach:Q});this.attachments=Q,this.$=X,this.onFail=this.meta.onFail??this.$.resolvedConfig.onFail,this.includesTransform=this.hasKind("morph")||this.hasKind("structure")&&this.structuralMorph!==void 0||this.hasKind("sequence")&&this.inner.defaultables!==void 0,this.includesContextualPredicate=this.hasKind("predicate")&&this.inner.predicate.length!==1,this.isCyclic=this.kind==="alias",this.referencesById={[this.id]:this},this.shallowReferences=this.hasKind("structure")?[this,...this.children]:this.children.reduce((U,Z)=>sU(U,Z.shallowReferences),[this]);let Y=this.isStructural();this.flatRefs=[],this.flatMorphs=[];for(let U=0;U<this.children.length;U++){if(this.includesTransform||=this.children[U].includesTransform,this.includesContextualPredicate||=this.children[U].includesContextualPredicate,this.isCyclic||=this.children[U].isCyclic,!Y){let Z=this.children[U].flatRefs;for(let W=0;W<Z.length;W++){let G=Z[W];if(!this.flatRefs.some((_)=>S4(_,G))){this.flatRefs.push(G);for(let _ of G.node.branches)if(_.hasKind("morph")||_.hasKind("intersection")&&_.structure?.structuralMorph!==void 0)this.flatMorphs.push({path:G.path,propString:G.propString,node:_})}}}Object.assign(this.referencesById,this.children[U].referencesById)}this.flatRefs.sort((U,Z)=>U.path.length>Z.path.length?1:U.path.length<Z.path.length?-1:U.propString>Z.propString?1:U.propString<Z.propString?-1:U.node.expression<Z.node.expression?-1:1),this.allowsRequiresContext=this.includesContextualPredicate||this.isCyclic,this.rootApplyStrategy=!this.allowsRequiresContext&&this.flatMorphs.length===0?this.shallowMorphs.length===0?"allows":this.shallowMorphs.every((U)=>U.length===1||U.name==="$arkStructuralMorph")?this.hasKind("union")?this.branches.some((U)=>U.shallowMorphs.length>1)?"contextual":"branchedOptimistic":this.shallowMorphs.length>1?"contextual":"optimistic":"contextual":"contextual",this.rootApply=this.createRootApply(),this.allows=this.allowsRequiresContext?(U)=>this.traverseAllows(U,new U1(U,this.$.resolvedConfig)):(U)=>this.traverseAllows(U)}createRootApply(){switch(this.rootApplyStrategy){case"allows":return(X,Y)=>{if(this.allows(X))return X;let U=new U1(X,this.$.resolvedConfig);return this.traverseApply(X,U),U.finalize(Y)};case"contextual":return(X,Y)=>{let U=new U1(X,this.$.resolvedConfig);return this.traverseApply(X,U),U.finalize(Y)};case"optimistic":this.contextFreeMorph=this.shallowMorphs[0];let Q=this.$.resolvedConfig.clone;return(X,Y)=>{if(this.allows(X))return this.contextFreeMorph(Q&&(typeof X==="object"&&X!==null||typeof X==="function")?Q(X):X);let U=new U1(X,this.$.resolvedConfig);return this.traverseApply(X,U),U.finalize(Y)};case"branchedOptimistic":return this.createBranchedOptimisticRootApply();default:return this.rootApplyStrategy,C(`Unexpected rootApplyStrategy ${this.rootApplyStrategy}`)}}compiledMeta=iU(this.metaJson);cacheGetter(Q,X){return Object.defineProperty(this,Q,{value:X}),X}get description(){return this.cacheGetter("description",this.meta?.description??this.$.resolvedConfig[this.kind].description(this))}get references(){return Object.values(this.referencesById)}precedence=u1(this.kind);precompilation;assert=(Q,X)=>this(Q,X,(Y)=>Y.throw());traverse(Q,X){return this(Q,X,null)}get in(){return this.cacheGetter("in",this.rawIn.isRoot()?this.$.finalize(this.rawIn):this.rawIn)}get rawIn(){return this.cacheGetter("rawIn",this.getIo("in"))}get out(){return this.cacheGetter("out",this.rawOut.isRoot()?this.$.finalize(this.rawOut):this.rawOut)}get rawOut(){return this.cacheGetter("rawOut",this.getIo("out"))}getIo(Q){if(!this.includesTransform)return this;let X={};for(let[Y,U]of this.innerEntries){let Z=this.impl.keys[Y];if(Z.reduceIo)Z.reduceIo(Q,X,U);else if(Z.child){let W=U;X[Y]=K(W)?W.map((G)=>Q==="in"?G.rawIn:G.rawOut):Q==="in"?W.rawIn:W.rawOut}else X[Y]=U}return this.$.node(this.kind,X)}toJSON(){return this.json}toString(){return`Type<${this.expression}>`}equals(Q){let X=P(Q)?Q:this.$.parseDefinition(Q);return this.innerHash===X.innerHash}ifEquals(Q){return this.equals(Q)?this:void 0}hasKind(Q){return this.kind===Q}assertHasKind(Q){if(this.kind!==Q)P1(`${this.kind} node was not of asserted kind ${Q}`);return this}hasKindIn(...Q){return Q.includes(this.kind)}assertHasKindIn(...Q){if(!n(Q,this.kind))P1(`${this.kind} node was not one of asserted kinds ${Q}`);return this}isBasis(){return n(C4,this.kind)}isConstraint(){return n(d2,this.kind)}isStructural(){return n(x1,this.kind)}isRefinement(){return n(f6,this.kind)}isRoot(){return n(h1,this.kind)}isUnknown(){return this.hasKind("intersection")&&this.children.length===0}isNever(){return this.hasKind("union")&&this.children.length===0}hasUnit(Q){return this.hasKind("unit")&&this.allows(Q)}hasOpenIntersection(){return this.impl.intersectionIsOpen}get nestableExpression(){return this.expression}select(Q){let X=M2.normalize(Q);return this._select(X)}_select(Q){let X=M2.applyBoundary[Q.boundary??"references"](this);if(Q.kind)X=X.filter((Y)=>Y.kind===Q.kind);if(Q.where)X=X.filter(Q.where);return M2.applyMethod[Q.method??"filter"](X,this,Q)}transform(Q,X){return this._transform(Q,this._createTransformContext(X))}_createTransformContext(Q){return{root:this,selected:void 0,seen:{},path:[],parseOptions:{prereduced:Q?.prereduced??!1},undeclaredKeyHandling:void 0,...Q}}_transform(Q,X){let Y=X.bindScope??this.$;if(X.seen[this.id])return this.$.lazilyResolve(X.seen[this.id]);if(X.shouldTransform?.(this,X)===!1)return this;let U;if(X.seen[this.id]=()=>U,this.hasKind("structure")&&this.undeclared!==X.undeclaredKeyHandling)X={...X,undeclaredKeyHandling:this.undeclared};let Z=V(this.inner,(J,$)=>{if(!this.impl.keys[J].child)return[J,$];let O=$;if(!K(O)){let b=O._transform(Q,X);return b?[J,b]:[]}if(O.length===0)return[J,$];let R=O.flatMap((b)=>{return b._transform(Q,X)??[]});return R.length?[J,R]:[]});delete X.seen[this.id];let W=Object.assign(Z,{meta:this.meta}),G=X.selected&&!X.selected.includes(this)?W:Q(this.kind,W,X);if(G===null)return null;if(P(G))return U=G;let _=Object.keys(G);if((_.length===0||_.length===1&&_[0]==="meta")&&!J1(this.inner))return null;if((this.kind==="required"||this.kind==="optional"||this.kind==="index")&&!("value"in G))return X.undeclaredKeyHandling?{...G,value:F.intrinsic.unknown}:null;if(this.kind==="morph")G.in??=F.intrinsic.unknown;return U=Y.node(this.kind,G,X.parseOptions)}configureReferences(Q,X="references"){let Y=M2.normalize(X),U=typeof Q==="string"?(_,H)=>({...H,meta:{...H.meta,description:Q}}):typeof Q==="function"?(_,H)=>({...H,meta:Q(H.meta)}):(_,H)=>({...H,meta:{...H.meta,...Q}});if(Y.boundary==="self")return this.$.node(this.kind,U(this.kind,{...this.inner,meta:this.meta}));let Z=this._select(Y),W=Z&&B1(Z),G=Y.boundary==="child"?(_,H)=>H.root.children.includes(_):Y.boundary==="shallow"?(_)=>_.kind!=="structure":()=>!0;return this.$.finalize(this.transform(U,{shouldTransform:G,selected:W}))}}var M2={applyBoundary:{self:(Q)=>[Q],child:(Q)=>[...Q.children],shallow:(Q)=>[...Q.shallowReferences],references:(Q)=>[...Q.references]},applyMethod:{filter:(Q)=>Q,assertFilter:(Q,X,Y)=>{if(Q.length===0)P1(I4(X,Y));return Q},find:(Q)=>Q[0],assertFind:(Q,X,Y)=>{if(Q.length===0)P1(I4(X,Y));return Q[0]}},normalize:(Q)=>typeof Q==="function"?{boundary:"references",method:"filter",where:Q}:typeof Q==="string"?f(Q,M2.applyBoundary)?{method:"filter",boundary:Q}:{boundary:"references",method:"filter",kind:Q}:{boundary:"references",method:"filter",...Q}},I4=(Q,X)=>`${Q} had no references matching ${B(X)}.`,cU=(Q)=>z1(Q,{stringifyNonKey:(X)=>X.expression}),oU=/"(\$ark\.[^"]+)"/g,iU=(Q)=>JSON.stringify(Q).replace(oU,"$1"),Z1=(Q,X)=>({path:Q,node:X,propString:cU(Q)}),S4=(Q,X)=>Q.propString===X.propString&&Q.node.equals(X.node),g6=(Q,X)=>_1(Q,X,{isEqual:S4}),sU=(Q,X)=>_1(Q,X,{isEqual:(Y,U)=>Y.equals(U)});class q extends Array{static init(Q,X,Y,U){return new q({kind:Q,l:X,r:Y,path:U?.path??[],optional:U?.optional??!1})}add(Q,X,Y,U){return this.push({kind:Q,l:X,r:Y,path:U?.path??[],optional:U?.optional??!1}),this}get summary(){return this.describeReasons()}describeReasons(){if(this.length===1){let{path:Q,l:X,r:Y}=this[0],U=z1(Q);return h6(`Intersection${U&&` at ${U}`} of ${j4(X,Y)}`)}return`The following intersections result in unsatisfiable types:
|
|
21
|
+
• ${this.map(({path:Q,l:X,r:Y})=>`${Q}: ${j4(X,Y)}`).join(`
|
|
22
|
+
• `)}`}throw(){return L(this.describeReasons())}invert(){let Q=this.map((X)=>({...X,l:X.r,r:X.l}));if(!(Q instanceof q))return new q(...Q);return Q}withPrefixKey(Q,X){return this.map((Y)=>({...Y,path:[Q,...Y.path],optional:Y.optional||X==="optional"}))}toNeverIfDisjoint(){return F.intrinsic.never}}var j4=(Q,X)=>`${x6(Q)} and ${x6(X)}`,x6=(Q)=>P(Q)?Q.expression:K(Q)?Q.map(x6).join(" | ")||"never":String(Q),h6=(Q)=>`${Q} results in an unsatisfiable type`;var m1={},o=(Q,X,Y)=>N(Q,X,{$:Y,invert:!1,pipe:!1}),D2=(Q,X,Y)=>N(Q,X,{$:Y,invert:!1,pipe:!0}),N=(Q,X,Y)=>{let U=Y.pipe?"|>":"&",Z=`${Q.hash}${U}${X.hash}`;if(m1[Z]!==void 0)return m1[Z];if(!Y.pipe){let _=`${X.hash}${U}${Q.hash}`;if(m1[_]!==void 0){let H=m1[_],J=H instanceof q?H.invert():H;return m1[Z]=J,J}}let W=!Y.pipe||!Q.includesTransform&&!X.includesTransform;if(W&&Q.equals(X))return Q;let G=W?p6(Q,X,Y):Q.hasKindIn(...h1)?nU(Q,X,Y):p6(Q,X,Y);if(P(G)){if(Q.equals(G))G=Q;else if(X.equals(G))G=X}return m1[Z]=G,G},p6=(Q,X,Y)=>{let U=Q.precedence<X.precedence?Q.kind:X.kind,Z=Q.impl.intersections[X.kind]??X.impl.intersections[Q.kind];if(Z===void 0)return null;else if(U===Q.kind)return Z(Q,X,Y);else{let W=Z(X,Q,{...Y,invert:!Y.invert});if(W instanceof q)W=W.invert();return W}},nU=(Q,X,Y)=>Q.includesTransform||X.includesTransform?Y.invert?b4(X,Q,Y):b4(Q,X,Y):p6(Q,X,Y),b4=(Q,X,Y)=>Q.distribute((U)=>rU(U,X,Y),(U)=>{let Z=U.filter(P);if(Z.length===0)return q.init("union",Q.branches,X.branches);if(Z.length<Q.branches.length||!Q.branches.every((_,H)=>_.rawIn.equals(Z[H].rawIn)))return Y.$.parseSchema(Z);let W;if(Z.length===1){let _=Z[0];if(!W)return _;return Y.$.node("morph",{..._.inner,in:_.rawIn.configure(W,"self")})}let G={branches:Z};if(W)G.meta=W;return Y.$.parseSchema(G)}),rU=(Q,X,Y)=>{if(Q.hasKind("morph")){let Z=[...Q.morphs];if(Q.lastMorphIfNode){let W=N(Q.lastMorphIfNode,X,Y);if(W instanceof q)return W;Z[Z.length-1]=W}else Z.push(X);return Y.$.node("morph",{morphs:Z,in:Q.inner.in})}if(X.hasKind("morph")){let Z=N(Q,X.rawIn,Y);if(Z instanceof q)return Z;return Y.$.node("morph",{morphs:[X],in:Z})}return Y.$.node("morph",{morphs:[X],in:Q})};class t extends T2{constructor(Q,X){super(Q,X);Object.defineProperty(this,x,{value:"constraint",enumerable:!1})}impliedSiblings;intersect(Q){return o(this,Q,this.$)}}class O1 extends t{traverseApply=(Q,X)=>{if(!this.traverseAllows(Q,X))X.errorFromNodeContext(this.errorContext)};compile(Q){if(Q.traversalKind==="Allows")Q.return(this.compiledCondition);else Q.if(this.compiledNegation,()=>Q.line(`ctx.errorFromNodeContext(${this.compiledErrorContext})`))}get errorContext(){return{code:this.kind,description:this.description,meta:this.meta,...this.inner}}get compiledErrorContext(){return R1(this.errorContext)}}var g=(Q)=>(X,Y)=>{if(K(X)){if(X.length===0)return;let Z=X.map((W)=>Y.$.node(Q,W));if(Q==="predicate")return Z;return Z.sort((W,G)=>W.hash<G.hash?-1:1)}let U=Y.$.node(Q,X);return U.hasOpenIntersection()?[U]:U},l1=(Q)=>{let X=Q.r.shift();if(!X){let U=Q.l.length===0&&Q.kind==="structure"?F.intrinsic.unknown.internal:Q.ctx.$.node(Q.kind,Object.assign(Q.baseInner,tU(Q.l)),{prereduced:!0});for(let Z of Q.roots){if(U instanceof q)return U;U=N(Z,U,Q.ctx)}return U}let Y=!1;for(let U=0;U<Q.l.length;U++){let Z=N(Q.l[U],X,Q.ctx);if(Z===null)continue;if(Z instanceof q)return Z;if(Z.isRoot())return Q.roots.push(Z),Q.l.splice(U),l1(Q);if(!Y)Q.l[U]=Z,Y=!0;else if(!Q.l.includes(Z))return C(`Unexpectedly encountered multiple distinct intersection results for refinement ${X}`)}if(!Y)Q.l.push(X);if(Q.kind==="intersection"){if(X.impliedSiblings)for(let U of X.impliedSiblings)_1(Q.r,U)}return l1(Q)},d1=(Q)=>{return Object.entries(Q).flatMap(([Y,U])=>(Y in c2)?U:[]).sort((Y,U)=>Y.precedence<U.precedence?-1:Y.precedence>U.precedence?1:Y.kind==="predicate"&&U.kind==="predicate"?0:Y.hash<U.hash?-1:1)},tU=(Q)=>{let X={};for(let Y of Q)if(Y.hasOpenIntersection())X[Y.kind]=D(X[Y.kind],Y);else{if(X[Y.kind])return C(`Unexpected intersection of closed refinements of kind ${Y.kind}`);X[Y.kind]=Y}return X},y4=(...Q)=>L(f4(...Q)),f4=(Q,X,Y)=>{let U=Y.hasKind("morph")?"a morph":Y.isUnknown()?"unknown":Y.exclude(X).defaultShortDescription;return`${G4(Q)} operand must be ${X.description} (was ${U})`};var v4=(Q,X,Y)=>new w1(Q,X,Y,Y,null);class i2 extends l{}class w1 extends l{[x]="generic";paramDefs;bodyDef;$;arg$;baseInstantiation;hkt;description;constructor(Q,X,Y,U,Z){super((...W)=>{let G=V(this.names,(_,H)=>{let J=this.arg$.parse(W[_]);if(!J.extends(this.constraints[_]))L(aU(H,this.constraints[_].expression,J.expression));return[H,J]});if(this.defIsLazy()){let _=this.bodyDef(G);return this.$.parse(_)}return this.$.parse(X,{args:G})});this.paramDefs=Q,this.bodyDef=X,this.$=Y,this.arg$=U,this.hkt=Z,this.description=Z?new Z().description??`a generic type for ${Z.constructor.name}`:"a generic type",this.baseInstantiation=this(...this.constraints)}defIsLazy(){return this.bodyDef instanceof i2}cacheGetter(Q,X){return Object.defineProperty(this,Q,{value:X}),X}get json(){return this.cacheGetter("json",{params:this.params.map((Q)=>Q[1].isUnknown()?Q[0]:[Q[0],Q[1].json]),body:B4(this.bodyDef)})}get params(){return this.cacheGetter("params",this.paramDefs.map((Q)=>typeof Q==="string"?[Q,F.intrinsic.unknown]:[Q[0],this.$.parse(Q[1])]))}get names(){return this.cacheGetter("names",this.params.map((Q)=>Q[0]))}get constraints(){return this.cacheGetter("constraints",this.params.map((Q)=>Q[1]))}get internal(){return this}get referencesById(){return this.baseInstantiation.internal.referencesById}get references(){return this.baseInstantiation.internal.references}}var aU=(Q,X,Y)=>`${Q} must be assignable to ${X} (was ${Y})`;var eU=M({kind:"predicate",hasAssociatedError:!0,collapsibleKey:"predicate",keys:{predicate:{}},normalize:(Q)=>typeof Q==="function"?{predicate:Q}:Q,defaults:{description:(Q)=>`valid according to ${Q.predicate.name||"an anonymous predicate"}`},intersectionIsOpen:!0,intersections:{predicate:()=>null}});class k4 extends t{serializedPredicate=S(this.predicate);compiledCondition=`${this.serializedPredicate}(data, ctx)`;compiledNegation=`!${this.compiledCondition}`;impliedBasis=null;expression=this.serializedPredicate;traverseAllows=this.predicate;errorContext={code:"predicate",description:this.description,meta:this.meta};compiledErrorContext=R1(this.errorContext);traverseApply=(Q,X)=>{let Y=X.currentErrorCount;if(!this.predicate(Q,X.external)&&X.currentErrorCount===Y)X.errorFromNodeContext(this.errorContext)};compile(Q){if(Q.traversalKind==="Allows"){Q.return(this.compiledCondition);return}Q.initializeErrorCount(),Q.if(`${this.compiledNegation} && ctx.currentErrorCount === errorCount`,()=>Q.line(`ctx.errorFromNodeContext(${this.compiledErrorContext})`))}reduceJsonSchema(Q,X){return X.fallback.predicate({code:"predicate",base:Q,predicate:this.predicate})}}var u6={implementation:eU,Node:k4};var QZ=M({kind:"divisor",collapsibleKey:"rule",keys:{rule:{parse:(Q)=>Number.isInteger(Q)?Q:L(XZ(Q))}},normalize:(Q)=>typeof Q==="number"?{rule:Q}:Q,hasAssociatedError:!0,defaults:{description:(Q)=>Q.rule===1?"an integer":Q.rule===2?"even":`a multiple of ${Q.rule}`},intersections:{divisor:(Q,X,Y)=>Y.$.node("divisor",{rule:Math.abs(Q.rule*X.rule/YZ(Q.rule,X.rule))})},obviatesBasisDescription:!0});class g4 extends O1{traverseAllows=(Q)=>Q%this.rule===0;compiledCondition=`data % ${this.rule} === 0`;compiledNegation=`data % ${this.rule} !== 0`;impliedBasis=F.intrinsic.number.internal;expression=`% ${this.rule}`;reduceJsonSchema(Q){if(Q.type="integer",this.rule===1)return Q;return Q.multipleOf=this.rule,Q}}var m6={implementation:QZ,Node:g4};var XZ=(Q)=>`divisor must be an integer (was ${Q})`,YZ=(Q,X)=>{let Y,U=Q,Z=X;while(Z!==0)Y=Z,Z=U%Z,U=Y;return U};class s extends O1{boundOperandKind=GZ[this.kind];compiledActual=this.boundOperandKind==="value"?"data":this.boundOperandKind==="length"?"data.length":"data.valueOf()";comparator=_Z(this.kind,this.exclusive);numericLimit=this.rule.valueOf();expression=`${this.comparator} ${this.rule}`;compiledCondition=`${this.compiledActual} ${this.comparator} ${this.numericLimit}`;compiledNegation=`${this.compiledActual} ${UZ[this.comparator]} ${this.numericLimit}`;stringLimit=this.boundOperandKind==="date"?JZ(this.numericLimit):`${this.numericLimit}`;limitKind=this.comparator["0"]==="<"?"upper":"lower";isStricterThan(Q){return(this.limitKind==="upper"?this.numericLimit<Q.numericLimit:this.numericLimit>Q.numericLimit)||this.numericLimit===Q.numericLimit&&this.exclusive===!0&&!Q.exclusive}overlapsRange(Q){if(this.isStricterThan(Q))return!1;if(this.numericLimit===Q.numericLimit&&(this.exclusive||Q.exclusive))return!1;return!0}overlapIsUnit(Q){return this.numericLimit===Q.numericLimit&&!this.exclusive&&!Q.exclusive}}var UZ={"<":">=","<=":">",">":"<=",">=":"<"},ZZ={min:"max",minLength:"maxLength",after:"before"},s2={parse:(Q)=>Q||void 0},n2=(Q)=>(X)=>{if(typeof X==="number")return{rule:X};let{exclusive:Y,...U}=X;return Y?{...U,rule:Q==="minLength"?U.rule+1:U.rule-1}:U},r2=(Q)=>(X)=>{if(typeof X==="number"||typeof X==="string"||X instanceof Date)return{rule:X};let{exclusive:Y,...U}=X;if(!Y)return U;let Z=typeof U.rule==="number"?U.rule:typeof U.rule==="string"?new Date(U.rule).valueOf():U.rule.valueOf();return Y?{...U,rule:Q==="after"?Z+1:Z-1}:U},t2=(Q)=>typeof Q==="string"||typeof Q==="number"?new Date(Q):Q,WZ=(Q,X)=>`${Q} bound must be a positive integer (was ${X})`,c1=(Q)=>(X)=>{if(!Number.isInteger(X)||X<0)L(WZ(Q,X));return X},GZ={min:"value",max:"value",minLength:"length",maxLength:"length",after:"date",before:"date"},_Z=(Q,X)=>`${f(Q,ZZ)?">":"<"}${X?"":"="}`,JZ=(Q)=>typeof Q==="string"?Q:new Date(Q).toLocaleString(),x4=(Q)=>`Bounded expression ${Q} must be exactly one of number, string, Array, or Date`;var LZ=M({kind:"after",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{parse:t2,serialize:(Q)=>Q.toISOString()}},normalize:r2("after"),defaults:{description:(Q)=>`${Q.collapsibleLimitString} or later`,actual:j1},intersections:{after:(Q,X)=>Q.isStricterThan(X)?Q:X}});class h4 extends s{impliedBasis=F.intrinsic.Date.internal;collapsibleLimitString=j1(this.rule);traverseAllows=(Q)=>Q>=this.rule;reduceJsonSchema(Q,X){return X.fallback.date({code:"date",base:Q,after:this.rule})}}var l6={implementation:LZ,Node:h4};var HZ=M({kind:"before",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{parse:t2,serialize:(Q)=>Q.toISOString()}},normalize:r2("before"),defaults:{description:(Q)=>`${Q.collapsibleLimitString} or earlier`,actual:j1},intersections:{before:(Q,X)=>Q.isStricterThan(X)?Q:X,after:(Q,X,Y)=>Q.overlapsRange(X)?Q.overlapIsUnit(X)?Y.$.node("unit",{unit:Q.rule}):null:q.init("range",Q,X)}});class p4 extends s{collapsibleLimitString=j1(this.rule);traverseAllows=(Q)=>Q<=this.rule;impliedBasis=F.intrinsic.Date.internal;reduceJsonSchema(Q,X){return X.fallback.date({code:"date",base:Q,before:this.rule})}}var d6={implementation:HZ,Node:p4};var FZ=M({kind:"exactLength",collapsibleKey:"rule",keys:{rule:{parse:c1("exactLength")}},normalize:(Q)=>typeof Q==="number"?{rule:Q}:Q,hasAssociatedError:!0,defaults:{description:(Q)=>`exactly length ${Q.rule}`,actual:(Q)=>`${Q.length}`},intersections:{exactLength:(Q,X,Y)=>q.init("unit",Y.$.node("unit",{unit:Q.rule}),Y.$.node("unit",{unit:X.rule}),{path:["length"]}),minLength:(Q,X)=>Q.rule>=X.rule?Q:q.init("range",Q,X),maxLength:(Q,X)=>Q.rule<=X.rule?Q:q.init("range",Q,X)}});class u4 extends O1{traverseAllows=(Q)=>Q.length===this.rule;compiledCondition=`data.length === ${this.rule}`;compiledNegation=`data.length !== ${this.rule}`;impliedBasis=F.intrinsic.lengthBoundable.internal;expression=`== ${this.rule}`;reduceJsonSchema(Q){switch(Q.type){case"string":return Q.minLength=this.rule,Q.maxLength=this.rule,Q;case"array":return Q.minItems=this.rule,Q.maxItems=this.rule,Q;default:return E.throwInternalOperandError("exactLength",Q)}}}var c6={implementation:FZ,Node:u4};var qZ=M({kind:"max",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{},exclusive:s2},normalize:(Q)=>typeof Q==="number"?{rule:Q}:Q,defaults:{description:(Q)=>{if(Q.rule===0)return Q.exclusive?"negative":"non-positive";return`${Q.exclusive?"less than":"at most"} ${Q.rule}`}},intersections:{max:(Q,X)=>Q.isStricterThan(X)?Q:X,min:(Q,X,Y)=>Q.overlapsRange(X)?Q.overlapIsUnit(X)?Y.$.node("unit",{unit:Q.rule}):null:q.init("range",Q,X)},obviatesBasisDescription:!0});class m4 extends s{impliedBasis=F.intrinsic.number.internal;traverseAllows=this.exclusive?(Q)=>Q<this.rule:(Q)=>Q<=this.rule;reduceJsonSchema(Q){if(this.exclusive)Q.exclusiveMaximum=this.rule;else Q.maximum=this.rule;return Q}}var o6={implementation:qZ,Node:m4};var $Z=M({kind:"maxLength",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{parse:c1("maxLength")}},reduce:(Q,X)=>Q.rule===0?X.node("exactLength",Q):void 0,normalize:n2("maxLength"),defaults:{description:(Q)=>`at most length ${Q.rule}`,actual:(Q)=>`${Q.length}`},intersections:{maxLength:(Q,X)=>Q.isStricterThan(X)?Q:X,minLength:(Q,X,Y)=>Q.overlapsRange(X)?Q.overlapIsUnit(X)?Y.$.node("exactLength",{rule:Q.rule}):null:q.init("range",Q,X)}});class l4 extends s{impliedBasis=F.intrinsic.lengthBoundable.internal;traverseAllows=(Q)=>Q.length<=this.rule;reduceJsonSchema(Q){switch(Q.type){case"string":return Q.maxLength=this.rule,Q;case"array":return Q.maxItems=this.rule,Q;default:return E.throwInternalOperandError("maxLength",Q)}}}var i6={implementation:$Z,Node:l4};var AZ=M({kind:"min",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{},exclusive:s2},normalize:(Q)=>typeof Q==="number"?{rule:Q}:Q,defaults:{description:(Q)=>{if(Q.rule===0)return Q.exclusive?"positive":"non-negative";return`${Q.exclusive?"more than":"at least"} ${Q.rule}`}},intersections:{min:(Q,X)=>Q.isStricterThan(X)?Q:X},obviatesBasisDescription:!0});class d4 extends s{impliedBasis=F.intrinsic.number.internal;traverseAllows=this.exclusive?(Q)=>Q>this.rule:(Q)=>Q>=this.rule;reduceJsonSchema(Q){if(this.exclusive)Q.exclusiveMinimum=this.rule;else Q.minimum=this.rule;return Q}}var s6={implementation:AZ,Node:d4};var zZ=M({kind:"minLength",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{parse:c1("minLength")}},reduce:(Q)=>Q.rule===0?F.intrinsic.unknown:void 0,normalize:n2("minLength"),defaults:{description:(Q)=>Q.rule===1?"non-empty":`at least length ${Q.rule}`,actual:(Q)=>Q.length===0?"":`${Q.length}`},intersections:{minLength:(Q,X)=>Q.isStricterThan(X)?Q:X}});class c4 extends s{impliedBasis=F.intrinsic.lengthBoundable.internal;traverseAllows=(Q)=>Q.length>=this.rule;reduceJsonSchema(Q){switch(Q.type){case"string":return Q.minLength=this.rule,Q;case"array":return Q.minItems=this.rule,Q;default:return E.throwInternalOperandError("minLength",Q)}}}var n6={implementation:zZ,Node:c4};var o4={min:s6.implementation,max:o6.implementation,minLength:n6.implementation,maxLength:i6.implementation,exactLength:c6.implementation,after:l6.implementation,before:d6.implementation},i4={min:s6.Node,max:o6.Node,minLength:n6.Node,maxLength:i6.Node,exactLength:c6.Node,after:l6.Node,before:d6.Node};var OZ=M({kind:"pattern",collapsibleKey:"rule",keys:{rule:{},flags:{}},normalize:(Q)=>typeof Q==="string"?{rule:Q}:Q instanceof RegExp?Q.flags?{rule:Q.source,flags:Q.flags}:{rule:Q.source}:Q,obviatesBasisDescription:!0,obviatesBasisExpression:!0,hasAssociatedError:!0,intersectionIsOpen:!0,defaults:{description:(Q)=>`matched by ${Q.rule}`},intersections:{pattern:()=>null}});class s4 extends O1{instance=new RegExp(this.rule,this.flags);expression=`${this.instance}`;traverseAllows=this.instance.test.bind(this.instance);compiledCondition=`${this.expression}.test(data)`;compiledNegation=`!${this.compiledCondition}`;impliedBasis=F.intrinsic.string.internal;reduceJsonSchema(Q,X){if(Q.pattern)return X.fallback.patternIntersection({code:"patternIntersection",base:Q,pattern:this.rule});return Q.pattern=this.rule,Q}}var r6={implementation:OZ,Node:s4};var R2=(Q,X)=>{let Y=VZ(Q);if(X&&!X.includes(Y))return L(`Root of kind ${Y} should be one of ${X}`);return Y},VZ=(Q)=>{if(A(Q,"root"))return Q.kind;if(typeof Q==="string")return Q[0]==="$"?"alias":(Q in u)?"domain":"proto";if(typeof Q==="function")return"proto";if(typeof Q!=="object"||Q===null)return L(n4(Q));if("morphs"in Q)return"morph";if("branches"in Q||K(Q))return"union";if("unit"in Q)return"unit";if("reference"in Q)return"alias";let X=Object.keys(Q);if(X.length===0||X.some((Y)=>(Y in c2)))return"intersection";if("proto"in Q)return"proto";if("domain"in Q)return"domain";return L(n4(Q))},n4=(Q)=>`${B(Q)} is not a valid type schema`,r4={},BZ=(Q)=>K(Q)?Q.map((X)=>X.collapsibleJson):Q.collapsibleJson,h={};F.nodesByRegisteredId=h;var t6=(Q)=>{return r4[Q]??=0,`${Q}${++r4[Q]}`},a6=(Q)=>{let X=o1[Q.kind],Y=X.applyConfig?.(Q.def,Q.$.resolvedConfig)??Q.def,U={},{meta:Z,...W}=Y,G=Z===void 0?{}:typeof Z==="string"?{description:Z}:Z,_=D6(W).sort(([J],[$])=>p1(J)?p1($)?u1(J)-u1($):1:p1($)?-1:J<$?-1:1).filter(([J,$])=>{if(J.startsWith("meta.")){let O=J.slice(5);return G[O]=$,!1}return!0});for(let J of _){let $=J[0],O=X.keys[$];if(!O)return L(`Key ${$} is not valid on ${Q.kind} schema`);let R=O.parse?O.parse(J[1],Q):J[1];if(R!==m&&(R!==void 0||O.preserveUndefined))U[$]=R}if(X.reduce&&!Q.prereduced){let J=X.reduce(U,Q.$);if(J){if(J instanceof q)return J.throw();return MZ(J,G)}}return e6({id:Q.id,kind:Q.kind,inner:U,meta:G,$:Q.$})},e6=({id:Q,kind:X,inner:Y,meta:U,$:Z,ignoreCache:W})=>{let G=o1[X],_=D6(Y),H=[],J={};for(let[W1,f1]of _){let X2=G.keys[W1],WU=X2.serialize??(X2.child?BZ:r);if(J[W1]=WU(f1),X2.child===!0){let O6=f1;if(K(O6))H.push(...O6);else H.push(O6)}else if(typeof X2.child==="function")H.push(...X2.child(f1))}if(G.finalizeInnerJson)J=G.finalizeInnerJson(J);let $={...J},O={};if(!J1(U))O=V(U,(W1,f1)=>[W1,W1==="examples"?f1:r(f1)]),$.meta=a2(O,"description",!0);J=a2(J,G.collapsibleKey,!1);let R=JSON.stringify({kind:X,...J});$=a2($,G.collapsibleKey,!1);let b=a2($,G.collapsibleKey,!0),F1=JSON.stringify({kind:X,...$});if(Z.nodesByHash[F1]&&!W)return Z.nodesByHash[F1];let gQ={id:Q,kind:X,impl:G,inner:Y,innerEntries:_,innerJson:J,innerHash:R,meta:U,metaJson:O,json:$,hash:F1,collapsibleJson:b,children:H};if(X!=="intersection"){for(let W1 in Y)if(W1!=="in"&&W1!=="out")gQ[W1]=Y[W1]}let ZU=new a4[X](gQ,Z);return Z.nodesByHash[F1]=ZU},t4=(Q,X)=>{if(Q.id===X)return Q;if(P(h[X]))C(`Unexpected attempt to overwrite node id ${X}`);return e6({id:X,kind:Q.kind,inner:Q.inner,meta:Q.meta,$:Q.$,ignoreCache:!0})},MZ=(Q,X,Y)=>{if(Y&&P(h[Y]))C(`Unexpected attempt to overwrite node id ${Y}`);return e6({id:Y??t6(X.alias??Q.kind),kind:Q.kind,inner:Q.inner,meta:X,$:Q.$})},a2=(Q,X,Y)=>{let U=Object.keys(Q);if(U.length===1&&U[0]===X){let Z=Q[X];if(Y)return Z;if(p(Z,"object")&&(Object.keys(Z).length===1||Array.isArray(Z)))return Z}return Q};var C2=(Q,X,Y)=>{if(Q.key!==X.key)return null;let U=Q.key,Z=N(Q.value,X.value,Y),W=Q.required||X.required?"required":"optional";if(Z instanceof q)if(W==="optional")Z=F.intrinsic.never.internal;else return Z.withPrefixKey(Q.key,Q.required&&X.required?"required":"optional");if(W==="required")return Y.$.node("required",{key:U,value:Z});let G=Q.hasDefault()?X.hasDefault()?Q.default===X.default?Q.default:L(QQ(Q.default,X.default)):Q.default:X.hasDefault()?X.default:m;return Y.$.node("optional",{key:U,value:Z,default:G})};class w2 extends t{required=this.kind==="required";optional=this.kind==="optional";impliedBasis=F.intrinsic.object.internal;serializedKey=Y1(this.key);compiledKey=typeof this.key==="string"?this.key:this.serializedKey;flatRefs=D(this.value.flatRefs.map((Q)=>Z1([this.key,...Q.path],Q.node)),Z1([this.key],this.value));_transform(Q,X){X.path.push(this.key);let Y=super._transform(Q,X);return X.path.pop(),Y}hasDefault(){return"default"in this.inner}traverseAllows=(Q,X)=>{if(this.key in Q)return c(this.key,()=>this.value.traverseAllows(Q[this.key],X),X);return this.optional};traverseApply=(Q,X)=>{if(this.key in Q)c(this.key,()=>this.value.traverseApply(Q[this.key],X),X);else if(this.hasKind("required"))X.errorFromNodeContext(this.errorContext)};compile(Q){if(Q.if(`${this.serializedKey} in data`,()=>Q.traverseKey(this.serializedKey,`data${Q.prop(this.key)}`,this.value)),this.hasKind("required"))Q.else(()=>Q.traversalKind==="Apply"?Q.line(`ctx.errorFromNodeContext(${this.compiledErrorContext})`):Q.return(!1));if(Q.traversalKind==="Allows")Q.return(!0)}}var QQ=(Q,X)=>`Invalid intersection of default values ${B(Q)} & ${B(X)}`;var TZ=M({kind:"optional",hasAssociatedError:!1,intersectionIsOpen:!0,keys:{key:{},value:{child:!0,parse:(Q,X)=>X.$.parseSchema(Q)},default:{preserveUndefined:!0}},normalize:(Q)=>Q,reduce:(Q,X)=>{if(X.resolvedConfig.exactOptionalPropertyTypes===!1){if(!Q.value.allows(void 0))return X.node("optional",{...Q,value:Q.value.or(z.undefined)},{prereduced:!0})}},defaults:{description:(Q)=>`${Q.compiledKey}?: ${Q.value.description}`},intersections:{optional:C2}});class e4 extends w2{constructor(...Q){super(...Q);if("default"in this.inner)P2(this.value,this.inner.default,this.key)}get rawIn(){let Q=super.rawIn;if(!this.hasDefault())return Q;return this.$.node("optional",x2(Q.inner,{default:!0}),{prereduced:!0})}get outProp(){if(!this.hasDefault())return this;let{default:Q,...X}=this.inner;return this.cacheGetter("outProp",this.$.node("required",X,{prereduced:!0}))}expression=this.hasDefault()?`${this.compiledKey}: ${this.value.expression} = ${B(this.inner.default)}`:`${this.compiledKey}?: ${this.value.expression}`;defaultValueMorph=RZ(this);defaultValueMorphRef=this.defaultValueMorph&&S(this.defaultValueMorph)}var K2={implementation:TZ,Node:e4},DZ={},RZ=(Q)=>{if(!Q.hasDefault())return;let X=`{${Q.compiledKey}: ${Q.value.id} = ${r(Q.default)}}`;return DZ[X]??=XQ(Q.key,Q.value,Q.default)},XQ=(Q,X,Y)=>{if(typeof Y==="function")return X.includesTransform?(Z,W)=>{return c(Q,()=>X(Z[Q]=Y(),W),W),Z}:(Z)=>{return Z[Q]=Y(),Z};let U=X.includesTransform?X.assert(Y):Y;return p(U,"object")?(Z,W)=>{return c(Q,()=>X(Z[Q]=Y,W),W),Z}:(Z)=>{return Z[Q]=U,Z}},P2=(Q,X,Y)=>{let U=M1(X);if(p(X,"object")&&!U)L(CZ(Y));let Z=Q.in(U?X():X);if(Z instanceof d){if(Y===null)L(`Default ${Z.summary}`);let W=Z.transform((G)=>G.transform((_)=>({..._,prefixPath:[Y]})));L(`Default for ${W.summary}`)}return X},CZ=(Q)=>{return`Non-primitive default ${Q===null?"":typeof Q==="number"?`for value at [${Q}] `:`for ${Y1(Q)} `}must be specified as a function like () => ({my: 'object'})`};class a extends T2{constructor(Q,X){super(Q,X);Object.defineProperty(this,x,{value:"root",enumerable:!1})}get rawIn(){return super.rawIn}get rawOut(){return super.rawOut}get internal(){return this}get "~standard"(){return{vendor:"arktype",version:1,validate:(Q)=>{let X=this(Q);if(X instanceof d)return X;return{value:X}},jsonSchema:{input:(Q)=>this.rawIn.toJsonSchema({target:QX(Q.target),...Q.libraryOptions}),output:(Q)=>this.rawOut.toJsonSchema({target:QX(Q.target),...Q.libraryOptions})}}}as(){return this}brand(Q){if(Q==="")return L(wZ);return this}readonly(){return this}branches=this.hasKind("union")?this.inner.branches:[this];distribute(Q,X){let Y=this.branches.map(Q);return X?.(Y)??Y}get shortDescription(){return this.meta.description??this.defaultShortDescription}toJsonSchema(Q={}){let X=v6(this.$.resolvedConfig.toJsonSchema,Q);X.useRefs||=this.isCyclic;let Y=typeof X.dialect==="string"?{$schema:X.dialect}:{};if(Object.assign(Y,this.toJsonSchemaRecurse(X)),X.useRefs){let U=V(this.references,(Z,W)=>W.isRoot()&&!W.alwaysExpandJsonSchema?[W.id,W.toResolvedJsonSchema(X)]:[]);if(X.target==="draft-07")Object.assign(Y,{definitions:U});else Y.$defs=U}return Y}toJsonSchemaRecurse(Q){if(Q.useRefs&&!this.alwaysExpandJsonSchema)return{$ref:`#/${Q.target==="draft-07"?"definitions":"$defs"}/${this.id}`};return this.toResolvedJsonSchema(Q)}get alwaysExpandJsonSchema(){return this.isBasis()||this.kind==="alias"||this.hasKind("union")&&this.isBoolean}toResolvedJsonSchema(Q){let X=this.innerToJsonSchema(Q);return Object.assign(X,this.metaJson)}intersect(Q){let X=this.$.parseDefinition(Q),Y=this.rawIntersect(X);if(Y instanceof q)return Y;return this.$.finalize(Y)}rawIntersect(Q){return o(this,Q,this.$)}toNeverIfDisjoint(){return this}and(Q){let X=this.intersect(Q);return X instanceof q?X.throw():X}rawAnd(Q){let X=this.rawIntersect(Q);return X instanceof q?X.throw():X}or(Q){let X=this.$.parseDefinition(Q);return this.$.finalize(this.rawOr(X))}rawOr(Q){let X=[...this.branches,...Q.branches];return this.$.node("union",X)}map(Q){return this.$.schema(this.applyStructuralOperation("map",[Q]))}pick(...Q){return this.$.schema(this.applyStructuralOperation("pick",Q))}omit(...Q){return this.$.schema(this.applyStructuralOperation("omit",Q))}required(){return this.$.schema(this.applyStructuralOperation("required",[]))}partial(){return this.$.schema(this.applyStructuralOperation("partial",[]))}_keyof;keyof(){if(this._keyof)return this._keyof;let Q=this.applyStructuralOperation("keyof",[]).reduce((X,Y)=>X.intersect(Y).toNeverIfDisjoint(),F.intrinsic.unknown.internal);if(Q.branches.length===0)L(h6(`keyof ${this.expression}`));return this._keyof=this.$.finalize(Q)}get props(){if(this.branches.length!==1)return L(PZ(this.expression));return[...this.applyStructuralOperation("props",[])[0]]}merge(Q){let X=this.$.parseDefinition(Q);return this.$.schema(X.distribute((Y)=>this.applyStructuralOperation("merge",[XX(Y)??L(YX("merge",Y.expression))])))}applyStructuralOperation(Q,X){return this.distribute((Y)=>{if(Y.equals(F.intrinsic.object)&&Q!=="merge")return Y;let U=XX(Y);if(!U)L(YX(Q,Y.expression));if(Q==="keyof")return U.keyof();if(Q==="get")return U.get(...X);if(Q==="props")return U.props;let Z=Q==="required"?"require":Q==="partial"?"optionalize":Q;return this.$.node("intersection",{domain:"object",structure:U[Z](...X)})})}get(...Q){if(Q[0]===void 0)return this;return this.$.schema(this.applyStructuralOperation("get",Q))}extract(Q){let X=this.$.parseDefinition(Q);return this.$.schema(this.branches.filter((Y)=>Y.extends(X)))}exclude(Q){let X=this.$.parseDefinition(Q);return this.$.schema(this.branches.filter((Y)=>!Y.extends(X)))}array(){return this.$.schema(this.isUnknown()?{proto:Array}:{proto:Array,sequence:this},{prereduced:!0})}overlaps(Q){return!(this.intersect(Q)instanceof q)}extends(Q){if(this.isNever())return!0;let X=this.intersect(Q);return!(X instanceof q)&&this.equals(X)}ifExtends(Q){return this.extends(Q)?this:void 0}subsumes(Q){return this.$.parseDefinition(Q).extends(this)}configure(Q,X="shallow"){return this.configureReferences(Q,X)}describe(Q,X="shallow"){return this.configure({description:Q},X)}optional(){return[this,"?"]}default(Q){return P2(this,Q,null),[this,"=",Q]}from(Q){return this.assert(Q)}_pipe(...Q){let X=Q.reduce((Y,U)=>Y.rawPipeOnce(U),this);return this.$.finalize(X)}tryPipe(...Q){let X=Q.reduce((Y,U)=>Y.rawPipeOnce(A(U,"root")?U:(Z,W)=>{try{return U(Z,W)}catch(G){return W.error({code:"predicate",predicate:U,actual:`aborted due to error:
|
|
23
23
|
${G}
|
|
24
|
-
`})}}),this);return this.$.finalize(X)}pipe=Object.assign(this._pipe.bind(this),{try:this.tryPipe.bind(this)});to(Q){return this.$.finalize(this.toNode(this.$.parseDefinition(Q)))}toNode(Q){let X=
|
|
25
|
-
${Q}`,
|
|
24
|
+
`})}}),this);return this.$.finalize(X)}pipe=Object.assign(this._pipe.bind(this),{try:this.tryPipe.bind(this)});to(Q){return this.$.finalize(this.toNode(this.$.parseDefinition(Q)))}toNode(Q){let X=D2(this,Q,this.$);if(X instanceof q)return X.throw();return X}rawPipeOnce(Q){if(A(Q,"root"))return this.toNode(Q);return this.distribute((X)=>X.hasKind("morph")?this.$.node("morph",{in:X.inner.in,morphs:[...X.morphs,Q]}):this.$.node("morph",{in:X,morphs:[Q]}),this.$.parseSchema)}narrow(Q){return this.constrainOut("predicate",Q)}constrain(Q,X){return this._constrain("root",Q,X)}constrainIn(Q,X){return this._constrain("in",Q,X)}constrainOut(Q,X){return this._constrain("out",Q,X)}_constrain(Q,X,Y){let U=this.$.node(X,Y);if(U.isRoot())return U.isUnknown()?this:C(`Unexpected constraint node ${U}`);let Z=Q==="root"?this:Q==="in"?this.rawIn:this.rawOut;if(Z.hasKind("morph")||U.impliedBasis&&!Z.extends(U.impliedBasis))return y4(X,U.impliedBasis,this);let W=this.$.node("intersection",{[U.kind]:U}),G=Q==="out"?D2(this,W,this.$):o(this,W,this.$);if(G instanceof q)G.throw();return this.$.finalize(G)}onUndeclaredKey(Q){let X=typeof Q==="string"?Q:Q.rule,Y=typeof Q==="string"?!1:Q.deep;return this.$.finalize(this.transform((U,Z)=>U==="structure"?X==="ignore"?x2(Z,{undeclared:1}):{...Z,undeclared:X}:Z,Y?void 0:{shouldTransform:(U)=>!n(x1,U.kind)}))}hasEqualMorphs(Q){if(!this.includesTransform&&!Q.includesTransform)return!0;if(!$1(this.shallowMorphs,Q.shallowMorphs))return!1;if(!$1(this.flatMorphs,Q.flatMorphs,{isEqual:(X,Y)=>X.propString===Y.propString&&(X.node.hasKind("morph")&&Y.node.hasKind("morph")?X.node.hasEqualMorphs(Y.node):X.node.hasKind("intersection")&&Y.node.hasKind("intersection")?X.node.structure?.structuralMorphRef===Y.node.structure?.structuralMorphRef:!1)}))return!1;return!0}onDeepUndeclaredKey(Q){return this.onUndeclaredKey({rule:Q,deep:!0})}filter(Q){return this.constrainIn("predicate",Q)}divisibleBy(Q){return this.constrain("divisor",Q)}matching(Q){return this.constrain("pattern",Q)}atLeast(Q){return this.constrain("min",Q)}atMost(Q){return this.constrain("max",Q)}moreThan(Q){return this.constrain("min",i1(Q))}lessThan(Q){return this.constrain("max",i1(Q))}atLeastLength(Q){return this.constrain("minLength",Q)}atMostLength(Q){return this.constrain("maxLength",Q)}moreThanLength(Q){return this.constrain("minLength",i1(Q))}lessThanLength(Q){return this.constrain("maxLength",i1(Q))}exactlyLength(Q){return this.constrain("exactLength",Q)}atOrAfter(Q){return this.constrain("after",Q)}atOrBefore(Q){return this.constrain("before",Q)}laterThan(Q){return this.constrain("after",i1(Q))}earlierThan(Q){return this.constrain("before",i1(Q))}}var wZ="Expected a non-empty brand name after #",UX=["draft-2020-12","draft-07"],KZ=(Q)=>`JSONSchema target '${Q}' is not supported (must be ${UX.map((X)=>`"${X}"`).join(" or ")})`,QX=(Q)=>{if(!n(UX,Q))L(KZ(Q));return Q},i1=(Q)=>typeof Q==="object"&&!(Q instanceof Date)?{...Q,exclusive:!0}:{rule:Q,exclusive:!0},N2=(Q,X)=>A(X,"root")?A(Q,"root")?Q.extends(X):X.allows(Q):A(Q,"root")?Q.hasUnit(X):X===Q,XX=(Q)=>{if(Q.hasKind("morph"))return null;if(Q.hasKind("intersection"))return Q.inner.structure??(Q.basis?.domain==="object"?Q.$.bindReference(F.intrinsic.emptyStructure):null);if(Q.isBasis()&&Q.domain==="object")return Q.$.bindReference(F.intrinsic.emptyStructure);return null},PZ=(Q)=>`Props cannot be extracted from a union. Use .distribute to extract props from each branch instead. Received:
|
|
25
|
+
${Q}`,YX=(Q,X)=>`${Q} operand must be an object (was ${X})`;var L1=(Q,X)=>V(o2(Q),(Y,U)=>[U,X]);var NZ=(Q)=>typeof Q==="string"?{reference:Q}:Q,ZX=(Q)=>Q instanceof q?F.intrinsic.never.internal:Q,EZ=M({kind:"alias",hasAssociatedError:!1,collapsibleKey:"reference",keys:{reference:{serialize:(Q)=>Q.startsWith("$")?Q:`$ark.${Q}`},resolve:{}},normalize:NZ,defaults:{description:(Q)=>Q.reference},intersections:{alias:(Q,X,Y)=>Y.$.lazilyResolve(()=>ZX(N(Q.resolution,X.resolution,Y)),`${Q.reference}${Y.pipe?"=>":"&"}${X.reference}`),...L1("alias",(Q,X,Y)=>{if(X.isUnknown())return Q;if(X.isNever())return X;if(X.isBasis()&&!X.overlaps(F.intrinsic.object))return q.init("assignability",F.intrinsic.object,X);return Y.$.lazilyResolve(()=>ZX(N(Q.resolution,X,Y)),`${Q.reference}${Y.pipe?"=>":"&"}${X.id}`)})}});class WX extends a{expression=this.reference;structure=void 0;get resolution(){let Q=this._resolve();return h[this.id]=Q}_resolve(){if(this.resolve)return this.resolve();if(this.reference[0]==="$")return this.$.resolveRoot(this.reference.slice(1));let Q=this.reference,X=h[Q],Y=[];while(A(X,"context")){if(Y.includes(X.id))return L(IZ(X.id,Y));Y.push(X.id),X=h[X.id]}if(!A(X,"root"))return C(`Unexpected resolution for reference ${this.reference}
|
|
26
26
|
Seen: [${Y.join("->")}]
|
|
27
|
-
Resolution: ${
|
|
27
|
+
Resolution: ${B(X)}`);return X}get resolutionId(){if(this.reference.includes("&")||this.reference.includes("=>"))return this.resolution.id;if(this.reference[0]!=="$")return this.reference;let Q=this.reference.slice(1),X=this.$.resolutions[Q];if(typeof X==="string")return X;if(A(X,"root"))return X.id;return C(`Unexpected resolution for reference ${this.reference}: ${B(X)}`)}get defaultShortDescription(){return u.object}innerToJsonSchema(Q){return this.resolution.toJsonSchemaRecurse(Q)}traverseAllows=(Q,X)=>{let Y=X.seen[this.reference];if(Y?.includes(Q))return!0;return X.seen[this.reference]=D(Y,Q),this.resolution.traverseAllows(Q,X)};traverseApply=(Q,X)=>{let Y=X.seen[this.reference];if(Y?.includes(Q))return;X.seen[this.reference]=D(Y,Q),this.resolution.traverseApply(Q,X)};compile(Q){let X=this.resolutionId;Q.if(`ctx.seen.${X} && ctx.seen.${X}.includes(data)`,()=>Q.return(!0)),Q.if(`!ctx.seen.${X}`,()=>Q.line(`ctx.seen.${X} = []`)),Q.line(`ctx.seen.${X}.push(data)`),Q.return(Q.invoke(X))}}var IZ=(Q,X)=>`Alias '${Q}' has a shallow resolution cycle: ${[...X,Q].join("->")}`,E2={implementation:EZ,Node:WX};class b1 extends a{traverseApply=(Q,X)=>{if(!this.traverseAllows(Q,X))X.errorFromNodeContext(this.errorContext)};get errorContext(){return{code:this.kind,description:this.description,meta:this.meta,...this.inner}}get compiledErrorContext(){return R1(this.errorContext)}compile(Q){if(Q.traversalKind==="Allows")Q.return(this.compiledCondition);else Q.if(this.compiledNegation,()=>Q.line(`ctx.errorFromNodeContext(${this.compiledErrorContext})`))}}var SZ=M({kind:"domain",hasAssociatedError:!0,collapsibleKey:"domain",keys:{domain:{},numberAllowsNaN:{}},normalize:(Q)=>typeof Q==="string"?{domain:Q}:k1(Q,"numberAllowsNaN")&&Q.domain!=="number"?L(e2.writeBadAllowNanMessage(Q.domain)):Q,applyConfig:(Q,X)=>Q.numberAllowsNaN===void 0&&Q.domain==="number"&&X.numberAllowsNaN?{...Q,numberAllowsNaN:!0}:Q,defaults:{description:(Q)=>u[Q.domain],actual:(Q)=>Number.isNaN(Q)?"NaN":u[y(Q)]},intersections:{domain:(Q,X)=>Q.domain==="number"&&X.domain==="number"?Q.numberAllowsNaN?X:Q:q.init("domain",Q,X)}});class GX extends b1{requiresNaNCheck=this.domain==="number"&&!this.numberAllowsNaN;traverseAllows=this.requiresNaNCheck?(Q)=>typeof Q==="number"&&!Number.isNaN(Q):(Q)=>y(Q)===this.domain;compiledCondition=this.domain==="object"?'((typeof data === "object" && data !== null) || typeof data === "function")':`typeof data === "${this.domain}"${this.requiresNaNCheck?" && !Number.isNaN(data)":""}`;compiledNegation=this.domain==="object"?'((typeof data !== "object" || data === null) && typeof data !== "function")':`typeof data !== "${this.domain}"${this.requiresNaNCheck?" || Number.isNaN(data)":""}`;expression=this.numberAllowsNaN?"number | NaN":this.domain;get nestableExpression(){return this.numberAllowsNaN?`(${this.expression})`:this.expression}get defaultShortDescription(){return u[this.domain]}innerToJsonSchema(Q){if(this.domain==="bigint"||this.domain==="symbol")return Q.fallback.domain({code:"domain",base:{},domain:this.domain});return{type:this.domain}}}var e2={implementation:SZ,Node:GX,writeBadAllowNanMessage:(Q)=>`numberAllowsNaN may only be specified with domain "number" (was ${Q})`};var jZ=M({kind:"intersection",hasAssociatedError:!0,normalize:(Q)=>{if(P(Q))return Q;let{structure:X,...Y}=Q,U=!!X,Z=X??{},W=V(Y,(G,_)=>{if(f(G,w4)){if(U)L(`Flattened structure key ${G} cannot be specified alongside a root 'structure' key.`);return Z[G]=_,[]}return[G,_]});if(A(Z,"constraint")||!J1(Z))W.structure=Z;return W},finalizeInnerJson:({structure:Q,...X})=>p(Q,"object")?{...Q,...X}:X,keys:{domain:{child:!0,parse:(Q,X)=>X.$.node("domain",Q)},proto:{child:!0,parse:(Q,X)=>X.$.node("proto",Q)},structure:{child:!0,parse:(Q,X)=>X.$.node("structure",Q),serialize:(Q)=>{if(!Q.sequence?.minLength)return Q.collapsibleJson;let{sequence:X,...Y}=Q.collapsibleJson,{minVariadicLength:U,...Z}=X,W=Z.variadic&&Object.keys(Z).length===1?Z.variadic:Z;return{...Y,sequence:W}}},divisor:{child:!0,parse:g("divisor")},max:{child:!0,parse:g("max")},min:{child:!0,parse:g("min")},maxLength:{child:!0,parse:g("maxLength")},minLength:{child:!0,parse:g("minLength")},exactLength:{child:!0,parse:g("exactLength")},before:{child:!0,parse:g("before")},after:{child:!0,parse:g("after")},pattern:{child:!0,parse:g("pattern")},predicate:{child:!0,parse:g("predicate")}},reduce:(Q,X)=>_X({},Q,{$:X,invert:!1,pipe:!1}),defaults:{description:(Q)=>{if(Q.children.length===0)return"unknown";if(Q.structure)return Q.structure.description;let X=[];if(Q.basis&&!Q.prestructurals.some((Y)=>Y.impl.obviatesBasisDescription))X.push(Q.basis.description);if(Q.prestructurals.length){let Y=Q.prestructurals.slice().sort((U,Z)=>U.kind==="min"&&Z.kind==="max"?-1:0).map((U)=>U.description);X.push(...Y)}if(Q.inner.predicate)X.push(...Q.inner.predicate.map((Y)=>Y.description));return X.join(" and ")},expected:(Q)=>` ◦ ${Q.errors.map((X)=>X.expected).join(`
|
|
28
28
|
◦ `)}`,problem:(Q)=>`(${Q.actual}) must be...
|
|
29
|
-
${Q.expected}`},intersections:{intersection:(Q,X,Y)=>
|
|
29
|
+
${Q.expected}`},intersections:{intersection:(Q,X,Y)=>_X(Q.inner,X.inner,Y),...L1("intersection",(Q,X,Y)=>{if(Q.children.length===0)return X;let{domain:U,proto:Z,...W}=Q.inner,G=Z??U,_=G?N(G,X,Y):X;return _ instanceof q?_:Q?.basis?.equals(_)?Q:Q.$.node("intersection",{...W,[_.kind]:_},{prereduced:!0})})}});class JX extends a{basis=this.inner.domain??this.inner.proto??null;prestructurals=[];refinements=this.children.filter((Q)=>{if(!Q.isRefinement())return!1;if(n(y6,Q.kind))this.prestructurals.push(Q);return!0});structure=this.inner.structure;expression=bZ(this);get shallowMorphs(){return this.inner.structure?.structuralMorph?[this.inner.structure.structuralMorph]:[]}get defaultShortDescription(){return this.basis?.defaultShortDescription??"present"}innerToJsonSchema(Q){return this.children.reduce((X,Y)=>Y.isBasis()?Y.toJsonSchemaRecurse(Q):Y.reduceJsonSchema(X,Q),{})}traverseAllows=(Q,X)=>this.children.every((Y)=>Y.traverseAllows(Q,X));traverseApply=(Q,X)=>{let Y=X.currentErrorCount;if(this.basis){if(this.basis.traverseApply(Q,X),X.currentErrorCount>Y)return}if(this.prestructurals.length){for(let U=0;U<this.prestructurals.length-1;U++)if(this.prestructurals[U].traverseApply(Q,X),X.failFast&&X.currentErrorCount>Y)return;if(this.prestructurals[this.prestructurals.length-1].traverseApply(Q,X),X.currentErrorCount>Y)return}if(this.structure){if(this.structure.traverseApply(Q,X),X.currentErrorCount>Y)return}if(this.inner.predicate){for(let U=0;U<this.inner.predicate.length-1;U++)if(this.inner.predicate[U].traverseApply(Q,X),X.failFast&&X.currentErrorCount>Y)return;this.inner.predicate[this.inner.predicate.length-1].traverseApply(Q,X)}};compile(Q){if(Q.traversalKind==="Allows"){for(let X of this.children)Q.check(X);Q.return(!0);return}if(Q.initializeErrorCount(),this.basis){if(Q.check(this.basis),this.children.length>1)Q.returnIfFail()}if(this.prestructurals.length){for(let X=0;X<this.prestructurals.length-1;X++)Q.check(this.prestructurals[X]),Q.returnIfFailFast();if(Q.check(this.prestructurals[this.prestructurals.length-1]),this.structure||this.inner.predicate)Q.returnIfFail()}if(this.structure){if(Q.check(this.structure),this.inner.predicate)Q.returnIfFail()}if(this.inner.predicate){for(let X=0;X<this.inner.predicate.length-1;X++)Q.check(this.inner.predicate[X]),Q.returnIfFail();Q.check(this.inner.predicate[this.inner.predicate.length-1])}}}var YQ={implementation:jZ,Node:JX},bZ=(Q)=>{if(Q.structure?.expression)return Q.structure.expression;let X=Q.basis&&!Q.prestructurals.some((Z)=>Z.impl.obviatesBasisExpression)?Q.basis.nestableExpression:"",Y=Q.prestructurals.map((Z)=>Z.expression).join(" & "),U=`${X}${X?" ":""}${Y}`;if(U==="Array == 0")return"[]";return U||"unknown"},_X=(Q,X,Y)=>{let U={},Z=Q.proto??Q.domain,W=X.proto??X.domain,G=Z?W?N(Z,W,Y):Z:W;if(G instanceof q)return G;if(G)U[G.kind]=G;return l1({kind:"intersection",baseInner:U,l:d1(Q),r:d1(X),roots:[],ctx:Y})};var yZ=M({kind:"morph",hasAssociatedError:!1,keys:{in:{child:!0,parse:(Q,X)=>X.$.parseSchema(Q)},morphs:{parse:B1,serialize:(Q)=>Q.map((X)=>A(X,"root")?X.json:S(X))},declaredIn:{child:!1,serialize:(Q)=>Q.json},declaredOut:{child:!1,serialize:(Q)=>Q.json}},normalize:(Q)=>Q,defaults:{description:(Q)=>`a morph from ${Q.rawIn.description} to ${Q.rawOut?.description??"unknown"}`},intersections:{morph:(Q,X,Y)=>{if(!Q.hasEqualMorphs(X))return L(fZ(Q.expression,X.expression));let U=N(Q.rawIn,X.rawIn,Y);if(U instanceof q)return U;let Z={morphs:Q.morphs};if(Q.declaredIn||X.declaredIn){let W=N(Q.rawIn,X.rawIn,Y);if(W instanceof q)return W.throw();else Z.declaredIn=W}if(Q.declaredOut||X.declaredOut){let W=N(Q.rawOut,X.rawOut,Y);if(W instanceof q)return W.throw();else Z.declaredOut=W}return U.distribute((W)=>Y.$.node("morph",{...Z,in:W}),Y.$.parseSchema)},...L1("morph",(Q,X,Y)=>{let U=Q.inner.in?N(Q.inner.in,X,Y):X;return U instanceof q?U:U.equals(Q.inner.in)?Q:Y.$.node("morph",{...Q.inner,in:U})})}});class LX extends a{serializedMorphs=this.morphs.map(S);compiledMorphs=`[${this.serializedMorphs}]`;lastMorph=this.inner.morphs[this.inner.morphs.length-1];lastMorphIfNode=A(this.lastMorph,"root")?this.lastMorph:void 0;introspectableIn=this.inner.in;introspectableOut=this.lastMorphIfNode?Object.assign(this.referencesById,this.lastMorphIfNode.referencesById)&&this.lastMorphIfNode.rawOut:void 0;get shallowMorphs(){return Array.isArray(this.inner.in?.shallowMorphs)?[...this.inner.in.shallowMorphs,...this.morphs]:this.morphs}get rawIn(){return this.declaredIn??this.inner.in?.rawIn??F.intrinsic.unknown.internal}get rawOut(){return this.declaredOut??this.introspectableOut??F.intrinsic.unknown.internal}declareIn(Q){return this.$.node("morph",{...this.inner,declaredIn:Q})}declareOut(Q){return this.$.node("morph",{...this.inner,declaredOut:Q})}expression=`(In: ${this.rawIn.expression}) => ${this.lastMorphIfNode?"To":"Out"}<${this.rawOut.expression}>`;get defaultShortDescription(){return this.rawIn.meta.description??this.rawIn.defaultShortDescription}innerToJsonSchema(Q){return Q.fallback.morph({code:"morph",base:this.rawIn.toJsonSchemaRecurse(Q),out:this.introspectableOut?.toJsonSchemaRecurse(Q)??null})}compile(Q){if(Q.traversalKind==="Allows"){if(!this.introspectableIn)return;Q.return(Q.invoke(this.introspectableIn));return}if(this.introspectableIn)Q.line(Q.invoke(this.introspectableIn));Q.line(`ctx.queueMorphs(${this.compiledMorphs})`)}traverseAllows=(Q,X)=>!this.introspectableIn||this.introspectableIn.traverseAllows(Q,X);traverseApply=(Q,X)=>{if(this.introspectableIn)this.introspectableIn.traverseApply(Q,X);X.queueMorphs(this.morphs)};hasEqualMorphs(Q){return $1(this.morphs,Q.morphs,{isEqual:(X,Y)=>X===Y||A(X,"root")&&A(Y,"root")&&X.equals(Y)})}}var UQ={implementation:yZ,Node:LX},fZ=(Q,X)=>`The intersection of distinct morphs at a single path is indeterminate:
|
|
30
30
|
Left: ${Q}
|
|
31
|
-
Right: ${X}`;var
|
|
31
|
+
Right: ${X}`;var vZ=M({kind:"proto",hasAssociatedError:!0,collapsibleKey:"proto",keys:{proto:{serialize:(Q)=>H2(Q)??r(Q)},dateAllowsInvalid:{}},normalize:(Q)=>{let X=typeof Q==="string"?{proto:E1[Q]}:typeof Q==="function"?P(Q)?Q:{proto:Q}:typeof Q.proto==="string"?{...Q,proto:E1[Q.proto]}:Q;if(typeof X.proto!=="function")L(I2.writeInvalidSchemaMessage(X.proto));if(k1(X,"dateAllowsInvalid")&&X.proto!==Date)L(I2.writeBadInvalidDateMessage(X.proto));return X},applyConfig:(Q,X)=>{if(Q.dateAllowsInvalid===void 0&&Q.proto===Date&&X.dateAllowsInvalid)return{...Q,dateAllowsInvalid:!0};return Q},defaults:{description:(Q)=>Q.builtinName?eQ[Q.builtinName]:`an instance of ${Q.proto.name}`,actual:(Q)=>Q instanceof Date&&Q.toString()==="Invalid Date"?"an invalid Date":L2(Q)},intersections:{proto:(Q,X)=>Q.proto===Date&&X.proto===Date?Q.dateAllowsInvalid?X:Q:P6(Q.proto,X.proto)?Q:P6(X.proto,Q.proto)?X:q.init("proto",Q,X),domain:(Q,X)=>X.domain==="object"?Q:q.init("domain",F.intrinsic.object.internal,X)}});class HX extends b1{builtinName=H2(this.proto);serializedConstructor=this.json.proto;requiresInvalidDateCheck=this.proto===Date&&!this.dateAllowsInvalid;traverseAllows=this.requiresInvalidDateCheck?(Q)=>Q instanceof Date&&Q.toString()!=="Invalid Date":(Q)=>Q instanceof this.proto;compiledCondition=`data instanceof ${this.serializedConstructor}${this.requiresInvalidDateCheck?' && data.toString() !== "Invalid Date"':""}`;compiledNegation=`!(${this.compiledCondition})`;innerToJsonSchema(Q){switch(this.builtinName){case"Array":return{type:"array"};case"Date":return Q.fallback.date?.({code:"date",base:{}})??Q.fallback.proto({code:"proto",base:{},proto:this.proto});default:return Q.fallback.proto({code:"proto",base:{},proto:this.proto})}}expression=this.dateAllowsInvalid?"Date | InvalidDate":this.proto.name;get nestableExpression(){return this.dateAllowsInvalid?`(${this.expression})`:this.expression}domain="object";get defaultShortDescription(){return this.description}}var I2={implementation:vZ,Node:HX,writeBadInvalidDateMessage:(Q)=>`dateAllowsInvalid may only be specified with constructor Date (was ${Q.name})`,writeInvalidSchemaMessage:(Q)=>`instanceOf operand must be a function (was ${y(Q)})`};var kZ=M({kind:"union",hasAssociatedError:!0,collapsibleKey:"branches",keys:{ordered:{},branches:{child:!0,parse:(Q,X)=>{let Y=[];for(let U of Q){let Z=A(U,"root")?U.branches:X.$.parseSchema(U).branches;for(let W of Z)if(W.hasKind("morph")){let G=Y.findIndex((_)=>_.hasKind("morph")&&_.hasEqualMorphs(W));if(G===-1)Y.push(W);else{let _=Y[G];Y[G]=X.$.node("morph",{..._.inner,in:_.rawIn.rawOr(W.rawIn)})}}else Y.push(W)}if(!X.def.ordered)Y.sort((U,Z)=>U.hash<Z.hash?-1:1);return Y}}},normalize:(Q)=>K(Q)?{branches:Q}:Q,reduce:(Q,X)=>{let Y=oZ(Q);if(Y.length===1)return Y[0];if(Y.length===Q.branches.length)return;return X.node("union",{...Q,branches:Y},{prereduced:!0})},defaults:{description:(Q)=>Q.distribute((X)=>X.description,s1),expected:(Q)=>{let X=cQ(Q.errors,"propString"),Y=Object.entries(X).map(([U,Z])=>{let W=[];for(let H of Z)_1(W,H.expected);let G=s1(W),_=Z.every((H)=>H.actual===Z[0].actual)?Z[0].actual:B(Z[0].data);return`${U&&`${U} `}must be ${G}${_&&` (was ${_})`}`});return s1(Y)},problem:(Q)=>Q.expected,message:(Q)=>{if(Q.problem[0]==="[")return`value at ${Q.problem}`;return Q.problem}},intersections:{union:(Q,X,Y)=>{if(Q.isNever!==X.isNever)return q.init("presence",Q,X);let U;if(Q.ordered){if(X.ordered)L(sZ(Q.expression,X.expression));if(U=ZQ(X.branches,Q.branches,Y),U instanceof q)U.invert()}else U=ZQ(Q.branches,X.branches,Y);if(U instanceof q)return U;return Y.$.parseSchema(Q.ordered||X.ordered?{branches:U,ordered:!0}:{branches:U})},...L1("union",(Q,X,Y)=>{let U=ZQ(Q.branches,[X],Y);if(U instanceof q)return U;if(U.length===1)return U[0];return Y.$.parseSchema(Q.ordered?{branches:U,ordered:!0}:{branches:U})})}});class $X extends a{isBoolean=this.branches.length===2&&this.branches[0].hasUnit(!1)&&this.branches[1].hasUnit(!0);get branchGroups(){let Q=[],X=-1;for(let Y of this.branches){if(Y.hasKind("unit")&&Y.domain==="boolean"){if(X===-1)X=Q.length,Q.push(Y);else Q[X]=F.intrinsic.boolean;continue}Q.push(Y)}return Q}unitBranches=this.branches.filter((Q)=>Q.rawIn.hasKind("unit"));discriminant=this.discriminate();discriminantJson=this.discriminant?lZ(this.discriminant):null;expression=this.distribute((Q)=>Q.nestableExpression,cZ);createBranchedOptimisticRootApply(){return(Q,X)=>{let Y=this.traverseOptimistic(Q);if(Y!==m)return Y;let U=new U1(Q,this.$.resolvedConfig);return this.traverseApply(Q,U),U.finalize(X)}}get shallowMorphs(){return this.branches.reduce((Q,X)=>_1(Q,X.shallowMorphs),[])}get defaultShortDescription(){return this.distribute((Q)=>Q.defaultShortDescription,s1)}innerToJsonSchema(Q){if(this.branchGroups.length===1&&this.branchGroups[0].equals(F.intrinsic.boolean))return{type:"boolean"};let X=this.branchGroups.map((Y)=>Y.toJsonSchemaRecurse(Q));if(X.every((Y)=>Object.keys(Y).length===1&&k1(Y,"const")))return{enum:X.map((Y)=>Y.const)};return{anyOf:X}}traverseAllows=(Q,X)=>this.branches.some((Y)=>Y.traverseAllows(Q,X));traverseApply=(Q,X)=>{let Y=[];for(let U=0;U<this.branches.length;U++){if(X.pushBranch(),this.branches[U].traverseApply(Q,X),!X.hasError()){if(this.branches[U].includesTransform)return X.queuedMorphs.push(...X.popBranch().queuedMorphs);return X.popBranch()}Y.push(X.popBranch().error)}X.errorFromNodeContext({code:"union",errors:Y,meta:this.meta})};traverseOptimistic=(Q)=>{for(let X=0;X<this.branches.length;X++){let Y=this.branches[X];if(Y.traverseAllows(Q)){if(Y.contextFreeMorph)return Y.contextFreeMorph(Q);return Q}}return m};compile(Q){if(!this.discriminant||this.unitBranches.length===this.branches.length&&this.branches.length===2)return this.compileIndiscriminable(Q);let X=this.discriminant.optionallyChainedPropString;if(this.discriminant.kind==="domain")X=`typeof ${X} === "object" ? ${X} === null ? "null" : "object" : typeof ${X} === "function" ? "object" : typeof ${X}`;let Y=this.discriminant.cases,U=Object.keys(Y),{optimistic:Z}=Q;if(Q.optimistic=!1,Q.block(`switch(${X})`,()=>{for(let J in Y){let $=Y[J],O=J==="default"?J:`case ${J}`,R;if($===!0)R=Z?"data":"true";else if(Z)if($.rootApplyStrategy==="branchedOptimistic")R=Q.invoke($,{kind:"Optimistic"});else if($.contextFreeMorph)R=`${Q.invoke($)} ? ${S($.contextFreeMorph)}(data) : "${m}"`;else R=`${Q.invoke($)} ? data : "${m}"`;else R=Q.invoke($);Q.line(`${O}: return ${R}`)}return Q}),Q.traversalKind==="Allows"){Q.return(Z?`"${m}"`:!1);return}let W=s1(this.discriminant.kind==="domain"?U.map((J)=>{let $=J.slice(1,-1);return $==="function"?u.object:u[$]}):U),G=this.discriminant.path.map((J)=>typeof J==="symbol"?S(J):JSON.stringify(J)),_=JSON.stringify(W),H=this.discriminant.kind==="domain"?`${uZ}[${X}]`:`${mZ}(${X})`;Q.line(`ctx.errorFromNodeContext({
|
|
32
32
|
code: "predicate",
|
|
33
33
|
expected: ${_},
|
|
34
34
|
actual: ${H},
|
|
35
35
|
relativePath: [${G}],
|
|
36
36
|
meta: ${this.compiledMeta}
|
|
37
|
-
})`)}compileIndiscriminable(Q){if(Q.traversalKind==="Apply"){Q.const("errors","[]");for(let X of this.branches)Q.line("ctx.pushBranch()").line(Q.invoke(X)).if("!ctx.hasError()",()=>Q.return(X.includesTransform?"ctx.queuedMorphs.push(...ctx.popBranch().queuedMorphs)":"ctx.popBranch()")).line("errors.push(ctx.popBranch().error)");Q.line(`ctx.errorFromNodeContext({ code: "union", errors, meta: ${this.compiledMeta} })`)}else{let{optimistic:X}=Q;Q.optimistic=!1;for(let Y of this.branches)Q.if(`${Q.invoke(Y)}`,()=>Q.return(X?Y.contextFreeMorph?`${S(Y.contextFreeMorph)}(data)`:"data":!0));Q.return(X?`"${m}"`:!1)}}get nestableExpression(){return this.isBoolean?"boolean":`(${this.expression})`}discriminate(){if(this.branches.length<2||this.isCyclic)return null;if(this.unitBranches.length===this.branches.length){let Z=V(this.unitBranches,(W,G)=>[`${G.rawIn.serializedValue}`,G.hasKind("morph")?G:!0]);return{kind:"unit",path:[],optionallyChainedPropString:"data",cases:Z}}let Q=[];for(let Z=0;Z<this.branches.length-1;Z++){let W=this.branches[Z];for(let G=Z+1;G<this.branches.length;G++){let _=this.branches[G],H=o(W.rawIn,_.rawIn,W.$);if(!(H instanceof q))continue;for(let J of H){if(!J.kind||J.optional)continue;let $,O;if(J.kind==="domain"){let{l:b,r:
|
|
37
|
+
})`)}compileIndiscriminable(Q){if(Q.traversalKind==="Apply"){Q.const("errors","[]");for(let X of this.branches)Q.line("ctx.pushBranch()").line(Q.invoke(X)).if("!ctx.hasError()",()=>Q.return(X.includesTransform?"ctx.queuedMorphs.push(...ctx.popBranch().queuedMorphs)":"ctx.popBranch()")).line("errors.push(ctx.popBranch().error)");Q.line(`ctx.errorFromNodeContext({ code: "union", errors, meta: ${this.compiledMeta} })`)}else{let{optimistic:X}=Q;Q.optimistic=!1;for(let Y of this.branches)Q.if(`${Q.invoke(Y)}`,()=>Q.return(X?Y.contextFreeMorph?`${S(Y.contextFreeMorph)}(data)`:"data":!0));Q.return(X?`"${m}"`:!1)}}get nestableExpression(){return this.isBoolean?"boolean":`(${this.expression})`}discriminate(){if(this.branches.length<2||this.isCyclic)return null;if(this.unitBranches.length===this.branches.length){let Z=V(this.unitBranches,(W,G)=>[`${G.rawIn.serializedValue}`,G.hasKind("morph")?G:!0]);return{kind:"unit",path:[],optionallyChainedPropString:"data",cases:Z}}let Q=[];for(let Z=0;Z<this.branches.length-1;Z++){let W=this.branches[Z];for(let G=Z+1;G<this.branches.length;G++){let _=this.branches[G],H=o(W.rawIn,_.rawIn,W.$);if(!(H instanceof q))continue;for(let J of H){if(!J.kind||J.optional)continue;let $,O;if(J.kind==="domain"){let{l:b,r:F1}=J;$=`"${typeof b==="string"?b:b.domain}"`,O=`"${typeof F1==="string"?F1:F1.domain}"`}else if(J.kind==="unit")$=J.l.serializedValue,O=J.r.serializedValue;else continue;let R=Q.find((b)=>$1(b.path,J.path)&&b.kind===J.kind);if(!R)Q.push({kind:J.kind,cases:{[$]:{branchIndices:[Z],condition:J.l},[O]:{branchIndices:[G],condition:J.r}},path:J.path});else{if(R.cases[$])R.cases[$].branchIndices=_1(R.cases[$].branchIndices,Z);else R.cases[$]??={branchIndices:[Z],condition:J.l};if(R.cases[O])R.cases[O].branchIndices=_1(R.cases[O].branchIndices,G);else R.cases[O]??={branchIndices:[G],condition:J.r}}}}}let X=this.ordered?hZ(Q,this.branches):Q;if(!X.length)return null;let Y=gZ(X,this),U={};for(let Z in Y.best.cases){let W=xZ(Y,Z);if(W===null){U[Z]=!0;continue}if(W.length===this.branches.length)return null;if(this.ordered)W.sort((H,J)=>H.originalIndex-J.originalIndex);let G=W.map((H)=>H.branch),_=G.length===1?G[0]:this.$.node("union",this.ordered?{branches:G,ordered:!0}:G);Object.assign(this.referencesById,_.referencesById),U[Z]=_}if(Y.defaultEntries.length){let Z=Y.defaultEntries.map((W)=>W.branch);U.default=this.$.node("union",this.ordered?{branches:Z,ordered:!0}:Z,{prereduced:!0}),Object.assign(this.referencesById,U.default.referencesById)}return Object.assign(Y.location,{cases:U})}}var gZ=(Q,X)=>{let U=Q.sort((G,_)=>G.path.length===_.path.length?Object.keys(_.cases).length-Object.keys(G.cases).length:G.path.length-_.path.length)[0],Z={kind:U.kind,path:U.path,optionallyChainedPropString:AX(U.path)},W=X.branches.map((G,_)=>({originalIndex:_,branch:G}));return{best:U,location:Z,defaultEntries:W,node:X}},xZ=(Q,X)=>{let Y=Q.best.cases[X],U=pZ(Y.condition,Q.location.path,Q.node.$),Z=[],W=[];for(let G=0;G<Q.defaultEntries.length;G++){let _=Q.defaultEntries[G];if(Y.branchIndices.includes(_.originalIndex)){let H=FX(Q.node.branches[_.originalIndex],Q.location);if(H===null)Z=null;else Z?.push({originalIndex:_.originalIndex,branch:H})}else if(_.branch.hasKind("alias")&&U.hasKind("domain")&&U.domain==="object")Z?.push(_);else{if(_.branch.rawIn.overlaps(U)){let H=FX(_.branch,Q.location);Z?.push({originalIndex:_.originalIndex,branch:H})}W.push(_)}}return Q.defaultEntries=W,Z},hZ=(Q,X)=>{return Q.filter((U)=>{let Z=Object.values(U.cases).map((W)=>W.branchIndices);for(let W=0;W<Z.length-1;W++){let G=Z[W];for(let _=W+1;_<Z.length;_++){let H=Z[_];for(let J of G)for(let $ of H)if(J>$){if(X[J].overlaps(X[$]))return!1}}}return!0})},pZ=(Q,X,Y)=>{let U=Q==="undefined"?Y.node("unit",{unit:void 0}):Q==="null"?Y.node("unit",{unit:null}):Q==="boolean"?Y.units([!0,!1]):Q;for(let Z=X.length-1;Z>=0;Z--){let W=X[Z];U=Y.node("intersection",typeof W==="number"?{proto:"Array",sequence:[...lQ(W).map((G)=>({})),U]}:{domain:"object",required:[{key:W,value:U}]})}return U},AX=(Q)=>Q.reduce((X,Y)=>X+b6(Y,!0),"data"),uZ=S(oQ),mZ=S(B),WQ={implementation:kZ,Node:$X},lZ=(Q)=>({kind:Q.kind,path:Q.path.map((X)=>typeof X==="string"?X:Y1(X)),cases:V(Q.cases,(X,Y)=>[X,Y===!0?Y:Y.hasKind("union")&&Y.discriminantJson?Y.discriminantJson:Y.json])}),dZ={delimiter:" | ",finalDelimiter:" | "},cZ=(Q)=>s1(Q,dZ),s1=(Q,X)=>{let Y=X?.delimiter??", ",U=X?.finalDelimiter??" or ";if(Q.length===0)return"never";if(Q.length===1)return Q[0];if(Q.length===2&&Q[0]==="false"&&Q[1]==="true"||Q[0]==="true"&&Q[1]==="false")return"boolean";let Z={},W=Q.filter((_)=>Z[_]?!1:Z[_]=!0),G=W.pop();return`${W.join(Y)}${W.length?U:""}${G}`},ZQ=(Q,X,Y)=>{let U=X.map(()=>[]);for(let W=0;W<Q.length;W++){let G={};for(let _=0;_<X.length;_++){if(U[_]===null)continue;if(Q[W].equals(X[_])){U[_]=null,G={};break}let H=N(Q[W],X[_],Y);if(H instanceof q)continue;if(H.equals(Q[W])){U[_].push(Q[W]),G={};break}if(H.equals(X[_]))U[_]=null;else G[_]=H}for(let _ in G)U[_][W]=G[_]}let Z=U.flatMap((W,G)=>W?.flatMap((_)=>_.branches)??X[G]);return Z.length===0?q.init("union",Q,X):Z},oZ=({branches:Q,ordered:X})=>{if(Q.length<2)return Q;let Y=Q.map(()=>!0);for(let U=0;U<Q.length;U++)for(let Z=U+1;Z<Q.length&&Y[U]&&Y[Z];Z++){if(Q[U].equals(Q[Z])){Y[Z]=!1;continue}let W=o(Q[U].rawIn,Q[Z].rawIn,Q[0].$);if(W instanceof q)continue;if(!X)iZ(Q[U],Q[Z]);if(W.equals(Q[U].rawIn))Y[U]=!!X;else if(W.equals(Q[Z].rawIn))Y[Z]=!1}return Q.filter((U,Z)=>Y[Z])},iZ=(Q,X)=>{if(!Q.includesTransform&&!X.includesTransform)return;if(!$1(Q.shallowMorphs,X.shallowMorphs))L(qX(Q.expression,X.expression));if(!$1(Q.flatMorphs,X.flatMorphs,{isEqual:(Y,U)=>Y.propString===U.propString&&(Y.node.hasKind("morph")&&U.node.hasKind("morph")?Y.node.hasEqualMorphs(U.node):Y.node.hasKind("intersection")&&U.node.hasKind("intersection")?Y.node.structure?.structuralMorphRef===U.node.structure?.structuralMorphRef:!1)}))L(qX(Q.expression,X.expression))},FX=(Q,X)=>Q.transform((Y,U)=>{if(Y==="domain"||Y==="unit")return null;return U},{shouldTransform:(Y,U)=>{let Z=AX(U.path);if(!X.optionallyChainedPropString.startsWith(Z))return!1;if(Y.hasKind("domain")&&Y.domain==="object")return!0;if((Y.hasKind("domain")||X.kind==="unit")&&Z===X.optionallyChainedPropString)return!0;return Y.children.length!==0&&Y.kind!=="index"}}),qX=(Q,X)=>`An unordered union of a type including a morph and a type with overlapping input is indeterminate:
|
|
38
38
|
Left: ${Q}
|
|
39
|
-
Right: ${X}`,
|
|
39
|
+
Right: ${X}`,sZ=(Q,X)=>`The intersection of two ordered unions is indeterminate:
|
|
40
40
|
Left: ${Q}
|
|
41
|
-
Right: ${X}`;var iZ=B({kind:"unit",hasAssociatedError:!0,keys:{unit:{preserveUndefined:!0,serialize:(Q)=>Q instanceof Date?Q.toISOString():r(Q)}},normalize:(Q)=>Q,defaults:{description:(Q)=>T(Q.unit),problem:({expected:Q,actual:X})=>`${Q===X?`must be reference equal to ${Q} (serialized to the same value)`:`must be ${Q} (was ${X})`}`},intersections:{unit:(Q,X)=>q.init("unit",Q,X),...J1("unit",(Q,X)=>{if(X.allows(Q.unit))return Q;let Y=X.hasKind("intersection")?X.basis:X;if(Y){let U=Y.hasKind("domain")?Y:F.intrinsic.object;if(Q.domain!==U.domain){let Z=Q.domain==="undefined"||Q.domain==="null"||Q.domain==="boolean"?Q.domain:F.intrinsic[Q.domain];return q.init("domain",Z,U)}}return q.init("assignability",Q,X.hasKind("intersection")?X.children.find((U)=>!U.allows(Q.unit)):X)})}});class AX extends b1{compiledValue=this.json.unit;serializedValue=typeof this.unit==="string"||this.unit instanceof Date?JSON.stringify(this.compiledValue):`${this.compiledValue}`;compiledCondition=$X(this.unit,this.serializedValue);compiledNegation=$X(this.unit,this.serializedValue,"negated");expression=T(this.unit);domain=y(this.unit);get defaultShortDescription(){return this.domain==="object"?u.object:this.description}innerToJsonSchema(Q){return this.unit===null?{type:"null"}:F.intrinsic.jsonPrimitive.allows(this.unit)?{const:this.unit}:Q.fallback.unit({code:"unit",base:{},unit:this.unit})}traverseAllows=this.unit instanceof Date?(Q)=>Q instanceof Date&&Q.toISOString()===this.compiledValue:Number.isNaN(this.unit)?(Q)=>Number.isNaN(Q):(Q)=>Q===this.unit}var WQ={implementation:iZ,Node:AX},$X=(Q,X,Y)=>{if(Q instanceof Date){let U=`data instanceof Date && data.toISOString() === ${X}`;return Y?`!(${U})`:U}if(Number.isNaN(Q))return`${Y?"!":""}Number.isNaN(data)`;return`data ${Y?"!":"="}== ${X}`};var sZ=B({kind:"index",hasAssociatedError:!1,intersectionIsOpen:!0,keys:{signature:{child:!0,parse:(Q,X)=>{let Y=X.$.parseSchema(Q);if(!Y.extends(F.intrinsic.key))return L(rZ(Y.expression));let U=Y.branches.filter((Z)=>Z.hasKind("unit"));if(U.length)return L(nZ(U.map((Z)=>T(Z.unit))));return Y}},value:{child:!0,parse:(Q,X)=>X.$.parseSchema(Q)}},normalize:(Q)=>Q,defaults:{description:(Q)=>`[${Q.signature.expression}]: ${Q.value.description}`},intersections:{index:(Q,X,Y)=>{if(Q.signature.equals(X.signature)){let U=P(Q.value,X.value,Y),Z=U instanceof q?F.intrinsic.never.internal:U;return Y.$.node("index",{signature:Q.signature,value:Z})}if(Q.signature.extends(X.signature)&&Q.value.subsumes(X.value))return X;if(X.signature.extends(Q.signature)&&X.value.subsumes(Q.value))return Q;return null}}});class zX extends t{impliedBasis=F.intrinsic.object.internal;expression=`[${this.signature.expression}]: ${this.value.expression}`;flatRefs=R(this.value.flatRefs.map((Q)=>Z1([this.signature,...Q.path],Q.node)),Z1([this.signature],this.value));traverseAllows=(Q,X)=>P1(Q).every((Y)=>{if(this.signature.traverseAllows(Y[0],X))return c(Y[0],()=>this.value.traverseAllows(Y[1],X),X);return!0});traverseApply=(Q,X)=>{for(let Y of P1(Q))if(this.signature.traverseAllows(Y[0],X))c(Y[0],()=>this.value.traverseApply(Y[1],X),X)};_transform(Q,X){X.path.push(this.signature);let Y=super._transform(Q,X);return X.path.pop(),Y}compile(){}}var GQ={implementation:sZ,Node:zX},nZ=(Q)=>`Index keys ${Q.join(", ")} should be specified as named props.`,rZ=(Q)=>`Indexed key definition '${Q}' must be a string or symbol`;var tZ=B({kind:"required",hasAssociatedError:!0,intersectionIsOpen:!0,keys:{key:{},value:{child:!0,parse:(Q,X)=>X.$.parseSchema(Q)}},normalize:(Q)=>Q,defaults:{description:(Q)=>`${Q.compiledKey}: ${Q.value.description}`,expected:(Q)=>Q.missingValueDescription,actual:()=>"missing"},intersections:{required:C2,optional:C2}});class OX extends w2{expression=`${this.compiledKey}: ${this.value.expression}`;errorContext=Object.freeze({code:"required",missingValueDescription:this.value.defaultShortDescription,relativePath:[this.key],meta:this.meta});compiledErrorContext=R1(this.errorContext)}var _Q={implementation:tZ,Node:OX};var aZ=B({kind:"sequence",hasAssociatedError:!1,collapsibleKey:"variadic",keys:{prefix:{child:!0,parse:(Q,X)=>{if(Q.length===0)return;return Q.map((Y)=>X.$.parseSchema(Y))}},optionals:{child:!0,parse:(Q,X)=>{if(Q.length===0)return;return Q.map((Y)=>X.$.parseSchema(Y))}},defaultables:{child:(Q)=>Q.map((X)=>X[0]),parse:(Q,X)=>{if(Q.length===0)return;return Q.map((Y)=>{let U=X.$.parseSchema(Y[0]);return N2(U,Y[1],null),[U,Y[1]]})},serialize:(Q)=>Q.map((X)=>[X[0].collapsibleJson,r(X[1])]),reduceIo:(Q,X,Y)=>{if(Q==="in"){X.optionals=Y.map((U)=>U[0].rawIn);return}X.prefix=Y.map((U)=>U[0].rawOut);return}},variadic:{child:!0,parse:(Q,X)=>X.$.parseSchema(Q,X)},minVariadicLength:{parse:(Q)=>Q===0?void 0:Q},postfix:{child:!0,parse:(Q,X)=>{if(Q.length===0)return;return Q.map((Y)=>X.$.parseSchema(Y))}}},normalize:(Q)=>{if(typeof Q==="string")return{variadic:Q};if("variadic"in Q||"prefix"in Q||"defaultables"in Q||"optionals"in Q||"postfix"in Q||"minVariadicLength"in Q){if(Q.postfix?.length){if(!Q.variadic)return L(Y8);if(Q.optionals?.length||Q.defaultables?.length)return L(LQ)}if(Q.minVariadicLength&&!Q.variadic)return L("minVariadicLength may not be specified without a variadic element");return Q}return{variadic:Q}},reduce:(Q,X)=>{let Y=Q.minVariadicLength??0,U=Q.prefix?.slice()??[],Z=Q.defaultables?.slice()??[],W=Q.optionals?.slice()??[],G=Q.postfix?.slice()??[];if(Q.variadic){while(W[W.length-1]?.equals(Q.variadic))W.pop();if(W.length===0&&Z.length===0)while(U[U.length-1]?.equals(Q.variadic))U.pop(),Y++;while(G[0]?.equals(Q.variadic))G.shift(),Y++}else if(W.length===0&&Z.length===0)U.push(...G.splice(0));if(Y!==Q.minVariadicLength||Q.prefix&&Q.prefix.length!==U.length)return X.node("sequence",{...Q,prefix:U,defaultables:Z,optionals:W,postfix:G,minVariadicLength:Y},{prereduced:!0})},defaults:{description:(Q)=>{if(Q.isVariadicOnly)return`${Q.variadic.nestableExpression}[]`;return`[${Q.tuple.map((Y)=>Y.kind==="defaultables"?`${Y.node.nestableExpression} = ${T(Y.default)}`:Y.kind==="optionals"?`${Y.node.nestableExpression}?`:Y.kind==="variadic"?`...${Y.node.nestableExpression}[]`:Y.node.expression).join(", ")}]`}},intersections:{sequence:(Q,X,Y)=>{let U=S2({l:Q.tuple,r:X.tuple,disjoint:new q,result:[],fixedVariants:[],ctx:Y}),Z=U.disjoint.length===0?[U,...U.fixedVariants]:U.fixedVariants;return Z.length===0?U.disjoint:Z.length===1?Y.$.node("sequence",VX(Z[0].result)):Y.$.node("union",Z.map((W)=>({proto:Array,sequence:VX(W.result)})))}}});class BX extends t{impliedBasis=F.intrinsic.Array.internal;tuple=X8(this.inner);prefixLength=this.prefix?.length??0;defaultablesLength=this.defaultables?.length??0;optionalsLength=this.optionals?.length??0;postfixLength=this.postfix?.length??0;defaultablesAndOptionals=[];prevariadic=this.tuple.filter((Q)=>{if(Q.kind==="defaultables"||Q.kind==="optionals")return this.defaultablesAndOptionals.push(Q.node),!0;return Q.kind==="prefix"});variadicOrPostfix=F1(this.variadic&&[this.variadic],this.postfix);flatRefs=this.addFlatRefs();addFlatRefs(){return k6(this.flatRefs,this.prevariadic.flatMap((Q,X)=>R(Q.node.flatRefs.map((Y)=>Z1([`${X}`,...Y.path],Y.node)),Z1([`${X}`],Q.node)))),k6(this.flatRefs,this.variadicOrPostfix.flatMap((Q)=>R(Q.flatRefs.map((X)=>Z1([F.intrinsic.nonNegativeIntegerString.internal,...X.path],X.node)),Z1([F.intrinsic.nonNegativeIntegerString.internal],Q)))),this.flatRefs}isVariadicOnly=this.prevariadic.length+this.postfixLength===0;minVariadicLength=this.inner.minVariadicLength??0;minLength=this.prefixLength+this.minVariadicLength+this.postfixLength;minLengthNode=this.minLength===0?null:this.$.node("minLength",this.minLength);maxLength=this.variadic?null:this.tuple.length;maxLengthNode=this.maxLength===null?null:this.$.node("maxLength",this.maxLength);impliedSiblings=this.minLengthNode?this.maxLengthNode?[this.minLengthNode,this.maxLengthNode]:[this.minLengthNode]:this.maxLengthNode?[this.maxLengthNode]:[];defaultValueMorphs=Q8(this);defaultValueMorphsReference=this.defaultValueMorphs.length?S(this.defaultValueMorphs):void 0;elementAtIndex(Q,X){if(X<this.prevariadic.length)return this.tuple[X];let Y=Q.length-this.postfixLength;if(X>=Y)return{kind:"postfix",node:this.postfix[X-Y]};return{kind:"variadic",node:this.variadic??C(`Unexpected attempt to access index ${X} on ${this}`)}}traverseAllows=(Q,X)=>{for(let Y=0;Y<Q.length;Y++)if(!this.elementAtIndex(Q,Y).node.traverseAllows(Q[Y],X))return!1;return!0};traverseApply=(Q,X)=>{let Y=0;for(;Y<Q.length;Y++)c(Y,()=>this.elementAtIndex(Q,Y).node.traverseApply(Q[Y],X),X)};get element(){return this.cacheGetter("element",this.$.node("union",this.children))}compile(Q){if(this.prefix)for(let[X,Y]of this.prefix.entries())Q.traverseKey(`${X}`,`data[${X}]`,Y);for(let[X,Y]of this.defaultablesAndOptionals.entries()){let U=`${X+this.prefixLength}`;Q.if(`${U} >= data.length`,()=>Q.traversalKind==="Allows"?Q.return(!0):Q.return()),Q.traverseKey(U,`data[${U}]`,Y)}if(this.variadic){if(this.postfix)Q.const("firstPostfixIndex",`data.length${this.postfix?`- ${this.postfix.length}`:""}`);if(Q.for(`i < ${this.postfix?"firstPostfixIndex":"data.length"}`,()=>Q.traverseKey("i","data[i]",this.variadic),this.prevariadic.length),this.postfix)for(let[X,Y]of this.postfix.entries()){let U=`firstPostfixIndex + ${X}`;Q.traverseKey(U,`data[${U}]`,Y)}}if(Q.traversalKind==="Allows")Q.return(!0)}_transform(Q,X){X.path.push(F.intrinsic.nonNegativeIntegerString.internal);let Y=super._transform(Q,X);return X.path.pop(),Y}expression=this.description;reduceJsonSchema(Q,X){let Y=X.target==="draft-07";if(this.prevariadic.length){let U=this.prevariadic.map((Z)=>{let W=Z.node.toJsonSchemaRecurse(X);if(Z.kind==="defaultables"){let G=typeof Z.default==="function"?Z.default():Z.default;W.default=F.intrinsic.jsonData.allows(G)?G:X.fallback.defaultValue({code:"defaultValue",base:W,value:G})}return W});if(Y)Q.items=U;else Q.prefixItems=U}if(this.minLength)Q.minItems=this.minLength;if(this.variadic){let U=this.variadic.toJsonSchemaRecurse(X);if(Y&&this.prevariadic.length)Q.additionalItems=U;else Q.items=U;if(this.maxLength)Q.maxItems=this.maxLength;if(this.postfix){let Z=this.postfix.map((W)=>W.toJsonSchemaRecurse(X));Q=X.fallback.arrayPostfix({code:"arrayPostfix",base:Q,elements:Z})}}else{if(Y)Q.additionalItems=!1;else Q.items=!1;delete Q.maxItems}return Q}}var eZ={},Q8=(Q)=>{if(!Q.defaultables)return[];let X=[],Y="[",U=Q.prefixLength+Q.defaultablesLength-1;for(let Z=Q.prefixLength;Z<=U;Z++){let[W,G]=Q.defaultables[Z-Q.prefixLength];X.push(QQ(Z,W,G)),Y+=`${Z}: ${W.id} = ${r(G)}, `}return Y+="]",eZ[Y]??=X},JQ={implementation:aZ,Node:BX},X8=(Q)=>{let X=[];if(Q.prefix)for(let Y of Q.prefix)X.push({kind:"prefix",node:Y});if(Q.defaultables)for(let[Y,U]of Q.defaultables)X.push({kind:"defaultables",node:Y,default:U});if(Q.optionals)for(let Y of Q.optionals)X.push({kind:"optionals",node:Y});if(Q.variadic)X.push({kind:"variadic",node:Q.variadic});if(Q.postfix)for(let Y of Q.postfix)X.push({kind:"postfix",node:Y});return X},VX=(Q)=>Q.reduce((X,Y)=>{if(Y.kind==="variadic")X.variadic=Y.node;else if(Y.kind==="defaultables")X.defaultables=R(X.defaultables,[[Y.node,Y.default]]);else X[Y.kind]=R(X[Y.kind],Y.node);return X},{}),LQ="A postfix required element cannot follow an optional or defaultable element",Y8="A postfix element requires a variadic element",S2=(Q)=>{let[X,...Y]=Q.l,[U,...Z]=Q.r;if(!X||!U)return Q;let W=Y[Y.length-1]?.kind==="postfix",G=Z[Z.length-1]?.kind==="postfix",_=X.kind==="prefix"||U.kind==="prefix"?"prefix":X.kind==="postfix"||U.kind==="postfix"?"postfix":X.kind==="variadic"&&U.kind==="variadic"?"variadic":W||G?"prefix":X.kind==="defaultables"||U.kind==="defaultables"?"defaultables":"optionals";if(X.kind==="prefix"&&U.kind==="variadic"&&G){let O=S2({...Q,fixedVariants:[],r:Z.map((D)=>({...D,kind:"prefix"}))});if(O.disjoint.length===0)Q.fixedVariants.push(O)}else if(U.kind==="prefix"&&X.kind==="variadic"&&W){let O=S2({...Q,fixedVariants:[],l:Y.map((D)=>({...D,kind:"prefix"}))});if(O.disjoint.length===0)Q.fixedVariants.push(O)}let H=P(X.node,U.node,Q.ctx);if(H instanceof q)if(_==="prefix"||_==="postfix")Q.disjoint.push(...H.withPrefixKey(_==="prefix"?Q.result.length:`-${Y.length+1}`,TX(X)&&TX(U)?"required":"optional")),Q.result=[...Q.result,{kind:_,node:F.intrinsic.never.internal}];else if(_==="optionals"||_==="defaultables")return Q;else return S2({...Q,fixedVariants:[],l:Y.map((O)=>({...O,kind:"prefix"})),r:Y.map((O)=>({...O,kind:"prefix"}))});else if(_==="defaultables"){if(X.kind==="defaultables"&&U.kind==="defaultables"&&X.default!==U.default)L(e6(X.default,U.default));Q.result=[...Q.result,{kind:_,node:H,default:X.kind==="defaultables"?X.default:U.kind==="defaultables"?U.default:C(`Unexpected defaultable intersection from ${X.kind} and ${U.kind} elements.`)}]}else Q.result=[...Q.result,{kind:_,node:H}];let J=Q.l.length,$=Q.r.length;if(X.kind!=="variadic"||J>=$&&(U.kind==="variadic"||$===1))Q.l=Y;if(U.kind!=="variadic"||$>=J&&(X.kind==="variadic"||J===1))Q.r=Z;return S2(Q)},TX=(Q)=>Q.kind==="prefix"||Q.kind==="postfix";var CX=(Q)=>(X)=>{if(X.props.length||X.index){let Y=X.index?.map((Z)=>Z[Q])??[];for(let Z of X.props)Y.push(Z[Q]);if(X.undeclared)Y.push(`+ (undeclared): ${X.undeclared}`);let U=`{ ${Y.join(", ")} }`;return X.sequence?`${U} & ${X.sequence.description}`:U}return X.sequence?.description??"{}"},U8=CX("description"),Z8=CX("expression"),MX=(Q,X,Y)=>{let U=Q.required?"required":"optional";if(!X.signature.allows(Q.key))return null;let Z=o(Q.value,X.value,Y);if(Z instanceof q)return U==="optional"?Y.node("optional",{key:Q.key,value:F.intrinsic.never.internal}):Z.withPrefixKey(Q.key,Q.kind);return null},W8=B({kind:"structure",hasAssociatedError:!1,normalize:(Q)=>Q,applyConfig:(Q,X)=>{if(!Q.undeclared&&X.onUndeclaredKey!=="ignore")return{...Q,undeclared:X.onUndeclaredKey};return Q},keys:{required:{child:!0,parse:g("required"),reduceIo:(Q,X,Y)=>{X.required=R(X.required,Y.map((U)=>Q==="in"?U.rawIn:U.rawOut));return}},optional:{child:!0,parse:g("optional"),reduceIo:(Q,X,Y)=>{if(Q==="in"){X.optional=Y.map((U)=>U.rawIn);return}for(let U of Y)X[U.outProp.kind]=R(X[U.outProp.kind],U.outProp.rawOut)}},index:{child:!0,parse:g("index")},sequence:{child:!0,parse:g("sequence")},undeclared:{parse:(Q)=>Q==="ignore"?void 0:Q,reduceIo:(Q,X,Y)=>{if(Y==="reject"){X.undeclared="reject";return}if(Q==="in")delete X.undeclared;else X.undeclared="reject"}}},defaults:{description:U8},intersections:{structure:(Q,X,Y)=>{let U={...Q.inner},Z={...X.inner},W=new q;if(Q.undeclared){let H=Q.keyof();for(let J of X.requiredKeys)if(!H.allows(J))W.add("presence",F.intrinsic.never.internal,X.propsByKey[J].value,{path:[J]});if(Z.optional)Z.optional=Z.optional.filter((J)=>H.allows(J.key));if(Z.index)Z.index=Z.index.flatMap((J)=>{if(J.signature.extends(H))return J;let $=o(H,J.signature,Y.$);if($ instanceof q)return[];let O=e2($,J.value,Y.$);if(O.required)Z.required=F1(Z.required,O.required);if(O.optional)Z.optional=F1(Z.optional,O.optional);return O.index??[]})}if(X.undeclared){let H=X.keyof();for(let J of Q.requiredKeys)if(!H.allows(J))W.add("presence",Q.propsByKey[J].value,F.intrinsic.never.internal,{path:[J]});if(U.optional)U.optional=U.optional.filter((J)=>H.allows(J.key));if(U.index)U.index=U.index.flatMap((J)=>{if(J.signature.extends(H))return J;let $=o(H,J.signature,Y.$);if($ instanceof q)return[];let O=e2($,J.value,Y.$);if(O.required)U.required=F1(U.required,O.required);if(O.optional)U.optional=F1(U.optional,O.optional);return O.index??[]})}let G={};if(Q.undeclared||X.undeclared)G.undeclared=Q.undeclared==="reject"||X.undeclared==="reject"?"reject":"delete";let _=l1({kind:"structure",baseInner:G,l:d1(U),r:d1(Z),roots:[],ctx:Y});if(_ instanceof q)W.push(..._);if(W.length)return W;return _}},reduce:(Q,X)=>{if(!Q.required&&!Q.optional)return;let Y={},U=!1,Z=Q.optional?[...Q.optional]:[];if(Q.required)for(let W=0;W<Q.required.length;W++){let G=Q.required[W];if(G.key in Y)L(DX(G.key));if(Y[G.key]=!0,Q.index)for(let _ of Q.index){let H=MX(G,_,X);if(H instanceof q)return H}}if(Q.optional)for(let W=0;W<Q.optional.length;W++){let G=Q.optional[W];if(G.key in Y)L(DX(G.key));if(Y[G.key]=!0,Q.index)for(let _ of Q.index){let H=MX(G,_,X);if(H instanceof q)return H;if(H!==null)Z[W]=H,U=!0}}if(U)return X.node("structure",{...Q,optional:Z},{prereduced:!0})}});class wX extends t{impliedBasis=F.intrinsic.object.internal;impliedSiblings=this.children.flatMap((Q)=>Q.impliedSiblings??[]);props=F1(this.required,this.optional);propsByKey=V(this.props,(Q,X)=>[X.key,X]);propsByKeyReference=S(this.propsByKey);expression=Z8(this);requiredKeys=this.required?.map((Q)=>Q.key)??[];optionalKeys=this.optional?.map((Q)=>Q.key)??[];literalKeys=[...this.requiredKeys,...this.optionalKeys];_keyof;keyof(){if(this._keyof)return this._keyof;let Q=this.$.units(this.literalKeys).branches;if(this.index)for(let{signature:X}of this.index)Q=Q.concat(X.branches);return this._keyof=this.$.node("union",Q)}map(Q){return this.$.node("structure",this.props.flatMap(Q).reduce((X,Y)=>{let U=this.propsByKey[Y.key];if(N(Y)){if(Y.kind!=="required"&&Y.kind!=="optional")return L(`Map result must have kind "required" or "optional" (was ${Y.kind})`);return X[Y.kind]=R(X[Y.kind],Y),X}let Z=Y.kind??U?.kind??"required",W=V(Y,(G,_)=>(G in K2.implementation.keys)?[G,_]:[]);return X[Z]=R(X[Z],this.$.node(Z,W)),X},{}))}assertHasKeys(Q){let X=Q.filter((Y)=>!P2(Y,this.keyof()));if(X.length)return L(RX(this.expression,X))}get(Q,...X){let Y,U=!1,Z=L8(Q);if((typeof Z==="string"||typeof Z==="symbol")&&this.propsByKey[Z])Y=this.propsByKey[Z].value,U=this.propsByKey[Z].required;if(this.index){for(let G of this.index)if(P2(Z,G.signature))Y=Y?.and(G.value)??G.value}if(this.sequence&&P2(Z,F.intrinsic.nonNegativeIntegerString))if(A(Z,"root")){if(this.sequence.variadic)Y=Y?.and(this.sequence.element)??this.sequence.element}else{let G=Number.parseInt(Z);if(G<this.sequence.prevariadic.length){let _=this.sequence.prevariadic[G].node;Y=Y?.and(_)??_,U||=G<this.sequence.prefixLength}else if(this.sequence.variadic){let _=this.$.node("union",this.sequence.variadicOrPostfix);Y=Y?.and(_)??_}}if(!Y){if(this.sequence?.variadic&&A(Z,"root")&&Z.extends(F.intrinsic.number))return L(H8(Z.expression,this.sequence.expression));return L(RX(this.expression,[Z]))}let W=Y.get(...X);return U?W:W.or(F.intrinsic.undefined)}pick(...Q){return this.assertHasKeys(Q),this.$.node("structure",this.filterKeys("pick",Q))}omit(...Q){return this.assertHasKeys(Q),this.$.node("structure",this.filterKeys("omit",Q))}optionalize(){let{required:Q,...X}=this.inner;return this.$.node("structure",{...X,optional:this.props.map((Y)=>Y.hasKind("required")?this.$.node("optional",Y.inner):Y)})}require(){let{optional:Q,...X}=this.inner;return this.$.node("structure",{...X,required:this.props.map((Y)=>Y.hasKind("optional")?{key:Y.key,value:Y.value}:Y)})}merge(Q){let X=this.filterKeys("omit",[Q.keyof()]);if(Q.required)X.required=R(X.required,Q.required);if(Q.optional)X.optional=R(X.optional,Q.optional);if(Q.index)X.index=R(X.index,Q.index);if(Q.sequence)X.sequence=Q.sequence;if(Q.undeclared)X.undeclared=Q.undeclared;else delete X.undeclared;return this.$.node("structure",X)}filterKeys(Q,X){let Y=m2(this.inner),U=(Z)=>{let W=X.some((G)=>P2(Z,G));return Q==="pick"?W:!W};if(Y.required)Y.required=Y.required.filter((Z)=>U(Z.key));if(Y.optional)Y.optional=Y.optional.filter((Z)=>U(Z.key));if(Y.index)Y.index=Y.index.filter((Z)=>U(Z.signature));return Y}traverseAllows=(Q,X)=>this._traverse("Allows",Q,X);traverseApply=(Q,X)=>this._traverse("Apply",Q,X);_traverse=(Q,X,Y)=>{let U=Y?.currentErrorCount??0;for(let Z=0;Z<this.props.length;Z++)if(Q==="Allows"){if(!this.props[Z].traverseAllows(X,Y))return!1}else if(this.props[Z].traverseApply(X,Y),Y.failFast&&Y.currentErrorCount>U)return!1;if(this.sequence){if(Q==="Allows"){if(!this.sequence.traverseAllows(X,Y))return!1}else if(this.sequence.traverseApply(X,Y),Y.failFast&&Y.currentErrorCount>U)return!1}if(this.index||this.undeclared==="reject"){let Z=Object.keys(X);Z.push(...Object.getOwnPropertySymbols(X));for(let W=0;W<Z.length;W++){let G=Z[W];if(this.index){for(let _ of this.index)if(_.signature.traverseAllows(G,Y)){if(Q==="Allows"){if(!c(G,()=>_.value.traverseAllows(X[G],Y),Y))return!1}else if(c(G,()=>_.value.traverseApply(X[G],Y),Y),Y.failFast&&Y.currentErrorCount>U)return!1}}if(this.undeclared==="reject"&&!this.declaresKey(G)){if(Q==="Allows")return!1;if(Y.errorFromNodeContext({code:"predicate",expected:"removed",actual:"",relativePath:[G],meta:this.meta}),Y.failFast)return!1}}}if(this.structuralMorph&&Y&&!Y.hasError())Y.queueMorphs([this.structuralMorph]);return!0};get defaultable(){return this.cacheGetter("defaultable",this.optional?.filter((Q)=>Q.hasDefault())??[])}declaresKey=(Q)=>(Q in this.propsByKey)||this.index?.some((X)=>X.signature.allows(Q))||this.sequence!==void 0&&F.intrinsic.nonNegativeIntegerString.allows(Q);_compileDeclaresKey(Q){let X=[];if(this.props.length)X.push(`k in ${this.propsByKeyReference}`);if(this.index)for(let Y of this.index)X.push(Q.invoke(Y.signature,{kind:"Allows",arg:"k"}));if(this.sequence)X.push("$ark.intrinsic.nonNegativeIntegerString.allows(k)");return X.join(" || ")||"false"}get structuralMorph(){return this.cacheGetter("structuralMorph",_8(this))}structuralMorphRef=this.structuralMorph&&S(this.structuralMorph);compile(Q){if(Q.traversalKind==="Apply")Q.initializeErrorCount();for(let X of this.props)if(Q.check(X),Q.traversalKind==="Apply")Q.returnIfFailFast();if(this.sequence){if(Q.check(this.sequence),Q.traversalKind==="Apply")Q.returnIfFailFast()}if(this.index||this.undeclared==="reject")Q.const("keys","Object.keys(data)"),Q.line("keys.push(...Object.getOwnPropertySymbols(data))"),Q.for("i < keys.length",()=>this.compileExhaustiveEntry(Q));if(Q.traversalKind==="Allows")return Q.return(!0);if(this.structuralMorphRef)Q.if("ctx && !ctx.hasError()",()=>{return Q.line("ctx.queueMorphs(["),J8(Q,this),Q.line("])")})}compileExhaustiveEntry(Q){if(Q.const("k","keys[i]"),this.index)for(let X of this.index)Q.if(`${Q.invoke(X.signature,{arg:"k",kind:"Allows"})}`,()=>Q.traverseKey("k","data[k]",X.value));if(this.undeclared==="reject")Q.if(`!(${this._compileDeclaresKey(Q)})`,()=>{if(Q.traversalKind==="Allows")return Q.return(!1);return Q.line(`ctx.errorFromNodeContext({ code: "predicate", expected: "removed", actual: "", relativePath: [k], meta: ${this.compiledMeta} })`).if("ctx.failFast",()=>Q.return())});return Q}reduceJsonSchema(Q,X){switch(Q.type){case"object":return this.reduceObjectJsonSchema(Q,X);case"array":let Y=this.sequence?.reduceJsonSchema(Q,X)??Q;if(this.props.length||this.index)return X.fallback.arrayObject({code:"arrayObject",base:Y,object:this.reduceObjectJsonSchema({type:"object"},X)});return Y;default:return E.throwInternalOperandError("structure",Q)}}reduceObjectJsonSchema(Q,X){if(this.props.length){Q.properties={};for(let Y of this.props){let U=Y.value.toJsonSchemaRecurse(X);if(typeof Y.key==="symbol"){X.fallback.symbolKey({code:"symbolKey",base:Q,key:Y.key,value:U,optional:Y.optional});continue}if(Y.hasDefault()){let Z=typeof Y.default==="function"?Y.default():Y.default;U.default=F.intrinsic.jsonData.allows(Z)?Z:X.fallback.defaultValue({code:"defaultValue",base:U,value:Z})}Q.properties[Y.key]=U}if(this.requiredKeys.length&&Q.properties)Q.required=this.requiredKeys.filter((Y)=>typeof Y==="string"&&(Y in Q.properties))}if(this.index)for(let Y of this.index){let U=Y.value.toJsonSchemaRecurse(X);if(Y.signature.equals(F.intrinsic.string)){Q.additionalProperties=U;continue}for(let Z of Y.signature.branches){if(!Z.extends(F.intrinsic.string)){Q=X.fallback.symbolKey({code:"symbolKey",base:Q,key:null,value:U,optional:!1});continue}let W={type:"string"};if(Z.hasKind("morph"))W=X.fallback.morph({code:"morph",base:Z.rawIn.toJsonSchemaRecurse(X),out:Z.rawOut.toJsonSchemaRecurse(X)});if(!Z.hasKind("intersection"))return C(`Unexpected index branch kind ${Z.kind}.`);let{pattern:G}=Z.inner;if(G){let _=Object.assign(W,{pattern:G[0].rule});for(let H=1;H<G.length;H++)W=X.fallback.patternIntersection({code:"patternIntersection",base:_,pattern:G[H].rule});Q.patternProperties??={},Q.patternProperties[_.pattern]=U}}}if(this.undeclared&&!Q.additionalProperties)Q.additionalProperties=!1;return Q}}var HQ={},G8=(Q)=>{let X="";for(let Y=0;Y<Q.defaultable.length;Y++)X+=Q.defaultable[Y].defaultValueMorphRef;if(Q.sequence?.defaultValueMorphsReference)X+=Q.sequence?.defaultValueMorphsReference;if(Q.undeclared==="delete"){if(X+="delete !(",Q.required)for(let Y of Q.required)X+=Y.compiledKey+" | ";if(Q.optional)for(let Y of Q.optional)X+=Y.compiledKey+" | ";if(Q.index)for(let Y of Q.index)X+=Y.signature.id+" | ";if(Q.sequence)if(Q.sequence.maxLength===null)X+=z.nonNegativeIntegerString.id;else for(let Y=0;Y<Q.sequence.tuple.length;Y++)X+=Y+" | ";X+=")"}return X},_8=(Q)=>{let X=G8(Q);if(!X)return;if(HQ[X])return HQ[X];let Y=(U,Z)=>{for(let W=0;W<Q.defaultable.length;W++)if(!(Q.defaultable[W].key in U))Q.defaultable[W].defaultValueMorph(U,Z);if(Q.sequence?.defaultables)for(let W=U.length-Q.sequence.prefixLength;W<Q.sequence.defaultables.length;W++)Q.sequence.defaultValueMorphs[W](U,Z);if(Q.undeclared==="delete"){for(let W in U)if(!Q.declaresKey(W))delete U[W]}return U};return HQ[X]=Y},J8=(Q,X)=>{let U=`(data${X.defaultable.some((Z)=>Z.defaultValueMorph.length===2)||X.sequence?.defaultValueMorphs.some((Z)=>Z.length===2)?", ctx":""})`;return Q.block(`${U} => `,(Z)=>{for(let W=0;W<X.defaultable.length;W++){let{serializedKey:G,defaultValueMorphRef:_}=X.defaultable[W];Z.if(`!(${G} in data)`,(H)=>H.line(`${_}${U}`))}if(X.sequence?.defaultables)Z.for(`i < ${X.sequence.defaultables.length}`,(W)=>W.set("data[i]",5),`data.length - ${X.sequence.prefixLength}`);if(X.undeclared==="delete")Z.forIn("data",(W)=>W.if(`!(${X._compileDeclaresKey(W)})`,(G)=>G.line("delete data[k]")));return Z.return("data")})},FQ={implementation:W8,Node:wX},L8=(Q)=>{if(A(Q,"root")&&Q.hasKind("unit"))Q=Q.unit;if(typeof Q==="number")Q=`${Q}`;return Q},H8=(Q,X)=>`${Q} is not allowed as an array index on ${X}. Use the 'nonNegativeIntegerString' keyword instead.`,e2=(Q,X,Y)=>{let[U,Z]=pQ(Q.branches,(G)=>G.hasKind("unit"));if(!U.length)return{index:Y.node("index",{signature:Q,value:X})};let W={};for(let G of U){let _=Y.node("required",{key:G.unit,value:X});W[_.kind]=R(W[_.kind],_)}if(Z.length)W.index=Y.node("index",{signature:Z,value:X});return W},F8=(Q)=>A(Q,"root")?Q.expression:T(Q),RX=(Q,X)=>`Key${X.length===1?"":"s"} ${X.map(F8).join(", ")} ${X.length===1?"does":"do"} not exist on ${Q}`,DX=(Q)=>`Duplicate key ${Y1(Q)}`;var o1={...d4,alias:E2.implementation,domain:a2.implementation,unit:WQ.implementation,proto:I2.implementation,union:ZQ.implementation,morph:YQ.implementation,intersection:XQ.implementation,divisor:u6.implementation,pattern:n6.implementation,predicate:p6.implementation,required:_Q.implementation,optional:K2.implementation,index:GQ.implementation,sequence:JQ.implementation,structure:FQ.implementation};F.defaultConfig=nQ(Object.assign(V(o1,(Q,X)=>[Q,X.defaults]),{jitless:X4(),clone:aQ,onUndeclaredKey:"ignore",exactOptionalPropertyTypes:!0,numberAllowsNaN:!1,dateAllowsInvalid:!1,onFail:null,keywords:{},toJsonSchema:E.defaultConfig}));F.resolvedConfig=T2(F.defaultConfig,F.config);var r4={...c4,alias:E2.Node,domain:a2.Node,unit:WQ.Node,proto:I2.Node,union:ZQ.Node,morph:YQ.Node,intersection:XQ.Node,divisor:u6.Node,pattern:n6.Node,predicate:p6.Node,required:_Q.Node,optional:K2.Node,index:GQ.Node,sequence:JQ.Node,structure:FQ.Node};class n1 extends R6{get[x](){return"module"}}var qQ=(Q,X)=>new n1(V(Q,(Y,U)=>[Y,A(U,"module")?qQ(U,X):X.bindReference(U)]));var q8=(Q)=>K(Q)?Q:("branches"in Q)&&K(Q.branches)?Q.branches:void 0,$8=(Q,X)=>L(`Node of kind ${X} is not valid as a ${Q} definition`),KX=(Q)=>`#${Q} duplicates public alias ${Q}`,$Q={};F.ambient??={};var NX,EX="function $",A8=(Q)=>IX(Q,SX(Q)),IX=(Q,X)=>{let Y=X.write(EX,4),U=X.compile()();for(let Z of Q){if(Z.precompilation)continue;if(Z.traverseAllows=U[`${Z.id}Allows`].bind(U),Z.isRoot()&&!Z.allowsRequiresContext)Z.allows=Z.traverseAllows;if(Z.traverseApply=U[`${Z.id}Apply`].bind(U),U[`${Z.id}Optimistic`])Z.traverseOptimistic=U[`${Z.id}Optimistic`].bind(U);Z.precompilation=Y}},SX=(Q)=>new u2().return(Q.reduce((X,Y)=>{let U=new V2({kind:"Allows"}).indent();Y.compile(U);let Z=U.write(`${Y.id}Allows`),W=new V2({kind:"Apply"}).indent();Y.compile(W);let G=W.write(`${Y.id}Apply`),_=`${X}${Z},
|
|
41
|
+
Right: ${X}`;var nZ=M({kind:"unit",hasAssociatedError:!0,keys:{unit:{preserveUndefined:!0,serialize:(Q)=>Q instanceof Date?Q.toISOString():r(Q)}},normalize:(Q)=>Q,defaults:{description:(Q)=>B(Q.unit),problem:({expected:Q,actual:X})=>`${Q===X?`must be reference equal to ${Q} (serialized to the same value)`:`must be ${Q} (was ${X})`}`},intersections:{unit:(Q,X)=>q.init("unit",Q,X),...L1("unit",(Q,X)=>{if(X.allows(Q.unit))return Q;let Y=X.hasKind("intersection")?X.basis:X;if(Y){let U=Y.hasKind("domain")?Y:F.intrinsic.object;if(Q.domain!==U.domain){let Z=Q.domain==="undefined"||Q.domain==="null"||Q.domain==="boolean"?Q.domain:F.intrinsic[Q.domain];return q.init("domain",Z,U)}}return q.init("assignability",Q,X.hasKind("intersection")?X.children.find((U)=>!U.allows(Q.unit)):X)})}});class OX extends b1{compiledValue=this.json.unit;serializedValue=typeof this.unit==="string"||this.unit instanceof Date?JSON.stringify(this.compiledValue):`${this.compiledValue}`;compiledCondition=zX(this.unit,this.serializedValue);compiledNegation=zX(this.unit,this.serializedValue,"negated");expression=B(this.unit);domain=y(this.unit);get defaultShortDescription(){return this.domain==="object"?u.object:this.description}innerToJsonSchema(Q){return this.unit===null?{type:"null"}:F.intrinsic.jsonPrimitive.allows(this.unit)?{const:this.unit}:Q.fallback.unit({code:"unit",base:{},unit:this.unit})}traverseAllows=this.unit instanceof Date?(Q)=>Q instanceof Date&&Q.toISOString()===this.compiledValue:Number.isNaN(this.unit)?(Q)=>Number.isNaN(Q):(Q)=>Q===this.unit}var GQ={implementation:nZ,Node:OX},zX=(Q,X,Y)=>{if(Q instanceof Date){let U=`data instanceof Date && data.toISOString() === ${X}`;return Y?`!(${U})`:U}if(Number.isNaN(Q))return`${Y?"!":""}Number.isNaN(data)`;return`data ${Y?"!":"="}== ${X}`};var rZ=M({kind:"index",hasAssociatedError:!1,intersectionIsOpen:!0,keys:{signature:{child:!0,parse:(Q,X)=>{let Y=X.$.parseSchema(Q);if(!Y.extends(F.intrinsic.key))return L(aZ(Y.expression));let U=Y.branches.filter((Z)=>Z.hasKind("unit"));if(U.length)return L(tZ(U.map((Z)=>B(Z.unit))));return Y}},value:{child:!0,parse:(Q,X)=>X.$.parseSchema(Q)}},normalize:(Q)=>Q,defaults:{description:(Q)=>`[${Q.signature.expression}]: ${Q.value.description}`},intersections:{index:(Q,X,Y)=>{if(Q.signature.equals(X.signature)){let U=N(Q.value,X.value,Y),Z=U instanceof q?F.intrinsic.never.internal:U;return Y.$.node("index",{signature:Q.signature,value:Z})}if(Q.signature.extends(X.signature)&&Q.value.subsumes(X.value))return X;if(X.signature.extends(Q.signature)&&X.value.subsumes(Q.value))return Q;return null}}});class VX extends t{impliedBasis=F.intrinsic.object.internal;expression=`[${this.signature.expression}]: ${this.value.expression}`;flatRefs=D(this.value.flatRefs.map((Q)=>Z1([this.signature,...Q.path],Q.node)),Z1([this.signature],this.value));traverseAllows=(Q,X)=>N1(Q).every((Y)=>{if(this.signature.traverseAllows(Y[0],X))return c(Y[0],()=>this.value.traverseAllows(Y[1],X),X);return!0});traverseApply=(Q,X)=>{for(let Y of N1(Q))if(this.signature.traverseAllows(Y[0],X))c(Y[0],()=>this.value.traverseApply(Y[1],X),X)};_transform(Q,X){X.path.push(this.signature);let Y=super._transform(Q,X);return X.path.pop(),Y}compile(){}}var _Q={implementation:rZ,Node:VX},tZ=(Q)=>`Index keys ${Q.join(", ")} should be specified as named props.`,aZ=(Q)=>`Indexed key definition '${Q}' must be a string or symbol`;var eZ=M({kind:"required",hasAssociatedError:!0,intersectionIsOpen:!0,keys:{key:{},value:{child:!0,parse:(Q,X)=>X.$.parseSchema(Q)}},normalize:(Q)=>Q,defaults:{description:(Q)=>`${Q.compiledKey}: ${Q.value.description}`,expected:(Q)=>Q.missingValueDescription,actual:()=>"missing"},intersections:{required:C2,optional:C2}});class BX extends w2{expression=`${this.compiledKey}: ${this.value.expression}`;errorContext=Object.freeze({code:"required",missingValueDescription:this.value.defaultShortDescription,relativePath:[this.key],meta:this.meta});compiledErrorContext=R1(this.errorContext)}var JQ={implementation:eZ,Node:BX};var Q8=M({kind:"sequence",hasAssociatedError:!1,collapsibleKey:"variadic",keys:{prefix:{child:!0,parse:(Q,X)=>{if(Q.length===0)return;return Q.map((Y)=>X.$.parseSchema(Y))}},optionals:{child:!0,parse:(Q,X)=>{if(Q.length===0)return;return Q.map((Y)=>X.$.parseSchema(Y))}},defaultables:{child:(Q)=>Q.map((X)=>X[0]),parse:(Q,X)=>{if(Q.length===0)return;return Q.map((Y)=>{let U=X.$.parseSchema(Y[0]);return P2(U,Y[1],null),[U,Y[1]]})},serialize:(Q)=>Q.map((X)=>[X[0].collapsibleJson,r(X[1])]),reduceIo:(Q,X,Y)=>{if(Q==="in"){X.optionals=Y.map((U)=>U[0].rawIn);return}X.prefix=Y.map((U)=>U[0].rawOut);return}},variadic:{child:!0,parse:(Q,X)=>X.$.parseSchema(Q,X)},minVariadicLength:{parse:(Q)=>Q===0?void 0:Q},postfix:{child:!0,parse:(Q,X)=>{if(Q.length===0)return;return Q.map((Y)=>X.$.parseSchema(Y))}}},normalize:(Q)=>{if(typeof Q==="string")return{variadic:Q};if("variadic"in Q||"prefix"in Q||"defaultables"in Q||"optionals"in Q||"postfix"in Q||"minVariadicLength"in Q){if(Q.postfix?.length){if(!Q.variadic)return L(Z8);if(Q.optionals?.length||Q.defaultables?.length)return L(HQ)}if(Q.minVariadicLength&&!Q.variadic)return L("minVariadicLength may not be specified without a variadic element");return Q}return{variadic:Q}},reduce:(Q,X)=>{let Y=Q.minVariadicLength??0,U=Q.prefix?.slice()??[],Z=Q.defaultables?.slice()??[],W=Q.optionals?.slice()??[],G=Q.postfix?.slice()??[];if(Q.variadic){while(W[W.length-1]?.equals(Q.variadic))W.pop();if(W.length===0&&Z.length===0)while(U[U.length-1]?.equals(Q.variadic))U.pop(),Y++;while(G[0]?.equals(Q.variadic))G.shift(),Y++}else if(W.length===0&&Z.length===0)U.push(...G.splice(0));if(Y!==Q.minVariadicLength||Q.prefix&&Q.prefix.length!==U.length)return X.node("sequence",{...Q,prefix:U,defaultables:Z,optionals:W,postfix:G,minVariadicLength:Y},{prereduced:!0})},defaults:{description:(Q)=>{if(Q.isVariadicOnly)return`${Q.variadic.nestableExpression}[]`;return`[${Q.tuple.map((Y)=>Y.kind==="defaultables"?`${Y.node.nestableExpression} = ${B(Y.default)}`:Y.kind==="optionals"?`${Y.node.nestableExpression}?`:Y.kind==="variadic"?`...${Y.node.nestableExpression}[]`:Y.node.expression).join(", ")}]`}},intersections:{sequence:(Q,X,Y)=>{let U=S2({l:Q.tuple,r:X.tuple,disjoint:new q,result:[],fixedVariants:[],ctx:Y}),Z=U.disjoint.length===0?[U,...U.fixedVariants]:U.fixedVariants;return Z.length===0?U.disjoint:Z.length===1?Y.$.node("sequence",MX(Z[0].result)):Y.$.node("union",Z.map((W)=>({proto:Array,sequence:MX(W.result)})))}}});class DX extends t{impliedBasis=F.intrinsic.Array.internal;tuple=U8(this.inner);prefixLength=this.prefix?.length??0;defaultablesLength=this.defaultables?.length??0;optionalsLength=this.optionals?.length??0;postfixLength=this.postfix?.length??0;defaultablesAndOptionals=[];prevariadic=this.tuple.filter((Q)=>{if(Q.kind==="defaultables"||Q.kind==="optionals")return this.defaultablesAndOptionals.push(Q.node),!0;return Q.kind==="prefix"});variadicOrPostfix=q1(this.variadic&&[this.variadic],this.postfix);flatRefs=this.addFlatRefs();addFlatRefs(){return g6(this.flatRefs,this.prevariadic.flatMap((Q,X)=>D(Q.node.flatRefs.map((Y)=>Z1([`${X}`,...Y.path],Y.node)),Z1([`${X}`],Q.node)))),g6(this.flatRefs,this.variadicOrPostfix.flatMap((Q)=>D(Q.flatRefs.map((X)=>Z1([F.intrinsic.nonNegativeIntegerString.internal,...X.path],X.node)),Z1([F.intrinsic.nonNegativeIntegerString.internal],Q)))),this.flatRefs}isVariadicOnly=this.prevariadic.length+this.postfixLength===0;minVariadicLength=this.inner.minVariadicLength??0;minLength=this.prefixLength+this.minVariadicLength+this.postfixLength;minLengthNode=this.minLength===0?null:this.$.node("minLength",this.minLength);maxLength=this.variadic?null:this.tuple.length;maxLengthNode=this.maxLength===null?null:this.$.node("maxLength",this.maxLength);impliedSiblings=this.minLengthNode?this.maxLengthNode?[this.minLengthNode,this.maxLengthNode]:[this.minLengthNode]:this.maxLengthNode?[this.maxLengthNode]:[];defaultValueMorphs=Y8(this);defaultValueMorphsReference=this.defaultValueMorphs.length?S(this.defaultValueMorphs):void 0;elementAtIndex(Q,X){if(X<this.prevariadic.length)return this.tuple[X];let Y=Q.length-this.postfixLength;if(X>=Y)return{kind:"postfix",node:this.postfix[X-Y]};return{kind:"variadic",node:this.variadic??C(`Unexpected attempt to access index ${X} on ${this}`)}}traverseAllows=(Q,X)=>{for(let Y=0;Y<Q.length;Y++)if(!this.elementAtIndex(Q,Y).node.traverseAllows(Q[Y],X))return!1;return!0};traverseApply=(Q,X)=>{let Y=0;for(;Y<Q.length;Y++)c(Y,()=>this.elementAtIndex(Q,Y).node.traverseApply(Q[Y],X),X)};get element(){return this.cacheGetter("element",this.$.node("union",this.children))}compile(Q){if(this.prefix)for(let[X,Y]of this.prefix.entries())Q.traverseKey(`${X}`,`data[${X}]`,Y);for(let[X,Y]of this.defaultablesAndOptionals.entries()){let U=`${X+this.prefixLength}`;Q.if(`${U} >= data.length`,()=>Q.traversalKind==="Allows"?Q.return(!0):Q.return()),Q.traverseKey(U,`data[${U}]`,Y)}if(this.variadic){if(this.postfix)Q.const("firstPostfixIndex",`data.length${this.postfix?`- ${this.postfix.length}`:""}`);if(Q.for(`i < ${this.postfix?"firstPostfixIndex":"data.length"}`,()=>Q.traverseKey("i","data[i]",this.variadic),this.prevariadic.length),this.postfix)for(let[X,Y]of this.postfix.entries()){let U=`firstPostfixIndex + ${X}`;Q.traverseKey(U,`data[${U}]`,Y)}}if(Q.traversalKind==="Allows")Q.return(!0)}_transform(Q,X){X.path.push(F.intrinsic.nonNegativeIntegerString.internal);let Y=super._transform(Q,X);return X.path.pop(),Y}expression=this.description;reduceJsonSchema(Q,X){let Y=X.target==="draft-07";if(this.prevariadic.length){let U=this.prevariadic.map((Z)=>{let W=Z.node.toJsonSchemaRecurse(X);if(Z.kind==="defaultables"){let G=typeof Z.default==="function"?Z.default():Z.default;W.default=F.intrinsic.jsonData.allows(G)?G:X.fallback.defaultValue({code:"defaultValue",base:W,value:G})}return W});if(Y)Q.items=U;else Q.prefixItems=U}if(this.minLength)Q.minItems=this.minLength;if(this.variadic){let U=this.variadic.toJsonSchemaRecurse(X);if(Y&&this.prevariadic.length)Q.additionalItems=U;else Q.items=U;if(this.maxLength)Q.maxItems=this.maxLength;if(this.postfix){let Z=this.postfix.map((W)=>W.toJsonSchemaRecurse(X));Q=X.fallback.arrayPostfix({code:"arrayPostfix",base:Q,elements:Z})}}else{if(Y)Q.additionalItems=!1;else Q.items=!1;delete Q.maxItems}return Q}}var X8={},Y8=(Q)=>{if(!Q.defaultables)return[];let X=[],Y="[",U=Q.prefixLength+Q.defaultablesLength-1;for(let Z=Q.prefixLength;Z<=U;Z++){let[W,G]=Q.defaultables[Z-Q.prefixLength];X.push(XQ(Z,W,G)),Y+=`${Z}: ${W.id} = ${r(G)}, `}return Y+="]",X8[Y]??=X},LQ={implementation:Q8,Node:DX},U8=(Q)=>{let X=[];if(Q.prefix)for(let Y of Q.prefix)X.push({kind:"prefix",node:Y});if(Q.defaultables)for(let[Y,U]of Q.defaultables)X.push({kind:"defaultables",node:Y,default:U});if(Q.optionals)for(let Y of Q.optionals)X.push({kind:"optionals",node:Y});if(Q.variadic)X.push({kind:"variadic",node:Q.variadic});if(Q.postfix)for(let Y of Q.postfix)X.push({kind:"postfix",node:Y});return X},MX=(Q)=>Q.reduce((X,Y)=>{if(Y.kind==="variadic")X.variadic=Y.node;else if(Y.kind==="defaultables")X.defaultables=D(X.defaultables,[[Y.node,Y.default]]);else X[Y.kind]=D(X[Y.kind],Y.node);return X},{}),HQ="A postfix required element cannot follow an optional or defaultable element",Z8="A postfix element requires a variadic element",S2=(Q)=>{let[X,...Y]=Q.l,[U,...Z]=Q.r;if(!X||!U)return Q;let W=Y[Y.length-1]?.kind==="postfix",G=Z[Z.length-1]?.kind==="postfix",_=X.kind==="prefix"||U.kind==="prefix"?"prefix":X.kind==="postfix"||U.kind==="postfix"?"postfix":X.kind==="variadic"&&U.kind==="variadic"?"variadic":W||G?"prefix":X.kind==="defaultables"||U.kind==="defaultables"?"defaultables":"optionals";if(X.kind==="prefix"&&U.kind==="variadic"&&G){let O=S2({...Q,fixedVariants:[],r:Z.map((R)=>({...R,kind:"prefix"}))});if(O.disjoint.length===0)Q.fixedVariants.push(O)}else if(U.kind==="prefix"&&X.kind==="variadic"&&W){let O=S2({...Q,fixedVariants:[],l:Y.map((R)=>({...R,kind:"prefix"}))});if(O.disjoint.length===0)Q.fixedVariants.push(O)}let H=N(X.node,U.node,Q.ctx);if(H instanceof q)if(_==="prefix"||_==="postfix")Q.disjoint.push(...H.withPrefixKey(_==="prefix"?Q.result.length:`-${Y.length+1}`,TX(X)&&TX(U)?"required":"optional")),Q.result=[...Q.result,{kind:_,node:F.intrinsic.never.internal}];else if(_==="optionals"||_==="defaultables")return Q;else return S2({...Q,fixedVariants:[],l:Y.map((O)=>({...O,kind:"prefix"})),r:Y.map((O)=>({...O,kind:"prefix"}))});else if(_==="defaultables"){if(X.kind==="defaultables"&&U.kind==="defaultables"&&X.default!==U.default)L(QQ(X.default,U.default));Q.result=[...Q.result,{kind:_,node:H,default:X.kind==="defaultables"?X.default:U.kind==="defaultables"?U.default:C(`Unexpected defaultable intersection from ${X.kind} and ${U.kind} elements.`)}]}else Q.result=[...Q.result,{kind:_,node:H}];let J=Q.l.length,$=Q.r.length;if(X.kind!=="variadic"||J>=$&&(U.kind==="variadic"||$===1))Q.l=Y;if(U.kind!=="variadic"||$>=J&&(X.kind==="variadic"||J===1))Q.r=Z;return S2(Q)},TX=(Q)=>Q.kind==="prefix"||Q.kind==="postfix";var KX=(Q)=>(X)=>{if(X.props.length||X.index){let Y=X.index?.map((Z)=>Z[Q])??[];for(let Z of X.props)Y.push(Z[Q]);if(X.undeclared)Y.push(`+ (undeclared): ${X.undeclared}`);let U=`{ ${Y.join(", ")} }`;return X.sequence?`${U} & ${X.sequence.description}`:U}return X.sequence?.description??"{}"},W8=KX("description"),G8=KX("expression"),RX=(Q,X,Y)=>{let U=Q.required?"required":"optional";if(!X.signature.allows(Q.key))return null;let Z=o(Q.value,X.value,Y);if(Z instanceof q)return U==="optional"?Y.node("optional",{key:Q.key,value:F.intrinsic.never.internal}):Z.withPrefixKey(Q.key,Q.kind);return null},_8=M({kind:"structure",hasAssociatedError:!1,normalize:(Q)=>Q,applyConfig:(Q,X)=>{if(!Q.undeclared&&X.onUndeclaredKey!=="ignore")return{...Q,undeclared:X.onUndeclaredKey};return Q},keys:{required:{child:!0,parse:g("required"),reduceIo:(Q,X,Y)=>{X.required=D(X.required,Y.map((U)=>Q==="in"?U.rawIn:U.rawOut));return}},optional:{child:!0,parse:g("optional"),reduceIo:(Q,X,Y)=>{if(Q==="in"){X.optional=Y.map((U)=>U.rawIn);return}for(let U of Y)X[U.outProp.kind]=D(X[U.outProp.kind],U.outProp.rawOut)}},index:{child:!0,parse:g("index")},sequence:{child:!0,parse:g("sequence")},undeclared:{parse:(Q)=>Q==="ignore"?void 0:Q,reduceIo:(Q,X,Y)=>{if(Y==="reject"){X.undeclared="reject";return}if(Q==="in")delete X.undeclared;else X.undeclared="reject"}}},defaults:{description:W8},intersections:{structure:(Q,X,Y)=>{let U={...Q.inner},Z={...X.inner},W=new q;if(Q.undeclared){let H=Q.keyof();for(let J of X.requiredKeys)if(!H.allows(J))W.add("presence",F.intrinsic.never.internal,X.propsByKey[J].value,{path:[J]});if(Z.optional)Z.optional=Z.optional.filter((J)=>H.allows(J.key));if(Z.index)Z.index=Z.index.flatMap((J)=>{if(J.signature.extends(H))return J;let $=o(H,J.signature,Y.$);if($ instanceof q)return[];let O=Q6($,J.value,Y.$);if(O.required)Z.required=q1(Z.required,O.required);if(O.optional)Z.optional=q1(Z.optional,O.optional);return O.index??[]})}if(X.undeclared){let H=X.keyof();for(let J of Q.requiredKeys)if(!H.allows(J))W.add("presence",Q.propsByKey[J].value,F.intrinsic.never.internal,{path:[J]});if(U.optional)U.optional=U.optional.filter((J)=>H.allows(J.key));if(U.index)U.index=U.index.flatMap((J)=>{if(J.signature.extends(H))return J;let $=o(H,J.signature,Y.$);if($ instanceof q)return[];let O=Q6($,J.value,Y.$);if(O.required)U.required=q1(U.required,O.required);if(O.optional)U.optional=q1(U.optional,O.optional);return O.index??[]})}let G={};if(Q.undeclared||X.undeclared)G.undeclared=Q.undeclared==="reject"||X.undeclared==="reject"?"reject":"delete";let _=l1({kind:"structure",baseInner:G,l:d1(U),r:d1(Z),roots:[],ctx:Y});if(_ instanceof q)W.push(..._);if(W.length)return W;return _}},reduce:(Q,X)=>{if(!Q.required&&!Q.optional)return;let Y={},U=!1,Z=Q.optional?[...Q.optional]:[];if(Q.required)for(let W=0;W<Q.required.length;W++){let G=Q.required[W];if(G.key in Y)L(wX(G.key));if(Y[G.key]=!0,Q.index)for(let _ of Q.index){let H=RX(G,_,X);if(H instanceof q)return H}}if(Q.optional)for(let W=0;W<Q.optional.length;W++){let G=Q.optional[W];if(G.key in Y)L(wX(G.key));if(Y[G.key]=!0,Q.index)for(let _ of Q.index){let H=RX(G,_,X);if(H instanceof q)return H;if(H!==null)Z[W]=H,U=!0}}if(U)return X.node("structure",{...Q,optional:Z},{prereduced:!0})}});class PX extends t{impliedBasis=F.intrinsic.object.internal;impliedSiblings=this.children.flatMap((Q)=>Q.impliedSiblings??[]);props=q1(this.required,this.optional);propsByKey=V(this.props,(Q,X)=>[X.key,X]);propsByKeyReference=S(this.propsByKey);expression=G8(this);requiredKeys=this.required?.map((Q)=>Q.key)??[];optionalKeys=this.optional?.map((Q)=>Q.key)??[];literalKeys=[...this.requiredKeys,...this.optionalKeys];_keyof;keyof(){if(this._keyof)return this._keyof;let Q=this.$.units(this.literalKeys).branches;if(this.index)for(let{signature:X}of this.index)Q=Q.concat(X.branches);return this._keyof=this.$.node("union",Q)}map(Q){return this.$.node("structure",this.props.flatMap(Q).reduce((X,Y)=>{let U=this.propsByKey[Y.key];if(P(Y)){if(Y.kind!=="required"&&Y.kind!=="optional")return L(`Map result must have kind "required" or "optional" (was ${Y.kind})`);return X[Y.kind]=D(X[Y.kind],Y),X}let Z=Y.kind??U?.kind??"required",W=V(Y,(G,_)=>(G in K2.implementation.keys)?[G,_]:[]);return X[Z]=D(X[Z],this.$.node(Z,W)),X},{}))}assertHasKeys(Q){let X=Q.filter((Y)=>!N2(Y,this.keyof()));if(X.length)return L(CX(this.expression,X))}get(Q,...X){let Y,U=!1,Z=F8(Q);if((typeof Z==="string"||typeof Z==="symbol")&&this.propsByKey[Z])Y=this.propsByKey[Z].value,U=this.propsByKey[Z].required;if(this.index){for(let G of this.index)if(N2(Z,G.signature))Y=Y?.and(G.value)??G.value}if(this.sequence&&N2(Z,F.intrinsic.nonNegativeIntegerString))if(A(Z,"root")){if(this.sequence.variadic)Y=Y?.and(this.sequence.element)??this.sequence.element}else{let G=Number.parseInt(Z);if(G<this.sequence.prevariadic.length){let _=this.sequence.prevariadic[G].node;Y=Y?.and(_)??_,U||=G<this.sequence.prefixLength}else if(this.sequence.variadic){let _=this.$.node("union",this.sequence.variadicOrPostfix);Y=Y?.and(_)??_}}if(!Y){if(this.sequence?.variadic&&A(Z,"root")&&Z.extends(F.intrinsic.number))return L(q8(Z.expression,this.sequence.expression));return L(CX(this.expression,[Z]))}let W=Y.get(...X);return U?W:W.or(F.intrinsic.undefined)}pick(...Q){return this.assertHasKeys(Q),this.$.node("structure",this.filterKeys("pick",Q))}omit(...Q){return this.assertHasKeys(Q),this.$.node("structure",this.filterKeys("omit",Q))}optionalize(){let{required:Q,...X}=this.inner;return this.$.node("structure",{...X,optional:this.props.map((Y)=>Y.hasKind("required")?this.$.node("optional",Y.inner):Y)})}require(){let{optional:Q,...X}=this.inner;return this.$.node("structure",{...X,required:this.props.map((Y)=>Y.hasKind("optional")?{key:Y.key,value:Y.value}:Y)})}merge(Q){let X=this.filterKeys("omit",[Q.keyof()]);if(Q.required)X.required=D(X.required,Q.required);if(Q.optional)X.optional=D(X.optional,Q.optional);if(Q.index)X.index=D(X.index,Q.index);if(Q.sequence)X.sequence=Q.sequence;if(Q.undeclared)X.undeclared=Q.undeclared;else delete X.undeclared;return this.$.node("structure",X)}filterKeys(Q,X){let Y=l2(this.inner),U=(Z)=>{let W=X.some((G)=>N2(Z,G));return Q==="pick"?W:!W};if(Y.required)Y.required=Y.required.filter((Z)=>U(Z.key));if(Y.optional)Y.optional=Y.optional.filter((Z)=>U(Z.key));if(Y.index)Y.index=Y.index.filter((Z)=>U(Z.signature));return Y}traverseAllows=(Q,X)=>this._traverse("Allows",Q,X);traverseApply=(Q,X)=>this._traverse("Apply",Q,X);_traverse=(Q,X,Y)=>{let U=Y?.currentErrorCount??0;for(let Z=0;Z<this.props.length;Z++)if(Q==="Allows"){if(!this.props[Z].traverseAllows(X,Y))return!1}else if(this.props[Z].traverseApply(X,Y),Y.failFast&&Y.currentErrorCount>U)return!1;if(this.sequence){if(Q==="Allows"){if(!this.sequence.traverseAllows(X,Y))return!1}else if(this.sequence.traverseApply(X,Y),Y.failFast&&Y.currentErrorCount>U)return!1}if(this.index||this.undeclared==="reject"){let Z=Object.keys(X);Z.push(...Object.getOwnPropertySymbols(X));for(let W=0;W<Z.length;W++){let G=Z[W];if(this.index){for(let _ of this.index)if(_.signature.traverseAllows(G,Y)){if(Q==="Allows"){if(!c(G,()=>_.value.traverseAllows(X[G],Y),Y))return!1}else if(c(G,()=>_.value.traverseApply(X[G],Y),Y),Y.failFast&&Y.currentErrorCount>U)return!1}}if(this.undeclared==="reject"&&!this.declaresKey(G)){if(Q==="Allows")return!1;if(Y.errorFromNodeContext({code:"predicate",expected:"removed",actual:"",relativePath:[G],meta:this.meta}),Y.failFast)return!1}}}if(this.structuralMorph&&Y&&!Y.hasError())Y.queueMorphs([this.structuralMorph]);return!0};get defaultable(){return this.cacheGetter("defaultable",this.optional?.filter((Q)=>Q.hasDefault())??[])}declaresKey=(Q)=>(Q in this.propsByKey)||this.index?.some((X)=>X.signature.allows(Q))||this.sequence!==void 0&&F.intrinsic.nonNegativeIntegerString.allows(Q);_compileDeclaresKey(Q){let X=[];if(this.props.length)X.push(`k in ${this.propsByKeyReference}`);if(this.index)for(let Y of this.index)X.push(Q.invoke(Y.signature,{kind:"Allows",arg:"k"}));if(this.sequence)X.push("$ark.intrinsic.nonNegativeIntegerString.allows(k)");return X.join(" || ")||"false"}get structuralMorph(){return this.cacheGetter("structuralMorph",L8(this))}structuralMorphRef=this.structuralMorph&&S(this.structuralMorph);compile(Q){if(Q.traversalKind==="Apply")Q.initializeErrorCount();for(let X of this.props)if(Q.check(X),Q.traversalKind==="Apply")Q.returnIfFailFast();if(this.sequence){if(Q.check(this.sequence),Q.traversalKind==="Apply")Q.returnIfFailFast()}if(this.index||this.undeclared==="reject")Q.const("keys","Object.keys(data)"),Q.line("keys.push(...Object.getOwnPropertySymbols(data))"),Q.for("i < keys.length",()=>this.compileExhaustiveEntry(Q));if(Q.traversalKind==="Allows")return Q.return(!0);if(this.structuralMorphRef)Q.if("ctx && !ctx.hasError()",()=>{return Q.line("ctx.queueMorphs(["),H8(Q,this),Q.line("])")})}compileExhaustiveEntry(Q){if(Q.const("k","keys[i]"),this.index)for(let X of this.index)Q.if(`${Q.invoke(X.signature,{arg:"k",kind:"Allows"})}`,()=>Q.traverseKey("k","data[k]",X.value));if(this.undeclared==="reject")Q.if(`!(${this._compileDeclaresKey(Q)})`,()=>{if(Q.traversalKind==="Allows")return Q.return(!1);return Q.line(`ctx.errorFromNodeContext({ code: "predicate", expected: "removed", actual: "", relativePath: [k], meta: ${this.compiledMeta} })`).if("ctx.failFast",()=>Q.return())});return Q}reduceJsonSchema(Q,X){switch(Q.type){case"object":return this.reduceObjectJsonSchema(Q,X);case"array":let Y=this.sequence?.reduceJsonSchema(Q,X)??Q;if(this.props.length||this.index)return X.fallback.arrayObject({code:"arrayObject",base:Y,object:this.reduceObjectJsonSchema({type:"object"},X)});return Y;default:return E.throwInternalOperandError("structure",Q)}}reduceObjectJsonSchema(Q,X){if(this.props.length){Q.properties={};for(let Y of this.props){let U=Y.value.toJsonSchemaRecurse(X);if(typeof Y.key==="symbol"){X.fallback.symbolKey({code:"symbolKey",base:Q,key:Y.key,value:U,optional:Y.optional});continue}if(Y.hasDefault()){let Z=typeof Y.default==="function"?Y.default():Y.default;U.default=F.intrinsic.jsonData.allows(Z)?Z:X.fallback.defaultValue({code:"defaultValue",base:U,value:Z})}Q.properties[Y.key]=U}if(this.requiredKeys.length&&Q.properties)Q.required=this.requiredKeys.filter((Y)=>typeof Y==="string"&&(Y in Q.properties))}if(this.index)for(let Y of this.index){let U=Y.value.toJsonSchemaRecurse(X);if(Y.signature.equals(F.intrinsic.string)){Q.additionalProperties=U;continue}for(let Z of Y.signature.branches){if(!Z.extends(F.intrinsic.string)){Q=X.fallback.symbolKey({code:"symbolKey",base:Q,key:null,value:U,optional:!1});continue}let W={type:"string"};if(Z.hasKind("morph"))W=X.fallback.morph({code:"morph",base:Z.rawIn.toJsonSchemaRecurse(X),out:Z.rawOut.toJsonSchemaRecurse(X)});if(!Z.hasKind("intersection"))return C(`Unexpected index branch kind ${Z.kind}.`);let{pattern:G}=Z.inner;if(G){let _=Object.assign(W,{pattern:G[0].rule});for(let H=1;H<G.length;H++)W=X.fallback.patternIntersection({code:"patternIntersection",base:_,pattern:G[H].rule});Q.patternProperties??={},Q.patternProperties[_.pattern]=U}}}if(this.undeclared&&!Q.additionalProperties)Q.additionalProperties=!1;return Q}}var FQ={},J8=(Q)=>{let X="";for(let Y=0;Y<Q.defaultable.length;Y++)X+=Q.defaultable[Y].defaultValueMorphRef;if(Q.sequence?.defaultValueMorphsReference)X+=Q.sequence?.defaultValueMorphsReference;if(Q.undeclared==="delete"){if(X+="delete !(",Q.required)for(let Y of Q.required)X+=Y.compiledKey+" | ";if(Q.optional)for(let Y of Q.optional)X+=Y.compiledKey+" | ";if(Q.index)for(let Y of Q.index)X+=Y.signature.id+" | ";if(Q.sequence)if(Q.sequence.maxLength===null)X+=z.nonNegativeIntegerString.id;else for(let Y=0;Y<Q.sequence.tuple.length;Y++)X+=Y+" | ";X+=")"}return X},L8=(Q)=>{let X=J8(Q);if(!X)return;if(FQ[X])return FQ[X];let Y=(U,Z)=>{for(let W=0;W<Q.defaultable.length;W++)if(!(Q.defaultable[W].key in U))Q.defaultable[W].defaultValueMorph(U,Z);if(Q.sequence?.defaultables)for(let W=U.length-Q.sequence.prefixLength;W<Q.sequence.defaultables.length;W++)Q.sequence.defaultValueMorphs[W](U,Z);if(Q.undeclared==="delete"){for(let W in U)if(!Q.declaresKey(W))delete U[W]}return U};return FQ[X]=Y},H8=(Q,X)=>{let U=`(data${X.defaultable.some((Z)=>Z.defaultValueMorph.length===2)||X.sequence?.defaultValueMorphs.some((Z)=>Z.length===2)?", ctx":""})`;return Q.block(`${U} => `,(Z)=>{for(let W=0;W<X.defaultable.length;W++){let{serializedKey:G,defaultValueMorphRef:_}=X.defaultable[W];Z.if(`!(${G} in data)`,(H)=>H.line(`${_}${U}`))}if(X.sequence?.defaultables)Z.for(`i < ${X.sequence.defaultables.length}`,(W)=>W.set("data[i]",5),`data.length - ${X.sequence.prefixLength}`);if(X.undeclared==="delete")Z.forIn("data",(W)=>W.if(`!(${X._compileDeclaresKey(W)})`,(G)=>G.line("delete data[k]")));return Z.return("data")})},qQ={implementation:_8,Node:PX},F8=(Q)=>{if(A(Q,"root")&&Q.hasKind("unit"))Q=Q.unit;if(typeof Q==="number")Q=`${Q}`;return Q},q8=(Q,X)=>`${Q} is not allowed as an array index on ${X}. Use the 'nonNegativeIntegerString' keyword instead.`,Q6=(Q,X,Y)=>{let[U,Z]=mQ(Q.branches,(G)=>G.hasKind("unit"));if(!U.length)return{index:Y.node("index",{signature:Q,value:X})};let W={};for(let G of U){let _=Y.node("required",{key:G.unit,value:X});W[_.kind]=D(W[_.kind],_)}if(Z.length)W.index=Y.node("index",{signature:Z,value:X});return W},$8=(Q)=>A(Q,"root")?Q.expression:B(Q),CX=(Q,X)=>`Key${X.length===1?"":"s"} ${X.map($8).join(", ")} ${X.length===1?"does":"do"} not exist on ${Q}`,wX=(Q)=>`Duplicate key ${Y1(Q)}`;var o1={...o4,alias:E2.implementation,domain:e2.implementation,unit:GQ.implementation,proto:I2.implementation,union:WQ.implementation,morph:UQ.implementation,intersection:YQ.implementation,divisor:m6.implementation,pattern:r6.implementation,predicate:u6.implementation,required:JQ.implementation,optional:K2.implementation,index:_Q.implementation,sequence:LQ.implementation,structure:qQ.implementation};F.defaultConfig=tQ(Object.assign(V(o1,(Q,X)=>[Q,X.defaults]),{jitless:U4(),clone:Q4,onUndeclaredKey:"ignore",exactOptionalPropertyTypes:!0,numberAllowsNaN:!1,dateAllowsInvalid:!1,onFail:null,keywords:{},toJsonSchema:E.defaultConfig}));F.resolvedConfig=B2(F.defaultConfig,F.config);var a4={...i4,alias:E2.Node,domain:e2.Node,unit:GQ.Node,proto:I2.Node,union:WQ.Node,morph:UQ.Node,intersection:YQ.Node,divisor:m6.Node,pattern:r6.Node,predicate:u6.Node,required:JQ.Node,optional:K2.Node,index:_Q.Node,sequence:LQ.Node,structure:qQ.Node};class n1 extends R6{get[x](){return"module"}}var $Q=(Q,X)=>new n1(V(Q,(Y,U)=>[Y,A(U,"module")?$Q(U,X):X.bindReference(U)]));var A8=(Q)=>K(Q)?Q:("branches"in Q)&&K(Q.branches)?Q.branches:void 0,z8=(Q,X)=>L(`Node of kind ${X} is not valid as a ${Q} definition`),NX=(Q)=>`#${Q} duplicates public alias ${Q}`,AQ={};F.ambient??={};var EX,SX="function $",O8=(Q)=>jX(Q,bX(Q)),jX=(Q,X)=>{let Y=X.write(SX,4),U=X.compile()();for(let Z of Q){if(Z.precompilation)continue;if(Z.traverseAllows=U[`${Z.id}Allows`].bind(U),Z.isRoot()&&!Z.allowsRequiresContext)Z.allows=Z.traverseAllows;if(Z.traverseApply=U[`${Z.id}Apply`].bind(U),U[`${Z.id}Optimistic`])Z.traverseOptimistic=U[`${Z.id}Optimistic`].bind(U);Z.precompilation=Y}},bX=(Q)=>new m2().return(Q.reduce((X,Y)=>{let U=new V2({kind:"Allows"}).indent();Y.compile(U);let Z=U.write(`${Y.id}Allows`),W=new V2({kind:"Apply"}).indent();Y.compile(W);let G=W.write(`${Y.id}Apply`),_=`${X}${Z},
|
|
42
42
|
${G},
|
|
43
43
|
`;if(!Y.hasKind("union"))return _;let H=new V2({kind:"Allows",optimistic:!0}).indent();Y.compile(H);let J=H.write(`${Y.id}Optimistic`);return`${_}${J},
|
|
44
44
|
`},`{
|
|
45
|
-
`)+"}");class Q6{config;resolvedConfig;name;get[x](){return"scope"}referencesById={};references=[];resolutions={};exportedNames=[];aliases={};resolved=!1;nodesByHash={};intrinsic;constructor(Q,X){if(this.config=T2(F.config,X),this.resolvedConfig=T2(F.resolvedConfig,X),this.name=this.resolvedConfig.name??`anonymousScope${Object.keys($Q).length}`,this.name in $Q)L(`A Scope already named ${this.name} already exists`);$Q[this.name]=this;let Y=Object.entries(Q).map((U)=>this.preparseOwnAliasEntry(...U));for(let[U,Z]of Y){let W=U;if(U[0]==="#"){if(W=U.slice(1),W in this.aliases)L(KX(W));this.aliases[W]=Z}else{if(W in this.aliases)L(KX(U));this.aliases[W]=Z,this.exportedNames.push(W)}if(!A(Z,"module")&&!A(Z,"generic")&&!T1(Z)){let G=this.preparseOwnDefinitionFormat(Z,{alias:W});this.resolutions[W]=A(G,"root")?this.bindReference(G):this.createParseContext(G).id}}NX??=this.node("union",{branches:["string","number","object","bigint","symbol",{unit:!0},{unit:!1},{unit:void 0},{unit:null}]},{prereduced:!0}),this.nodesByHash[NX.hash]=this.node("intersection",{},{prereduced:!0}),this.intrinsic=F.intrinsic?V(F.intrinsic,(U,Z)=>U.startsWith("json")?[]:[U,this.bindReference(Z)]):{}}cacheGetter(Q,X){return Object.defineProperty(this,Q,{value:X}),X}get internal(){return this}_json;get json(){if(!this._json)this.export();return this._json}defineSchema(Q){return Q}generic=(...Q)=>{let X=this;return(Y,U)=>new C1(Q,U?new o2(Y):Y,X,X,U??null)};units=(Q,X)=>{let Y=[];for(let Z of Q)if(!Y.includes(Z))Y.push(Z);let U=Y.map((Z)=>this.node("unit",{unit:Z},X));return this.node("union",U,{...X,prereduced:!0})};lazyResolutions=[];lazilyResolve(Q,X){let Y=this.node("alias",{reference:X??"synthetic",resolve:Q},{prereduced:!0});if(!this.resolved)this.lazyResolutions.push(Y);return Y}schema=(Q,X)=>this.finalize(this.parseSchema(Q,X));parseSchema=(Q,X)=>this.node(D2(Q),Q,X);preparseNode(Q,X,Y){let U=typeof Q==="string"?Q:D2(X,Q);if(N(X)&&X.kind===U)return X;if(U==="alias"&&!Y?.prereduced){let{reference:G}=E2.implementation.normalize(X,this);if(G.startsWith("$")){let _=this.resolveRoot(G.slice(1));X=_,U=_.kind}}else if(U==="union"&&p(X,"object")){let G=q8(X);if(G?.length===1)X=G[0],U=D2(X)}if(N(X)&&X.kind===U)return X;let W=o1[U].normalize?.(X,this)??X;if(N(W))return W.kind===U?W:$8(U,W.kind);return{...Y,$:this,kind:U,def:W,prefix:Y.alias??U}}bindReference(Q){let X;if(N(Q))X=Q.$===this?Q:new Q.constructor(Q.attachments,this);else X=Q.$===this?Q:new C1(Q.params,Q.bodyDef,Q.$,this,Q.hkt);if(!this.resolved)Object.assign(this.referencesById,X.referencesById);return X}resolveRoot(Q){return this.maybeResolveRoot(Q)??L(OQ(Q))}maybeResolveRoot(Q){let X=this.maybeResolve(Q);if(A(X,"generic"))return;return X}maybeResolveSubalias(Q){return AQ(this.aliases,Q)??AQ(this.ambient,Q)}get ambient(){return F.ambient}maybeResolve(Q){let X=this.resolutions[Q];if(X){if(typeof X!=="string")return this.bindReference(X);let U=h[X];if(A(U,"root"))return this.resolutions[Q]=U;if(A(U,"context")){if(U.phase==="resolving")return this.node("alias",{reference:`$${Q}`},{prereduced:!0});if(U.phase==="resolved")return C(`Unexpected resolved context for was uncached by its scope: ${T(U)}`);U.phase="resolving";let Z=this.bindReference(this.parseOwnDefinitionFormat(U.def,U));return U.phase="resolved",h[Z.id]=Z,h[U.id]=Z,this.resolutions[Q]=Z}return C(`Unexpected nodesById entry for ${X}: ${T(U)}`)}let Y=this.aliases[Q]??this.ambient?.[Q];if(!Y)return this.maybeResolveSubalias(Q);if(Y=this.normalizeRootScopeValue(Y),A(Y,"generic"))return this.resolutions[Q]=this.bindReference(Y);if(A(Y,"module")){if(!Y.root)L(yX(Q));return this.resolutions[Q]=this.bindReference(Y.root)}return this.resolutions[Q]=this.parse(Y,{alias:Q})}createParseContext(Q){let X=Q.id??r6(Q.prefix);return h[X]=Object.assign(Q,{[x]:"context",$:this,id:X,phase:"unresolved"})}traversal(Q){return new U1(Q,this.resolvedConfig)}import(...Q){return new n1(V(this.export(...Q),(X,Y)=>[`#${X}`,Y]))}precompilation;_exportedResolutions;_exports;export(...Q){if(!this._exports){this._exports={};for(let Y of this.exportedNames){let U=this.aliases[Y];this._exports[Y]=A(U,"module")?qQ(U,this):PX(this.maybeResolve(Y))}for(let Y of this.lazyResolutions)Y.resolution;if(this._exportedResolutions=bX(this,this._exports),this._json=jX(this._exportedResolutions),Object.assign(this.resolutions,this._exportedResolutions),this.references=Object.values(this.referencesById),!this.resolvedConfig.jitless){let Y=SX(this.references);this.precompilation=Y.write(EX,4),IX(this.references,Y)}this.resolved=!0}let X=Q.length?Q:this.exportedNames;return new n1(V(X,(Y,U)=>[U,this._exports[U]]))}resolve(Q){return this.export()[Q]}node=(Q,X,Y={})=>{let U=this.preparseNode(Q,X,Y);if(N(U))return this.bindReference(U);let Z=this.createParseContext(U),W=t6(Z),G=this.bindReference(W);return h[Z.id]=G};parse=(Q,X={})=>this.finalize(this.parseDefinition(Q,X));parseDefinition(Q,X={}){if(A(Q,"root"))return this.bindReference(Q);let Y=this.preparseOwnDefinitionFormat(Q,X);if(A(Y,"root"))return this.bindReference(Y);let U=this.createParseContext(Y);h[U.id]=U;let Z=this.bindReference(this.parseOwnDefinitionFormat(Q,U));if(Z.isCyclic)Z=n4(Z,U.id);return h[U.id]=Z,Z}finalize(Q){if(PX(Q),!Q.precompilation&&!this.resolvedConfig.jitless)A8(Q.references);return Q}}class zQ extends Q6{parseOwnDefinitionFormat(Q,X){return t6(X)}preparseOwnDefinitionFormat(Q,X){return this.preparseNode(D2(Q),Q,X)}preparseOwnAliasEntry(Q,X){return[Q,X]}normalizeRootScopeValue(Q){return Q}}var PX=(Q)=>{let X=Q.references.filter((Y)=>Y.hasKind("alias"));for(let Y of X){Object.assign(Y.referencesById,Y.resolution.referencesById);for(let U of Q.references)if(Y.id in U.referencesById)Object.assign(U.referencesById,Y.referencesById)}return Q},jX=(Q)=>V(Q,(X,Y)=>[X,A(Y,"root")||A(Y,"generic")?Y.json:A(Y,"module")?jX(Y):C(`Unexpected resolution ${T(Y)}`)]),AQ=(Q,X)=>{let Y=X.indexOf(".");if(Y===-1)return;let U=X.slice(0,Y),Z=Q[U];if(Z===void 0)return;if(!A(Z,"module"))return L(z8(U));let W=X.slice(Y+1),G=Z[W];if(G===void 0)return AQ(Z,W);if(A(G,"root")||A(G,"generic"))return G;if(A(G,"module"))return G.root??L(yX(X));C(`Unexpected resolution for alias '${X}': ${T(G)}`)},X6=(Q,X)=>new zQ(Q,X),j2=new zQ({});var bX=(Q,X)=>{let Y={};for(let U in X){let Z=X[U];if(A(Z,"module")){let W=bX(Q,Z),G=V(W,(_,H)=>[`${U}.${_}`,H]);Object.assign(Y,G)}else if(A(Z,"root")||A(Z,"generic"))Y[U]=Z;else C(`Unexpected scope resolution ${T(Z)}`)}return Y},OQ=(Q)=>`'${Q}' is unresolvable`,z8=(Q)=>`'${Q}' must reference a module to be accessed using dot syntax`,yX=(Q)=>`Reference to submodule '${Q}' must specify an alias`;j2.export();var{schema:w,node:r1,defineSchema:m7,generic:e}=j2;var VQ="^(?:0|[1-9]\\d*)$",O8=new RegExp(VQ),c7=S(O8);var fX=X6({bigint:"bigint",boolean:[{unit:!1},{unit:!0}],false:{unit:!1},never:[],null:{unit:null},number:"number",object:"object",string:"string",symbol:"symbol",true:{unit:!0},unknown:{},undefined:{unit:void 0},Array,Date},{prereducedAliases:!0}).export();F.intrinsic={...fX};var vX=X6({integer:{domain:"number",divisor:1},lengthBoundable:["string",Array],key:["string","symbol"],nonNegativeIntegerString:{domain:"string",pattern:VQ}},{prereducedAliases:!0}).export();Object.assign(F.intrinsic,vX);var V8=X6({jsonPrimitive:["string","number",{unit:!0},{unit:!1},{unit:null}],jsonObject:{domain:"object",index:{signature:"string",value:"$jsonData"}},jsonData:["$jsonPrimitive","$jsonObject"]},{prereducedAliases:!0}).export(),z={...fX,...vX,...V8,emptyStructure:r1("structure",{},{prereduced:!0})};F.intrinsic={...z};var Y6=(Q,X)=>new RegExp(Q,X);Object.assign(Y6,{as:Y6});var gX=(Q)=>typeof Q==="string"&&Q[0]==="d"&&(Q[1]==="'"||Q[1]==='"')&&Q[Q.length-1]===Q[1],kX=(Q)=>Q.toString()!=="Invalid Date",xX=(Q)=>Q.slice(2,-1),TQ=(Q)=>`'${Q}' could not be parsed by the Date constructor`,hX=(Q,X)=>T8(Q,X),T8=(Q,X)=>{let Y=new Date(Q);if(kX(Y))return Y;let U=F4(Q);if(U!==void 0){let Z=new Date(U);if(kX(Z))return Z}return X?L(X===!0?TQ(Q):X):void 0};var B8=w({proto:"Array",sequence:"string",required:{key:"groups",value:["object",{unit:void 0}]}}),U6=(Q,X)=>{let Y=Q.scanner.shiftUntilEscapable(R8[mX[X]]);if(Q.scanner.lookahead==="")return Q.error(C8(Y,X));if(Q.scanner.shift(),X in uX){let U;try{U=new RegExp(Y)}catch(Z){L(String(Z))}if(Q.root=Q.ctx.$.node("intersection",{domain:"string",pattern:Y},{prereduced:!0}),X==="x/")Q.root=Q.ctx.$.node("morph",{in:Q.root,morphs:(Z)=>U.exec(Z),declaredOut:B8})}else if(f(X,BQ))Q.root=Q.ctx.$.node("unit",{unit:Y});else{let U=hX(Y,TQ(Y));Q.root=Q.ctx.$.node("unit",{meta:Y,unit:U})}},BQ={"'":1,'"':1},pX={"/":1,"'":1,'"':1},M8={"d'":"'",'d"':'"',"'":"'",'"':'"'},uX={"/":"/","x/":"/"},mX={...M8,...uX},R8={"'":(Q)=>Q.lookahead==="'",'"':(Q)=>Q.lookahead==='"',"/":(Q)=>Q.lookahead==="/"},D8={'"':"double-quote","'":"single-quote","/":"forward slash"},C8=(Q,X)=>`${X}${Q} requires a closing ${D8[mX[X]]}`;var lX=(Q)=>`Private type references should not include '#'. Use '${Q}' instead.`,Z6="Optional definitions like 'string?' are only valid as properties in an object or tuple",W6="Defaultable definitions like 'number = 0' are only valid as properties in an object or tuple";var L1={"<":1,">":1,"=":1,"|":1,"&":1,")":1,"[":1,"%":1,",":1,":":1,"?":1,"#":1,...B1};var dX=(Q,X)=>Q===">"?X[0]==="="?X[1]==="=":X.trimStart()===""||f(X.trimStart()[0],L1):Q==="="?X[0]!=="=":Q===","||Q==="?";var cX=(Q,X,Y)=>oX(Q,X,Y,[]),oX=(Q,X,Y,U)=>{let Z=Y.parseUntilFinalizer();if(U.push(Z.root),Z.finalizer===">"){if(U.length!==X.params.length)return Y.error(MQ(Q,X.names,U.map((W)=>W.expression)));return U}if(Z.finalizer===",")return oX(Q,X,Y,U);return Z.error(p2(">"))},MQ=(Q,X,Y)=>`${Q}<${X.join(", ")}> requires exactly ${X.length} args (got ${Y.length}${Y.length===0?"":`: ${Y.join(", ")}`})`;var G6=(Q)=>{let X=Q.scanner.shiftUntilLookahead(L1);if(X==="keyof")Q.addPrefix("keyof");else Q.root=K8(Q,X)},w8=(Q,X,Y)=>{if(Y.scanner.shiftUntilNonWhitespace(),Y.scanner.shift()!=="<")return Y.error(MQ(Q,X.names,[]));let Z=cX(Q,X,Y);return X(...Z)},K8=(Q,X)=>N8(Q,X)??P8(Q,X)??Q.error(X===""?Q.scanner.lookahead==="#"?lX(Q.shiftedBy(1).scanner.shiftUntilLookahead(L1)):RQ(Q):OQ(X)),N8=(Q,X)=>{if(Q.ctx.args?.[X]){let U=Q.ctx.args[X];if(typeof U!=="string")return U;return Q.ctx.$.node("alias",{reference:U},{prereduced:!0})}let Y=Q.ctx.$.maybeResolve(X);if(A(Y,"root"))return Y;if(Y===void 0)return;if(A(Y,"generic"))return w8(X,Y,Q);return L(`Unexpected resolution ${T(Y)}`)},P8=(Q,X)=>{let Y=q4(X);if(Y!==void 0)return Q.ctx.$.node("unit",{unit:Y});let U=A4(X);if(U!==void 0)return Q.ctx.$.node("unit",{unit:U})},RQ=(Q)=>{let X=Q.previousOperator();return X?DQ(X,Q.scanner.unscanned):E8(Q.scanner.unscanned)},DQ=(Q,X="")=>`Token '${Q}' requires a right operand${X?` before '${X}'`:""}`,E8=(Q)=>`Expected an expression${Q?` before '${Q}'`:""}`;var CQ=(Q)=>Q.scanner.lookahead===""?Q.error(RQ(Q)):Q.scanner.lookahead==="("?Q.shiftedBy(1).reduceGroupOpen():Q.scanner.lookaheadIsIn(pX)?U6(Q,Q.scanner.shift()):Q.scanner.lookaheadIsIn(B1)?CQ(Q.shiftedBy(1)):Q.scanner.lookahead==="d"?Q.scanner.nextLookahead in BQ?U6(Q,`${Q.scanner.shift()}${Q.scanner.shift()}`):G6(Q):Q.scanner.lookahead==="x"?Q.scanner.nextLookahead==="/"?Q.shiftedBy(2)&&U6(Q,"x/"):G6(Q):G6(Q);var iX={">":!0,">=":!0},sX={"<":!0,"<=":!0};var t1={"<":">",">":"<","<=":">=",">=":"<=","==":"=="},nX=(Q,X)=>`Left bounds are only valid when paired with right bounds (try ...${X}${Q})`,_6=(Q)=>`Left-bounded expressions must specify their limits using < or <= (was ${Q})`,rX=(Q,X,Y,U)=>`An expression may have at most one left bound (parsed ${Q}${t1[X]}, ${Y}${t1[U]})`;var aX=(Q,X)=>{let Y=I8(Q,X);if(Q.root.hasKind("unit")){if(typeof Q.root.unit==="number"){Q.reduceLeftBound(Q.root.unit,Y),Q.unsetRoot();return}if(Q.root.unit instanceof Date){let U=`d'${Q.root.description??Q.root.unit.toISOString()}'`;Q.unsetRoot(),Q.reduceLeftBound(U,Y);return}}return j8(Q,Y)},eX={"<":1,">":1,"=":1},I8=(Q,X)=>Q.scanner.lookaheadIs("=")?`${X}${Q.scanner.shift()}`:X;var tX=(Q,X,Y,U)=>{if(Y.extends(F.intrinsic.number)){if(typeof X!=="number")return L(wQ(Q,X,U));return Q==="=="?["min","max"]:Q[0]===">"?["min"]:["max"]}if(Y.extends(F.intrinsic.lengthBoundable)){if(typeof X!=="number")return L(wQ(Q,X,U));return Q==="=="?["exactLength"]:Q[0]===">"?["minLength"]:["maxLength"]}if(Y.extends(F.intrinsic.Date))return Q==="=="?["after","before"]:Q[0]===">"?["after"]:["before"];return L(k4(Y.expression))},S8=(Q)=>({rule:gX(Q.limit)?xX(Q.limit):Q.limit,exclusive:Q.comparator.length===1}),j8=(Q,X)=>{let Y=Q.unsetRoot(),U=Q.scanner.location;Q.parseOperand();let Z=Q.unsetRoot(),W=Q.scanner.sliceChars(U,Q.scanner.location);if(Q.root=Y,!Z.hasKind("unit")||typeof Z.unit!=="number"&&!(Z.unit instanceof Date))return Q.error(wQ(X,W,"right"));let G=Z.unit,_=X.length===1,H=tX(X,typeof G==="number"?G:W,Y,"right");for(let $ of H)Q.constrainRoot($,X==="=="?{rule:G}:{rule:G,exclusive:_});if(!Q.branches.leftBound)return;if(!f(X,sX))return Q.error(_6(X));let J=tX(Q.branches.leftBound.comparator,Q.branches.leftBound.limit,Y,"left");Q.constrainRoot(J[0],S8(Q.branches.leftBound)),Q.branches.leftBound=null},wQ=(Q,X,Y)=>`Comparator ${Y==="left"?t1[Q]:Q} must be ${Y==="left"?"preceded":"followed"} by a corresponding literal (was ${X})`;var QY=(Q)=>{Q.scanner.shiftUntilNonWhitespace();let X=Q.scanner.shiftUntilLookahead(L1);Q.root=Q.root.brand(X)};var YY=(Q)=>{Q.scanner.shiftUntilNonWhitespace();let X=Q.scanner.shiftUntilLookahead(L1),Y=$4(X,{errorOnFail:XY(X)});if(Y===0)Q.error(XY(0));Q.root=Q.root.constrain("divisor",Y)},XY=(Q)=>`% operator must be followed by a non-zero integer literal (was ${Q})`;var KQ=(Q)=>{let X=Q.scanner.shift();return X===""?Q.finalize(""):X==="["?Q.scanner.shift()==="]"?Q.setRoot(Q.root.array()):Q.error(b8):X==="|"?Q.scanner.lookahead===">"?Q.shiftedBy(1).pushRootToBranch("|>"):Q.pushRootToBranch(X):X==="&"?Q.pushRootToBranch(X):X===")"?Q.finalizeGroup():dX(X,Q.scanner.unscanned)?Q.finalize(X):f(X,eX)?aX(Q,X):X==="%"?YY(Q):X==="#"?QY(Q):(X in B1)?KQ(Q):Q.error(J6(X))},J6=(Q,X="")=>`'${Q}' is not allowed here${X&&` (should be ${X})`}`,b8="Missing expected ']'";var UY=(Q)=>{let X=Q.unsetRoot();Q.parseOperand();let Y=Q.unsetRoot();if(!Y.hasKind("unit"))return Q.error(y8(Y.expression));let U=Y.unit instanceof Date?()=>new Date(Y.unit):Y.unit;return[X,"=",U]},y8=(Q)=>`Default value '${Q}' must be a literal value`;var NQ=(Q,X)=>{let Y=X.$.maybeResolveRoot(Q);if(Y)return Y;if(Q.endsWith("[]")){let W=X.$.maybeResolveRoot(Q.slice(0,-2));if(W)return W.array()}let U=new a1(new O2(Q),X),Z=f8(U);if(U.finalizer===">")L(J6(">"));return Z},f8=(Q)=>{Q.parseOperand();let X=b2(Q).root;if(!X)return C(`Root was unexpectedly unset after parsing string '${Q.scanner.scanned}'`);if(Q.finalizer==="=")X=UY(Q);else if(Q.finalizer==="?")X=[X,"?"];if(Q.scanner.shiftUntilNonWhitespace(),Q.scanner.lookahead)L(J6(Q.scanner.lookahead));return X},b2=(Q)=>{while(Q.finalizer===void 0)v8(Q);return Q},v8=(Q)=>Q.hasRoot()?Q.parseOperator():Q.parseOperand();class a1{root;branches={prefixes:[],leftBound:null,intersection:null,union:null,pipe:null};finalizer;groups=[];scanner;ctx;constructor(Q,X){this.scanner=Q,this.ctx=X}error(Q){return L(Q)}hasRoot(){return this.root!==void 0}setRoot(Q){this.root=Q}unsetRoot(){let Q=this.root;return this.root=void 0,Q}constrainRoot(...Q){this.root=this.root.constrain(Q[0],Q[1])}finalize(Q){if(this.groups.length)return this.error(p2(")"));this.finalizeBranches(),this.finalizer=Q}reduceLeftBound(Q,X){let Y=t1[X];if(!f(Y,iX))return this.error(_6(X));if(this.branches.leftBound)return this.error(rX(this.branches.leftBound.limit,this.branches.leftBound.comparator,Q,Y));this.branches.leftBound={comparator:Y,limit:Q}}finalizeBranches(){if(this.assertRangeUnset(),this.branches.pipe){this.pushRootToBranch("|>"),this.root=this.branches.pipe;return}if(this.branches.union){this.pushRootToBranch("|"),this.root=this.branches.union;return}if(this.branches.intersection){this.pushRootToBranch("&"),this.root=this.branches.intersection;return}this.applyPrefixes()}finalizeGroup(){this.finalizeBranches();let Q=this.groups.pop();if(!Q)return this.error(T4(")",this.scanner.unscanned));this.branches=Q}addPrefix(Q){this.branches.prefixes.push(Q)}applyPrefixes(){while(this.branches.prefixes.length){let Q=this.branches.prefixes.pop();this.root=Q==="keyof"?this.root.keyof():C(`Unexpected prefix '${Q}'`)}}pushRootToBranch(Q){this.assertRangeUnset(),this.applyPrefixes();let X=this.root;if(this.root=void 0,this.branches.intersection=this.branches.intersection?.rawAnd(X)??X,Q==="&")return;if(this.branches.union=this.branches.union?.rawOr(this.branches.intersection)??this.branches.intersection,this.branches.intersection=null,Q==="|")return;this.branches.pipe=this.branches.pipe?.rawPipeOnce(this.branches.union)??this.branches.union,this.branches.union=null}parseUntilFinalizer(){return b2(new a1(this.scanner,this.ctx))}parseOperator(){return KQ(this)}parseOperand(){return CQ(this)}assertRangeUnset(){if(this.branches.leftBound)return this.error(nX(this.branches.leftBound.limit,this.branches.leftBound.comparator))}reduceGroupOpen(){this.groups.push(this.branches),this.branches={prefixes:[],leftBound:null,union:null,intersection:null,pipe:null}}previousOperator(){return this.branches.leftBound?.comparator??this.branches.prefixes[this.branches.prefixes.length-1]??(this.branches.intersection?"&":this.branches.union?"|":this.branches.pipe?"|>":void 0)}shiftedBy(Q){return this.scanner.jumpForward(Q),this}}var k8="An empty string is not a valid generic parameter name",L6=(Q,X,Y)=>{Q.shiftUntilNonWhitespace();let U=Q.shiftUntilLookahead(L1);if(U===""){if(Q.lookahead===""&&X.length)return X;return L(k8)}return Q.shiftUntilNonWhitespace(),g8(Q,U,X,Y)},ZY="extends ",g8=(Q,X,Y,U)=>{if(Q.shiftUntilNonWhitespace(),Q.unscanned.startsWith(ZY))Q.jumpForward(ZY.length);else{if(Q.lookahead===",")Q.shift();return Y.push(X),L6(Q,Y,U)}let Z=b2(new a1(Q,U));return Y.push([X,Z.root]),L6(Q,Y,U)};class PQ extends l{constructor(Q){let X={$:Q,raw:Q.fn};super((...Y)=>{let U=Y.indexOf(":"),Z=U===-1?Y.length-1:U-1,W=Y.slice(0,Z+1),G=Q.parse(W).assertHasKind("intersection"),_=Q.intrinsic.unknown;if(U!==-1){if(U!==Y.length-2)return L(x8);_=Q.parse(Y[U+1])}return(H)=>new WY(H,G,_)},{attach:X})}}class WY extends l{raw;params;returns;expression;constructor(Q,X,Y){let U=`typed ${Q.name}`,Z={[U]:(...G)=>{let _=X.assert(G),H=Q(..._);return Y.assert(H)}}[U];super(Z);this.raw=Q,this.params=X,this.returns=Y;let W=X.expression;if(W[0]==="["&&W[W.length-1]==="]")W=W.slice(1,-1);else if(W.endsWith("[]"))W=`...${W}`;this.expression=`(${W}) => ${Y?.expression??"unknown"}`}}var x8=`":" must be followed by exactly one return type e.g:
|
|
46
|
-
fn("string", ":", "number")(s => s.length)`;class EQ extends l{$;constructor(Q){super((...X)=>new y2(Q)(...X),{bind:Q});this.$=Q}in(Q){return new y2(this.$,Q===void 0?void 0:this.$.parse(Q))}at(Q,X){return new y2(this.$).at(Q,X)}case(Q,X){return new y2(this.$).case(Q,X)}}class y2 extends l{$;in;key;branches=[];constructor(Q,X){super((Y)=>this.caseEntries(Object.entries(Y).map(([U,Z])=>U==="default"?[U,Z]:[this.$.parse(U),Z])));this.$=Q,this.in=X}at(Q,X){if(this.key)L(p8);if(this.branches.length)L(h8);return this.key=Q,X?this.match(X):this}case(Q,X){return this.caseEntry(this.$.parse(Q),X)}caseEntry(Q,X){let U=(this.key?this.$.parse({[this.key]:Q}):Q).pipe(X);return this.branches.push(U),this}match(Q){return this(Q)}strings(Q){return this.caseEntries(Object.entries(Q).map(([X,Y])=>X==="default"?[X,Y]:[this.$.node("unit",{unit:X}),Y]))}caseEntries(Q){for(let X=0;X<Q.length;X++){let[Y,U]=Q[X];if(Y==="default"){if(X!==Q.length-1)L("default may only be specified as the last key of a switch definition");return this.default(U)}if(typeof U!=="function")return L(`Value for case "${Y}" must be a function (was ${y(U)})`);this.caseEntry(Y,U)}return this}default(Q){if(typeof Q==="function")this.case(z.unknown,Q);let X={branches:this.branches,ordered:!0};if(Q==="never"||Q==="assert")X.meta={onFail:GY};let Y=this.$.node("union",X);if(!this.in)return this.$.finalize(Y);let U=this.in.pipe(Y);if(Q==="never"||Q==="assert")U=U.configureReferences({onFail:GY},"self");return this.$.finalize(U)}}var GY=(Q)=>Q.throw(),h8="A key matcher must be specified before the first case i.e. match.at('foo') or match.in<object>().at('bar')",p8="At most one key matcher may be specified per expression";var H6=(Q,X)=>{if(K(Q)){if(Q[1]==="=")return[X.$.parseOwnDefinitionFormat(Q[0],X),"=",Q[2]];if(Q[1]==="?")return[X.$.parseOwnDefinitionFormat(Q[0],X),"?"]}return F6(Q,X)},_Y="Only required keys may make their values optional, e.g. { [mySymbol]: ['number', '?'] }",JY="Only required keys may specify default values, e.g. { value: 'number = 0' }";var LY=(Q,X)=>{let Y,U={},Z=P1(Q);for(let[G,_]of Z){let H=l8(G);if(H.kind==="spread"){if(!_1(U))return L(m8);let b=X.$.parseOwnDefinitionFormat(_,X);if(b.equals(z.object))continue;if(!b.hasKind("intersection")||!b.basis?.equals(z.object))return L(d8(b.expression));Y=b.structure;continue}if(H.kind==="undeclared"){if(_!=="reject"&&_!=="delete"&&_!=="ignore")L(u8(_));U.undeclared=_;continue}let J=H6(_,X),$=H;if(H.kind==="required"){if(!K(J))IQ(U,"required",{key:H.normalized,value:J},X);else IQ(U,"optional",J[1]==="="?{key:H.normalized,value:J[0],default:J[2]}:{key:H.normalized,value:J[0]},X);continue}if(K(J)){if(J[1]==="?")L(_Y);if(J[1]==="=")L(JY)}if(H.kind==="optional"){IQ(U,"optional",{key:H.normalized,value:J},X);continue}let O=X.$.parseOwnDefinitionFormat($.normalized,X),D=e2(O,J,X.$);if(D.index)U.index=R(U.index,D.index);if(D.required)U.required=R(U.required,D.required)}let W=X.$.node("structure",U);return X.$.parseSchema({domain:"object",structure:Y?.merge(W)??W})},IQ=(Q,X,Y,U)=>{Q[X]=R(Q[X],U.$.node(X,Y))},u8=(Q)=>`Value of '+' key must be 'reject', 'delete', or 'ignore' (was ${T(Q)})`,m8="Spread operator may only be used as the first key in an object",l8=(Q)=>typeof Q==="symbol"?{kind:"required",normalized:Q}:Q[Q.length-1]==="?"?Q[Q.length-2]===I1?{kind:"required",normalized:`${Q.slice(0,-2)}?`}:{kind:"optional",normalized:Q.slice(0,-1)}:Q[0]==="["&&Q[Q.length-1]==="]"?{kind:"index",normalized:Q.slice(1,-1)}:Q[0]===I1&&Q[1]==="["&&Q[Q.length-1]==="]"?{kind:"required",normalized:Q.slice(1)}:Q==="..."?{kind:"spread"}:Q==="+"?{kind:"undeclared"}:{kind:"required",normalized:Q==="\\..."?"...":Q==="\\+"?"+":Q},d8=(Q)=>`Spread operand must resolve to an object literal type (was ${Q})`;var FY=(Q,X)=>Q3(Q)?zY[Q[0]](Q,X):a8(Q)?AY[Q[1]](Q,X):null,c8=(Q,X)=>X.$.parseOwnDefinitionFormat(Q[1],X).keyof(),SQ=(Q,X)=>{if(Q[2]===void 0)return L(DQ(Q[1],""));let Y=X.$.parseOwnDefinitionFormat(Q[0],X),U=X.$.parseOwnDefinitionFormat(Q[2],X);if(Q[1]==="|")return X.$.node("union",{branches:[Y,U]});let Z=Q[1]==="&"?o(Y,U,X.$):R2(Y,U,X.$);if(Z instanceof q)return Z.throw();return Z},o8=(Q,X)=>X.$.parseOwnDefinitionFormat(Q[0],X).array(),i8=(Q,X)=>{if(typeof Q[2]!=="function")return L(qY("=>",Q[2]));return X.$.parseOwnDefinitionFormat(Q[0],X).pipe(Q[2])},qY=(Q,X)=>`${Q===":"?"Narrow":"Morph"} expression requires a function following '${Q}' (was ${typeof X})`,s8=(Q,X)=>{if(typeof Q[2]!=="function")return L(qY(":",Q[2]));return X.$.parseOwnDefinitionFormat(Q[0],X).constrain("predicate",Q[2])},n8=(Q,X)=>X.$.parseOwnDefinitionFormat(Q[0],X).configure(Q[2],Q[3]),$Y=(Q)=>Q,r8=$Y({"[]":o8,"?":()=>L(Z6)}),t8=$Y({"|":SQ,"&":SQ,":":s8,"=>":i8,"|>":SQ,"@":n8,"=":()=>L(W6)}),AY={...r8,...t8},a8=(Q)=>AY[Q[1]]!==void 0,e8=(Q)=>Q,zY=e8({keyof:c8,instanceof:(Q,X)=>{if(typeof Q[1]!=="function")return L(HY(L2(Q[1])));let Y=Q.slice(1).map((U)=>typeof U==="function"?X.$.node("proto",{proto:U}):L(HY(L2(U))));return Y.length===1?Y[0]:X.$.node("union",{branches:Y})},"===":(Q,X)=>X.$.units(Q.slice(1))}),Q3=(Q)=>zY[Q[0]]!==void 0,HY=(Q)=>`Expected a constructor following 'instanceof' operator (was ${Q})`;var TY=(Q,X)=>{let Y=[{}],U=0;while(U<Q.length){let Z=!1;if(Q[U]==="..."&&U<Q.length-1)Z=!0,U++;let W=H6(Q[U],X),[G,_,H]=!K(W)?[W]:W;if(U++,Z){if(!G.extends(F.intrinsic.Array))return L(U3(G.expression));Y=Y.flatMap((J)=>G.distribute(($)=>Y3(m2(J),$)))}else Y=Y.map((J)=>{if(_==="?")return BY(J,G);if(_==="=")return X3(J,G,H);return jQ(J,G)})}return X.$.parseSchema(Y.map((Z)=>_1(Z)?{proto:Array,exactLength:0}:{proto:Array,sequence:Z}))},jQ=(Q,X)=>{if(Q.defaultables||Q.optionals)return L(Q.variadic?LQ:Z3);if(Q.variadic)Q.postfix=R(Q.postfix,X);else Q.prefix=R(Q.prefix,X);return Q},BY=(Q,X)=>{if(Q.variadic)return L(MY);return Q.optionals=R(Q.optionals,X),Q},X3=(Q,X,Y)=>{if(Q.variadic)return L(MY);if(Q.optionals)return L(W3);return Q.defaultables=R(Q.defaultables,[[X,Y]]),Q},OY=(Q,X)=>{if(Q.postfix)L(VY);if(Q.variadic){if(!Q.variadic.equals(X))L(VY)}else Q.variadic=X.internal;return Q},Y3=(Q,X)=>{let Y=X.select({method:"find",kind:"sequence"});if(!Y)return OY(Q,F.intrinsic.unknown);if(Y.prefix)for(let U of Y.prefix)jQ(Q,U);if(Y.optionals)for(let U of Y.optionals)BY(Q,U);if(Y.variadic)OY(Q,Y.variadic);if(Y.postfix)for(let U of Y.postfix)jQ(Q,U);return Q},U3=(Q)=>`Spread element must be an array (was ${Q})`,VY="A tuple may have at most one variadic element",Z3="A required element may not follow an optional element",MY="An optional element may not follow a variadic element";var W3="A defaultable element may not follow an optional element without a default";var G3={},F6=(Q,X)=>{if(typeof Q==="string"){if(X.args&&Object.keys(X.args).some((U)=>Q.includes(U)))return NQ(Q,X);let Y=G3[X.$.name]??={};return Y[Q]??=NQ(Q,X)}return p(Q,"object")?_3(Q,X):L(bQ(y(Q)))},_3=(Q,X)=>{let Y=J2(Q);switch(Y){case void 0:if(A(Q,"root"))return Q;if("~standard"in Q)return J3(Q,X);return LY(Q,X);case"Array":return L3(Q,X);case"RegExp":return X.$.node("intersection",{domain:"string",pattern:Q},{prereduced:!0});case"Function":{let U=T1(Q)?Q():Q;if(A(U,"root"))return U;return L(bQ("Function"))}default:return L(bQ(Y??T(Q)))}},J3=(Q,X)=>X.$.intrinsic.unknown.pipe((Y,U)=>{let Z=Q["~standard"].validate(Y);if(!Z.issues)return Z.value;for(let{message:W,path:G}of Z.issues)if(G)if(G.length)U.error({problem:W4(W),relativePath:G.map((_)=>typeof _==="object"?_.key:_)});else U.error({message:W});else U.error({message:W})}),L3=(Q,X)=>FY(Q,X)??TY(Q,X),bQ=(Q)=>`Type definitions must be strings or objects (was ${Q})`;class yQ extends l{constructor(Q){let X=Object.assign({errors:d,hkt:k,$:Q,raw:Q.parse,module:Q.constructor.module,scope:Q.constructor.scope,declare:Q.declare,define:Q.define,match:Q.match,generic:Q.generic,schema:Q.schema,keywords:Q.ambient,unit:Q.unit,enumerated:Q.enumerated,instanceOf:Q.instanceOf,valueOf:Q.valueOf,or:Q.or,and:Q.and,merge:Q.merge,pipe:Q.pipe,fn:Q.fn},Q.ambientAttachments);super((...Y)=>{if(Y.length===1)return Q.parse(Y[0]);if(Y.length===2&&typeof Y[0]==="string"&&Y[0][0]==="<"&&Y[0][Y[0].length-1]===">"){let U=Y[0].slice(1,-1),Z=Q.parseGenericParams(U,{});return new C1(Z,Y[1],Q,Q,null)}return Q.parse(Y)},{attach:X})}}var e1=F;class q6 extends Q6{get ambientAttachments(){if(!e1.typeAttachments)return;return this.cacheGetter("ambientAttachments",V(e1.typeAttachments,(Q,X)=>[Q,this.bindReference(X)]))}preparseOwnAliasEntry(Q,X){let Y=Q.indexOf("<");if(Y===-1){if(A(X,"module")||A(X,"generic"))return[Q,X];let W=this.name==="ark"?Q:Q==="root"?this.name:`${this.name}.${Q}`,G=this.resolvedConfig.keywords?.[W];if(G)X=[X,"@",G];return[Q,X]}if(Q[Q.length-1]!==">")L("'>' must be the last character of a generic declaration in a scope");let U=Q.slice(0,Y),Z=Q.slice(Y+1,-1);return[U,()=>{let W=this.parseGenericParams(Z,{alias:U});return y4(W,X,this)}]}parseGenericParams(Q,X){return L6(new O2(Q),[],this.createParseContext({...X,def:Q,prefix:"generic"}))}normalizeRootScopeValue(Q){if(T1(Q)&&!A(Q,"generic"))return Q();return Q}preparseOwnDefinitionFormat(Q,X){return{...X,def:Q,prefix:X.alias??"type"}}parseOwnDefinitionFormat(Q,X){if(!(X.alias&&(X.alias in this.aliases))&&!X.args)X.args={this:X.id};let U=F6(Q,X);if(K(U)){if(U[1]==="=")return L(W6);if(U[1]==="?")return L(Z6)}return U}unit=(Q)=>this.units([Q]);valueOf=(Q)=>this.units(rQ(Q));enumerated=(...Q)=>this.units(Q);instanceOf=(Q)=>this.node("proto",{proto:Q},{prereduced:!0});or=(...Q)=>this.schema(Q.map((X)=>this.parse(X)));and=(...Q)=>Q.reduce((X,Y)=>X.and(this.parse(Y)),this.intrinsic.unknown);merge=(...Q)=>Q.reduce((X,Y)=>X.merge(this.parse(Y)),this.intrinsic.object);pipe=(...Q)=>this.intrinsic.unknown.pipe(...Q);fn=new PQ(this);match=new EQ(this);declare=()=>({type:this.type});define(Q){return Q}type=new yQ(this);static scope=(Q,X={})=>new q6(Q,X);static module=(Q,X={})=>this.scope(Q,X).export()}var f2=Object.assign(q6.scope,{define:(Q)=>Q}),M=q6;class RY extends k{description='merge an object\'s properties onto another like `Merge(User, { isAdmin: "true" })`'}var H3=e(["base",z.object],["props",z.object])((Q)=>Q.base.merge(Q.props),RY),DY=M.module({Key:z.key,Merge:H3});class CY extends k{}var F3=e("element")((Q)=>{let X=Q.element.exclude(z.Array),Y=X.array();return X.rawOr(Y).pipe(V1).distribute((U)=>U.assertHasKind("morph").declareOut(Y),w)},CY),wY=M.module({root:z.Array,readonly:"root",index:z.nonNegativeIntegerString,liftFrom:F3},{name:"Array"});var fQ=w(["string",S1.FileConstructor]),q3=fQ.rawOr(fQ.array()),KY=w({meta:"an object representing parsed form data",domain:"object",index:{signature:"string",value:q3}}),NY=M.module({root:["instanceof",FormData],value:fQ,parsed:KY,parse:w({in:FormData,morphs:(Q)=>{let X={};for(let[Y,U]of Q)if(Y in X){let Z=X[Y];if(typeof Z==="string"||Z instanceof S1.FileConstructor)X[Y]=[Z,U];else Z.push(U)}else X[Y]=U;return X},declaredOut:KY})},{name:"FormData"});var PY=M.module({Int8:["instanceof",Int8Array],Uint8:["instanceof",Uint8Array],Uint8Clamped:["instanceof",Uint8ClampedArray],Int16:["instanceof",Int16Array],Uint16:["instanceof",Uint16Array],Int32:["instanceof",Int32Array],Uint32:["instanceof",Uint32Array],Float32:["instanceof",Float32Array],Float64:["instanceof",Float64Array],BigInt64:["instanceof",BigInt64Array],BigUint64:["instanceof",BigUint64Array]},{name:"TypedArray"});var $3={Boolean:1,Number:1,String:1},EY=M.module({...V({...D6,...w6},(Q,X)=>(Q in $3)?[]:[Q,["instanceof",X]]),Array:wY,TypedArray:PY,FormData:NY});var A3=w({domain:{domain:"number",meta:"a number representing a Unix timestamp"},divisor:{rule:1,meta:"an integer representing a Unix timestamp"},min:{rule:-8640000000000000,meta:"a Unix timestamp after -8640000000000000"},max:{rule:8640000000000000,meta:"a Unix timestamp before 8640000000000000"},meta:"an integer representing a safe Unix timestamp"}),z3=w({domain:"number",divisor:1}),$6=M.module({root:z.number,integer:z3,epoch:A3,safe:w({domain:{domain:"number",numberAllowsNaN:!1},min:Number.MIN_SAFE_INTEGER,max:Number.MAX_SAFE_INTEGER}),NaN:["===",Number.NaN],Infinity:["===",Number.POSITIVE_INFINITY],NegativeInfinity:["===",Number.NEGATIVE_INFINITY]},{name:"number"});var I=(Q,X,Y)=>{let U={domain:"string",pattern:{rule:Q.source,flags:Q.flags,meta:X}};if(Y)U.meta={format:Y};return r1("intersection",U)},IY=I(F2,"a well-formed integer string"),uY=M.module({root:IY,parse:w({in:IY,morphs:(Q,X)=>{let Y=Number.parseInt(Q);return Number.isSafeInteger(Y)?Y:X.error("an integer in the range Number.MIN_SAFE_INTEGER to Number.MAX_SAFE_INTEGER")},declaredOut:z.integer})},{name:"string.integer"}),O3=I(/^[\dA-Fa-f]+$/,"hex characters only"),V3=M.module({root:I(/^(?:[\d+/A-Za-z]{4})*(?:[\d+/A-Za-z]{2}==|[\d+/A-Za-z]{3}=)?$/,"base64-encoded"),url:I(/^(?:[\w-]{4})*(?:[\w-]{2}(?:==|%3D%3D)?|[\w-]{3}(?:=|%3D)?)?$/,"base64url-encoded")},{name:"string.base64"}),SY=I(/^[A-Z].*$/,"capitalized"),T3=M.module({root:w({in:"string",morphs:(Q)=>Q.charAt(0).toUpperCase()+Q.slice(1),declaredOut:SY}),preformatted:SY},{name:"string.capitalize"}),B3=(Q)=>{let X=Q.replace(/[ -]+/g,""),Y=0,U,Z,W=!1;for(let G=X.length-1;G>=0;G--){if(U=X.substring(G,G+1),Z=Number.parseInt(U,10),W)Z*=2,Y+=Z>=10?Z%10+1:Z;else Y+=Z;W=!W}return!!(Y%10===0?X:!1)},M3=/^(?:4\d{12}(?:\d{3,6})?|5[1-5]\d{14}|(222[1-9]|22[3-9]\d|2[3-6]\d{2}|27[01]\d|2720)\d{12}|6(?:011|5\d\d)\d{12,15}|3[47]\d{13}|3(?:0[0-5]|[68]\d)\d{11}|(?:2131|1800|35\d{3})\d{11}|6[27]\d{14}|^(81\d{14,17}))$/,R3=w({domain:"string",pattern:{meta:"a credit card number",rule:M3.source},predicate:{meta:"a credit card number",predicate:B3}});var D3=/^([+-]?\d{4}(?!\d{2}\b))((-?)((0[1-9]|1[0-2])(\3([12]\d|0[1-9]|3[01]))?|W([0-4]\d|5[0-3])(-?[1-7])?|(00[1-9]|0[1-9]\d|[12]\d{2}|3([0-5]\d|6[1-6])))(T((([01]\d|2[0-3])((:?)[0-5]\d)?|24:?00)([,.]\d+(?!:))?)?(\17[0-5]\d([,.]\d+)?)?([Zz]|([+-])([01]\d|2[0-3]):?([0-5]\d)?)?)?)?$/;var C3=(Q)=>!Number.isNaN(new Date(Q).valueOf()),jY=w({domain:"string",predicate:{meta:"a parsable date",predicate:C3}}).assertHasKind("intersection"),bY=uY.root.internal.narrow((Q,X)=>{let Y=Number.parseInt(Q),U=$6.epoch(Y);if(U instanceof d)return X.errors.merge(U),!1;return!0}).configure({description:"an integer string representing a safe Unix timestamp"},"self").assertHasKind("intersection"),w3=M.module({root:bY,parse:w({in:bY,morphs:(Q)=>new Date(Q),declaredOut:z.Date})},{name:"string.date.epoch"}),yY=I(D3,"an ISO 8601 (YYYY-MM-DDTHH:mm:ss.sssZ) date").internal.assertHasKind("intersection"),K3=M.module({root:yY,parse:w({in:yY,morphs:(Q)=>new Date(Q),declaredOut:z.Date})},{name:"string.date.iso"}),N3=M.module({root:jY,parse:w({declaredIn:jY,in:"string",morphs:(Q,X)=>{let Y=new Date(Q);if(Number.isNaN(Y.valueOf()))return X.error("a parsable date");return Y},declaredOut:z.Date}),iso:K3,epoch:w3},{name:"string.date"}),P3=I(/^[\w%+.-]+@[\d.A-Za-z-]+\.[A-Za-z]{2,}$/,"an email address","email"),fY="(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])",w1=`(${fY}[.]){3}${fY}`,E3=new RegExp(`^${w1}$`),j="(?:[0-9a-fA-F]{1,4})",I3=new RegExp(`^((?:${j}:){7}(?:${j}|:)|(?:${j}:){6}(?:${w1}|:${j}|:)|(?:${j}:){5}(?::${w1}|(:${j}){1,2}|:)|(?:${j}:){4}(?:(:${j}){0,1}:${w1}|(:${j}){1,3}|:)|(?:${j}:){3}(?:(:${j}){0,2}:${w1}|(:${j}){1,4}|:)|(?:${j}:){2}(?:(:${j}){0,3}:${w1}|(:${j}){1,5}|:)|(?:${j}:){1}(?:(:${j}){0,4}:${w1}|(:${j}){1,6}|:)|(?::((?::${j}){0,5}:${w1}|(?::${j}){1,7}|:)))(%[0-9a-zA-Z.]{1,})?$`),S3=M.module({root:["v4 | v6","@","an IP address"],v4:I(E3,"an IPv4 address","ipv4"),v6:I(I3,"an IPv6 address","ipv6")},{name:"string.ip"}),Q2="a JSON string",mY=(Q)=>{if(!(Q instanceof SyntaxError))throw Q;return`must be ${Q2} (${Q})`},j3=w({meta:Q2,domain:"string",predicate:{meta:Q2,predicate:(Q,X)=>{try{return JSON.parse(Q),!0}catch(Y){return X.reject({code:"predicate",expected:Q2,problem:mY(Y)})}}}}),b3=(Q,X)=>{if(Q.length===0)return X.error({code:"predicate",expected:Q2,actual:"empty"});try{return JSON.parse(Q)}catch(Y){return X.error({code:"predicate",expected:Q2,problem:mY(Y)})}},y3=M.module({root:j3,parse:w({meta:"safe JSON string parser",in:"string",morphs:b3,declaredOut:z.jsonObject})},{name:"string.json"}),vY=I(/^[a-z]*$/,"only lowercase letters"),f3=M.module({root:w({in:"string",morphs:(Q)=>Q.toLowerCase(),declaredOut:vY}),preformatted:vY},{name:"string.lower"}),lY=["NFC","NFD","NFKC","NFKD"],v2=V(lY,(Q,X)=>[X,w({domain:"string",predicate:(Y)=>Y.normalize(X)===Y,meta:`${X}-normalized unicode`})]),A6=V(lY,(Q,X)=>[X,w({in:"string",morphs:(Y)=>Y.normalize(X),declaredOut:v2[X]})]),v3=M.module({root:A6.NFC,preformatted:v2.NFC},{name:"string.normalize.NFC"}),k3=M.module({root:A6.NFD,preformatted:v2.NFD},{name:"string.normalize.NFD"}),g3=M.module({root:A6.NFKC,preformatted:v2.NFKC},{name:"string.normalize.NFKC"}),x3=M.module({root:A6.NFKD,preformatted:v2.NFKD},{name:"string.normalize.NFKD"}),h3=M.module({root:"NFC",NFC:v3,NFD:k3,NFKC:g3,NFKD:x3},{name:"string.normalize"}),kY=I(x2,"a well-formed numeric string"),p3=M.module({root:kY,parse:w({in:kY,morphs:(Q)=>Number.parseFloat(Q),declaredOut:z.number})},{name:"string.numeric"}),gY="a regex pattern",u3=w({domain:"string",predicate:{meta:gY,predicate:(Q,X)=>{try{return new RegExp(Q),!0}catch(Y){return X.reject({code:"predicate",expected:gY,problem:String(Y)})}}},meta:{format:"regex"}}),m3=/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[A-Za-z-][\dA-Za-z-]*)(?:\.(?:0|[1-9]\d*|\d*[A-Za-z-][\dA-Za-z-]*))*))?(?:\+([\dA-Za-z-]+(?:\.[\dA-Za-z-]+)*))?$/,l3=I(m3,"a semantic version (see https://semver.org/)"),xY=I(/^\S.*\S$|^\S?$/,"trimmed"),d3=M.module({root:w({in:"string",morphs:(Q)=>Q.trim(),declaredOut:xY}),preformatted:xY},{name:"string.trim"}),hY=I(/^[A-Z]*$/,"only uppercase letters"),c3=M.module({root:w({in:"string",morphs:(Q)=>Q.toUpperCase(),declaredOut:hY}),preformatted:hY},{name:"string.upper"}),o3=(Q)=>URL.canParse(Q),pY=w({domain:"string",predicate:{meta:"a URL string",predicate:o3},meta:{format:"uri"}}),i3=M.module({root:pY,parse:w({declaredIn:pY,in:"string",morphs:(Q,X)=>{try{return new URL(Q)}catch{return X.error("a URL string")}},declaredOut:w(URL)})},{name:"string.url"}),s3=M.module({root:["versioned | nil | max","@",{description:"a UUID",format:"uuid"}],"#nil":"'00000000-0000-0000-0000-000000000000'","#max":"'ffffffff-ffff-ffff-ffff-ffffffffffff'","#versioned":/[\da-f]{8}-[\da-f]{4}-[1-8][\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}/i,v1:I(/^[\da-f]{8}-[\da-f]{4}-1[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv1"),v2:I(/^[\da-f]{8}-[\da-f]{4}-2[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv2"),v3:I(/^[\da-f]{8}-[\da-f]{4}-3[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv3"),v4:I(/^[\da-f]{8}-[\da-f]{4}-4[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv4"),v5:I(/^[\da-f]{8}-[\da-f]{4}-5[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv5"),v6:I(/^[\da-f]{8}-[\da-f]{4}-6[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv6"),v7:I(/^[\da-f]{8}-[\da-f]{4}-7[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv7"),v8:I(/^[\da-f]{8}-[\da-f]{4}-8[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv8")},{name:"string.uuid"}),dY=M.module({root:z.string,alpha:I(/^[A-Za-z]*$/,"only letters"),alphanumeric:I(/^[\dA-Za-z]*$/,"only letters and digits 0-9"),hex:O3,base64:V3,capitalize:T3,creditCard:R3,date:N3,digits:I(/^\d*$/,"only digits 0-9"),email:P3,integer:uY,ip:S3,json:y3,lower:f3,normalize:h3,numeric:p3,regex:u3,semver:l3,trim:d3,upper:c3,url:i3,uuid:s3},{name:"string"});var cY=M.module({bigint:z.bigint,boolean:z.boolean,false:z.false,never:z.never,null:z.null,number:z.number,object:z.object,string:z.string,symbol:z.symbol,true:z.true,unknown:z.unknown,undefined:z.undefined}),oY=M.module({root:z.unknown,any:z.unknown},{name:"unknown"}),n3=M.module({root:z.jsonObject,stringify:r1("morph",{in:z.jsonObject,morphs:(Q)=>JSON.stringify(Q),declaredOut:z.string})},{name:"object.json"}),iY=M.module({root:z.object,json:n3},{name:"object"});class sY extends k{description='instantiate an object from an index signature and corresponding value type like `Record("string", "number")`'}var r3=e(["K",z.key],"V")((Q)=>({domain:"object",index:{signature:Q.K,value:Q.V}}),sY);class nY extends k{description='pick a set of properties from an object like `Pick(User, "name | age")`'}var t3=e(["T",z.object],["K",z.key])((Q)=>Q.T.pick(Q.K),nY);class rY extends k{description='omit a set of properties from an object like `Omit(User, "age")`'}var a3=e(["T",z.object],["K",z.key])((Q)=>Q.T.omit(Q.K),rY);class tY extends k{description="make all named properties of an object optional like `Partial(User)`"}var e3=e(["T",z.object])((Q)=>Q.T.partial(),tY);class aY extends k{description="make all named properties of an object required like `Required(User)`"}var Q9=e(["T",z.object])((Q)=>Q.T.required(),aY);class eY extends k{description='exclude branches of a union like `Exclude("boolean", "true")`'}var X9=e("T","U")((Q)=>Q.T.exclude(Q.U),eY);class QU extends k{description='extract branches of a union like `Extract("0 | false | 1", "number")`'}var Y9=e("T","U")((Q)=>Q.T.extract(Q.U),QU),XU=M.module({Exclude:X9,Extract:Y9,Omit:a3,Partial:e3,Pick:t3,Record:r3,Required:Q9});var O1=f2({...cY,...XU,...EY,...DY,string:dY,number:$6,object:iY,unknown:oY},{prereducedAliases:!0,name:"ark"}),v=O1.export();Object.assign(e1.ambient,v);e1.typeAttachments={string:v.string.root,number:v.number.root,bigint:v.bigint,boolean:v.boolean,symbol:v.symbol,undefined:v.undefined,null:v.null,object:v.object.root,unknown:v.unknown.root,false:v.false,true:v.true,never:v.never,arrayIndex:v.Array.index,Key:v.Key,Record:v.Record,Array:v.Array.root,Date:v.Date};var vQ=Object.assign(O1.type,e1.typeAttachments),U9=O1.match,Z9=O1.fn,W9=O1.generic,Cq=O1.schema,G9=O1.define,_9=O1.declare;var y1=f2({Operator:"'EQ' | '==' | 'NEQ' | '!=' | 'GT' | '>' | 'GTE' | '>=' | 'LT' | '<' | 'LTE' | '<=' | 'IN' | 'NOT_IN' | 'CONTAINS' | 'MATCHES' | 'RANGE' | 'SINCE' | 'AFTER' | 'BEFORE' | 'UNTIL'",Condition:"RangeCondition | ListCondition | ContainsCondition | NumericCondition | RegexCondition | BasicCondition",RangeCondition:{field:"string > 0",operator:"'RANGE'",value:"unknown[] == 2"},ListCondition:{field:"string > 0",operator:"'IN' | 'NOT_IN'",value:"unknown[]"},ContainsCondition:{field:"string > 0",operator:"'CONTAINS'",value:"string | unknown[]"},NumericCondition:{field:"string > 0",operator:"'>' | '>=' | '<' | '<=' | 'GT' | 'GTE' | 'LT' | 'LTE'",value:"number | string"},RegexCondition:{field:"string > 0",operator:"'MATCHES'",value:"string"},BasicCondition:{field:"string > 0",operator:"Operator",value:"unknown"},ConditionGroup:{operator:"'AND' | 'OR'",conditions:"(Condition | ConditionGroup)[] >= 1"},RuleCondition:"Condition | ConditionGroup",Action:{type:"string > 0","params?":"object","delay?":"number.integer >= 0","probability?":"0 <= number <= 1"},ActionGroup:{"mode?":"'ALL' | 'EITHER' | 'SEQUENCE'",actions:"(Action | ActionGroup)[] >= 1"},RuleAction:"Action | ActionGroup",TriggerRule:{id:"string > 0","name?":"string","description?":"string","priority?":"number.integer","enabled?":"boolean","cooldown?":"number.integer >= 0","tags?":"string[]",on:"string > 0","if?":"RuleCondition | RuleCondition[]",do:"RuleAction | RuleAction[]","comment?":"string"}}).export(),uq=y1.Operator,mq=y1.Condition,lq=y1.ConditionGroup,dq=y1.RuleCondition,cq=y1.Action,oq=y1.ActionGroup,J9=y1.TriggerRule;class L9{static validate(Q){let X=J9(Q);if(X instanceof vQ.errors){let Z=[];for(let W of X){let G=W.path.join("."),_=W.message,H=void 0;if(G.endsWith("on")&&(_.includes("string")||_.includes("must be")))if(typeof Q==="object"&&Q&&Q.on===!0)_="The 'on' field is incorrect (boolean true found).",H=`In YAML, 'on' is a boolean keyword (true). Quote it: "on": "EventName"`;else H="Ensure 'on' is a string event name.";Z.push({path:G,message:_,suggestion:H,severity:"error"})}return{valid:!1,issues:Z}}let Y=X,U=[];if(this.validateConditionsRecursive(Y.if,U,"if"),U.length>0)return{valid:!1,issues:U};return{valid:!0,rule:Y}}static validateConditionsRecursive(Q,X,Y){if(!Q)return;if(Array.isArray(Q)){Q.forEach((U,Z)=>{this.validateConditionsRecursive(U,X,`${Y}.${Z}`)});return}if("conditions"in Q&&Array.isArray(Q.conditions)){Q.conditions.forEach((U,Z)=>{this.validateConditionsRecursive(U,X,`${Y}.conditions.${Z}`)});return}if("operator"in Q&&"value"in Q)this.validateConditionValue(Q,X,Y)}static validateConditionValue(Q,X,Y){let{operator:U,value:Z}=Q;if(["IN","NOT_IN","RANGE","CONTAINS"].includes(U)){if(U==="CONTAINS"){if(typeof Z!=="string"&&!Array.isArray(Z))X.push({path:`${Y}.value`,message:`Incorrect value type: Operator 'CONTAINS' expects a String or List (Array), but received ${typeof Z}.`,suggestion:"Use a substring or a list of items.",severity:"error"});return}if(!Array.isArray(Z)){X.push({path:`${Y}.value`,message:`Incorrect value type: Operator '${U}' expects a List (Array), but received ${typeof Z}.`,suggestion:U==="RANGE"?"Use format [min, max]":"Use format [item1, item2]",severity:"error"});return}if(U==="RANGE"){if(Z.length!==2)X.push({path:`${Y}.value`,message:"Invalid Range: Operator 'RANGE' requires exactly 2 values (min and max).",suggestion:"Use format [min, max], e.g. [1, 10]",severity:"error"});else if(typeof Z[0]!=="number"&&typeof Z[0]!=="string")X.push({path:`${Y}.value`,message:"Incorrect range type: Range values must be numbers or expression strings.",severity:"error"})}}else if(U==="MATCHES")if(typeof Z!=="string")X.push({path:`${Y}.value`,message:`Incorrect value type: Operator 'MATCHES' expects a string (regex pattern), but received ${typeof Z}.`,severity:"error"});else try{new RegExp(Z)}catch(W){X.push({path:`${Y}.value`,message:`Invalid Regex pattern: ${W.message}`,severity:"error"})}else if(["GT","GTE","LT","LTE",">",">=","<","<="].includes(U)){if(typeof Z!=="number"&&typeof Z!=="string")X.push({path:`${Y}.value`,message:`Incorrect value type: Operator '${U}' expects a number or expression string, but received ${typeof Z}.`,severity:"error"})}}}export{L9 as TriggerValidator,Y2 as TriggerUtils,J9 as TriggerRuleSchema,W2 as TriggerEngine,Q1 as StateManager,B6 as RuleEngine,dq as RuleConditionSchema,V6 as InMemoryPersistence,i as ExpressionEngine,GU as EventQueue,W2 as Engine,JU as ContextAdapter,mq as ConditionSchema,lq as ConditionGroupSchema,uq as ComparisonOperatorSchema,xQ as BrowserPersistence,B6 as AdvancedRuleEngine,cq as ActionSchema,v1 as ActionRegistry,oq as ActionGroupSchema};
|
|
45
|
+
`)+"}");class X6{config;resolvedConfig;name;get[x](){return"scope"}referencesById={};references=[];resolutions={};exportedNames=[];aliases={};resolved=!1;nodesByHash={};intrinsic;constructor(Q,X){if(this.config=B2(F.config,X),this.resolvedConfig=B2(F.resolvedConfig,X),this.name=this.resolvedConfig.name??`anonymousScope${Object.keys(AQ).length}`,this.name in AQ)L(`A Scope already named ${this.name} already exists`);AQ[this.name]=this;let Y=Object.entries(Q).map((U)=>this.preparseOwnAliasEntry(...U));for(let[U,Z]of Y){let W=U;if(U[0]==="#"){if(W=U.slice(1),W in this.aliases)L(NX(W));this.aliases[W]=Z}else{if(W in this.aliases)L(NX(U));this.aliases[W]=Z,this.exportedNames.push(W)}if(!A(Z,"module")&&!A(Z,"generic")&&!M1(Z)){let G=this.preparseOwnDefinitionFormat(Z,{alias:W});this.resolutions[W]=A(G,"root")?this.bindReference(G):this.createParseContext(G).id}}EX??=this.node("union",{branches:["string","number","object","bigint","symbol",{unit:!0},{unit:!1},{unit:void 0},{unit:null}]},{prereduced:!0}),this.nodesByHash[EX.hash]=this.node("intersection",{},{prereduced:!0}),this.intrinsic=F.intrinsic?V(F.intrinsic,(U,Z)=>U.startsWith("json")?[]:[U,this.bindReference(Z)]):{}}cacheGetter(Q,X){return Object.defineProperty(this,Q,{value:X}),X}get internal(){return this}_json;get json(){if(!this._json)this.export();return this._json}defineSchema(Q){return Q}generic=(...Q)=>{let X=this;return(Y,U)=>new w1(Q,U?new i2(Y):Y,X,X,U??null)};units=(Q,X)=>{let Y=[];for(let Z of Q)if(!Y.includes(Z))Y.push(Z);let U=Y.map((Z)=>this.node("unit",{unit:Z},X));return this.node("union",U,{...X,prereduced:!0})};lazyResolutions=[];lazilyResolve(Q,X){let Y=this.node("alias",{reference:X??"synthetic",resolve:Q},{prereduced:!0});if(!this.resolved)this.lazyResolutions.push(Y);return Y}schema=(Q,X)=>this.finalize(this.parseSchema(Q,X));parseSchema=(Q,X)=>this.node(R2(Q),Q,X);preparseNode(Q,X,Y){let U=typeof Q==="string"?Q:R2(X,Q);if(P(X)&&X.kind===U)return X;if(U==="alias"&&!Y?.prereduced){let{reference:G}=E2.implementation.normalize(X,this);if(G.startsWith("$")){let _=this.resolveRoot(G.slice(1));X=_,U=_.kind}}else if(U==="union"&&p(X,"object")){let G=A8(X);if(G?.length===1)X=G[0],U=R2(X)}if(P(X)&&X.kind===U)return X;let W=o1[U].normalize?.(X,this)??X;if(P(W))return W.kind===U?W:z8(U,W.kind);return{...Y,$:this,kind:U,def:W,prefix:Y.alias??U}}bindReference(Q){let X;if(P(Q))X=Q.$===this?Q:new Q.constructor(Q.attachments,this);else X=Q.$===this?Q:new w1(Q.params,Q.bodyDef,Q.$,this,Q.hkt);if(!this.resolved)Object.assign(this.referencesById,X.referencesById);return X}resolveRoot(Q){return this.maybeResolveRoot(Q)??L(VQ(Q))}maybeResolveRoot(Q){let X=this.maybeResolve(Q);if(A(X,"generic"))return;return X}maybeResolveSubalias(Q){return zQ(this.aliases,Q)??zQ(this.ambient,Q)}get ambient(){return F.ambient}maybeResolve(Q){let X=this.resolutions[Q];if(X){if(typeof X!=="string")return this.bindReference(X);let U=h[X];if(A(U,"root"))return this.resolutions[Q]=U;if(A(U,"context")){if(U.phase==="resolving")return this.node("alias",{reference:`$${Q}`},{prereduced:!0});if(U.phase==="resolved")return C(`Unexpected resolved context for was uncached by its scope: ${B(U)}`);U.phase="resolving";let Z=this.bindReference(this.parseOwnDefinitionFormat(U.def,U));return U.phase="resolved",h[Z.id]=Z,h[U.id]=Z,this.resolutions[Q]=Z}return C(`Unexpected nodesById entry for ${X}: ${B(U)}`)}let Y=this.aliases[Q]??this.ambient?.[Q];if(!Y)return this.maybeResolveSubalias(Q);if(Y=this.normalizeRootScopeValue(Y),A(Y,"generic"))return this.resolutions[Q]=this.bindReference(Y);if(A(Y,"module")){if(!Y.root)L(vX(Q));return this.resolutions[Q]=this.bindReference(Y.root)}return this.resolutions[Q]=this.parse(Y,{alias:Q})}createParseContext(Q){let X=Q.id??t6(Q.prefix);return h[X]=Object.assign(Q,{[x]:"context",$:this,id:X,phase:"unresolved"})}traversal(Q){return new U1(Q,this.resolvedConfig)}import(...Q){return new n1(V(this.export(...Q),(X,Y)=>[`#${X}`,Y]))}precompilation;_exportedResolutions;_exports;export(...Q){if(!this._exports){this._exports={};for(let Y of this.exportedNames){let U=this.aliases[Y];this._exports[Y]=A(U,"module")?$Q(U,this):IX(this.maybeResolve(Y))}for(let Y of this.lazyResolutions)Y.resolution;if(this._exportedResolutions=fX(this,this._exports),this._json=yX(this._exportedResolutions),Object.assign(this.resolutions,this._exportedResolutions),this.references=Object.values(this.referencesById),!this.resolvedConfig.jitless){let Y=bX(this.references);this.precompilation=Y.write(SX,4),jX(this.references,Y)}this.resolved=!0}let X=Q.length?Q:this.exportedNames;return new n1(V(X,(Y,U)=>[U,this._exports[U]]))}resolve(Q){return this.export()[Q]}node=(Q,X,Y={})=>{let U=this.preparseNode(Q,X,Y);if(P(U))return this.bindReference(U);let Z=this.createParseContext(U),W=a6(Z),G=this.bindReference(W);return h[Z.id]=G};parse=(Q,X={})=>this.finalize(this.parseDefinition(Q,X));parseDefinition(Q,X={}){if(A(Q,"root"))return this.bindReference(Q);let Y=this.preparseOwnDefinitionFormat(Q,X);if(A(Y,"root"))return this.bindReference(Y);let U=this.createParseContext(Y);h[U.id]=U;let Z=this.bindReference(this.parseOwnDefinitionFormat(Q,U));if(Z.isCyclic)Z=t4(Z,U.id);return h[U.id]=Z,Z}finalize(Q){if(IX(Q),!Q.precompilation&&!this.resolvedConfig.jitless)O8(Q.references);return Q}}class OQ extends X6{parseOwnDefinitionFormat(Q,X){return a6(X)}preparseOwnDefinitionFormat(Q,X){return this.preparseNode(R2(Q),Q,X)}preparseOwnAliasEntry(Q,X){return[Q,X]}normalizeRootScopeValue(Q){return Q}}var IX=(Q)=>{let X=Q.references.filter((Y)=>Y.hasKind("alias"));for(let Y of X){Object.assign(Y.referencesById,Y.resolution.referencesById);for(let U of Q.references)if(Y.id in U.referencesById)Object.assign(U.referencesById,Y.referencesById)}return Q},yX=(Q)=>V(Q,(X,Y)=>[X,A(Y,"root")||A(Y,"generic")?Y.json:A(Y,"module")?yX(Y):C(`Unexpected resolution ${B(Y)}`)]),zQ=(Q,X)=>{let Y=X.indexOf(".");if(Y===-1)return;let U=X.slice(0,Y),Z=Q[U];if(Z===void 0)return;if(!A(Z,"module"))return L(V8(U));let W=X.slice(Y+1),G=Z[W];if(G===void 0)return zQ(Z,W);if(A(G,"root")||A(G,"generic"))return G;if(A(G,"module"))return G.root??L(vX(X));C(`Unexpected resolution for alias '${X}': ${B(G)}`)},Y6=(Q,X)=>new OQ(Q,X),j2=new OQ({});var fX=(Q,X)=>{let Y={};for(let U in X){let Z=X[U];if(A(Z,"module")){let W=fX(Q,Z),G=V(W,(_,H)=>[`${U}.${_}`,H]);Object.assign(Y,G)}else if(A(Z,"root")||A(Z,"generic"))Y[U]=Z;else C(`Unexpected scope resolution ${B(Z)}`)}return Y},VQ=(Q)=>`'${Q}' is unresolvable`,V8=(Q)=>`'${Q}' must reference a module to be accessed using dot syntax`,vX=(Q)=>`Reference to submodule '${Q}' must specify an alias`;j2.export();var{schema:w,node:r1,defineSchema:o7,generic:e}=j2;var BQ="^(?:0|[1-9]\\d*)$",B8=new RegExp(BQ),n7=S(B8);var kX=Y6({bigint:"bigint",boolean:[{unit:!1},{unit:!0}],false:{unit:!1},never:[],null:{unit:null},number:"number",object:"object",string:"string",symbol:"symbol",true:{unit:!0},unknown:{},undefined:{unit:void 0},Array,Date},{prereducedAliases:!0}).export();F.intrinsic={...kX};var gX=Y6({integer:{domain:"number",divisor:1},lengthBoundable:["string",Array],key:["string","symbol"],nonNegativeIntegerString:{domain:"string",pattern:BQ}},{prereducedAliases:!0}).export();Object.assign(F.intrinsic,gX);var M8=Y6({jsonPrimitive:["string","number",{unit:!0},{unit:!1},{unit:null}],jsonObject:{domain:"object",index:{signature:"string",value:"$jsonData"}},jsonData:["$jsonPrimitive","$jsonObject"]},{prereducedAliases:!0}).export(),z={...kX,...gX,...M8,emptyStructure:r1("structure",{},{prereduced:!0})};F.intrinsic={...z};var U6=(Q,X)=>new RegExp(Q,X);Object.assign(U6,{as:U6});var hX=(Q)=>typeof Q==="string"&&Q[0]==="d"&&(Q[1]==="'"||Q[1]==='"')&&Q[Q.length-1]===Q[1],xX=(Q)=>Q.toString()!=="Invalid Date",pX=(Q)=>Q.slice(2,-1),MQ=(Q)=>`'${Q}' could not be parsed by the Date constructor`,uX=(Q,X)=>T8(Q,X),T8=(Q,X)=>{let Y=new Date(Q);if(xX(Y))return Y;let U=$4(Q);if(U!==void 0){let Z=new Date(U);if(xX(Z))return Z}return X?L(X===!0?MQ(Q):X):void 0};var D8=w({proto:"Array",sequence:"string",required:{key:"groups",value:["object",{unit:void 0}]}}),Z6=(Q,X)=>{let Y=Q.scanner.shiftUntilEscapable(C8[dX[X]]);if(Q.scanner.lookahead==="")return Q.error(K8(Y,X));if(Q.scanner.shift(),X in lX){let U;try{U=new RegExp(Y)}catch(Z){L(String(Z))}if(Q.root=Q.ctx.$.node("intersection",{domain:"string",pattern:Y},{prereduced:!0}),X==="x/")Q.root=Q.ctx.$.node("morph",{in:Q.root,morphs:(Z)=>U.exec(Z),declaredOut:D8})}else if(f(X,TQ))Q.root=Q.ctx.$.node("unit",{unit:Y});else{let U=uX(Y,MQ(Y));Q.root=Q.ctx.$.node("unit",{meta:Y,unit:U})}},TQ={"'":1,'"':1},mX={"/":1,"'":1,'"':1},R8={"d'":"'",'d"':'"',"'":"'",'"':'"'},lX={"/":"/","x/":"/"},dX={...R8,...lX},C8={"'":(Q)=>Q.lookahead==="'",'"':(Q)=>Q.lookahead==='"',"/":(Q)=>Q.lookahead==="/"},w8={'"':"double-quote","'":"single-quote","/":"forward slash"},K8=(Q,X)=>`${X}${Q} requires a closing ${w8[dX[X]]}`;var cX=(Q)=>`Private type references should not include '#'. Use '${Q}' instead.`,W6="Optional definitions like 'string?' are only valid as properties in an object or tuple",G6="Defaultable definitions like 'number = 0' are only valid as properties in an object or tuple";var H1={"<":1,">":1,"=":1,"|":1,"&":1,")":1,"[":1,"%":1,",":1,":":1,"?":1,"#":1,...T1};var oX=(Q,X)=>Q===">"?X[0]==="="?X[1]==="=":X.trimStart()===""||f(X.trimStart()[0],H1):Q==="="?X[0]!=="=":Q===","||Q==="?";var iX=(Q,X,Y)=>sX(Q,X,Y,[]),sX=(Q,X,Y,U)=>{let Z=Y.parseUntilFinalizer();if(U.push(Z.root),Z.finalizer===">"){if(U.length!==X.params.length)return Y.error(DQ(Q,X.names,U.map((W)=>W.expression)));return U}if(Z.finalizer===",")return sX(Q,X,Y,U);return Z.error(u2(">"))},DQ=(Q,X,Y)=>`${Q}<${X.join(", ")}> requires exactly ${X.length} args (got ${Y.length}${Y.length===0?"":`: ${Y.join(", ")}`})`;var _6=(Q)=>{let X=Q.scanner.shiftUntilLookahead(H1);if(X==="keyof")Q.addPrefix("keyof");else Q.root=N8(Q,X)},P8=(Q,X,Y)=>{if(Y.scanner.shiftUntilNonWhitespace(),Y.scanner.shift()!=="<")return Y.error(DQ(Q,X.names,[]));let Z=iX(Q,X,Y);return X(...Z)},N8=(Q,X)=>E8(Q,X)??I8(Q,X)??Q.error(X===""?Q.scanner.lookahead==="#"?cX(Q.shiftedBy(1).scanner.shiftUntilLookahead(H1)):RQ(Q):VQ(X)),E8=(Q,X)=>{if(Q.ctx.args?.[X]){let U=Q.ctx.args[X];if(typeof U!=="string")return U;return Q.ctx.$.node("alias",{reference:U},{prereduced:!0})}let Y=Q.ctx.$.maybeResolve(X);if(A(Y,"root"))return Y;if(Y===void 0)return;if(A(Y,"generic"))return P8(X,Y,Q);return L(`Unexpected resolution ${B(Y)}`)},I8=(Q,X)=>{let Y=A4(X);if(Y!==void 0)return Q.ctx.$.node("unit",{unit:Y});let U=O4(X);if(U!==void 0)return Q.ctx.$.node("unit",{unit:U})},RQ=(Q)=>{let X=Q.previousOperator();return X?CQ(X,Q.scanner.unscanned):S8(Q.scanner.unscanned)},CQ=(Q,X="")=>`Token '${Q}' requires a right operand${X?` before '${X}'`:""}`,S8=(Q)=>`Expected an expression${Q?` before '${Q}'`:""}`;var wQ=(Q)=>Q.scanner.lookahead===""?Q.error(RQ(Q)):Q.scanner.lookahead==="("?Q.shiftedBy(1).reduceGroupOpen():Q.scanner.lookaheadIsIn(mX)?Z6(Q,Q.scanner.shift()):Q.scanner.lookaheadIsIn(T1)?wQ(Q.shiftedBy(1)):Q.scanner.lookahead==="d"?Q.scanner.nextLookahead in TQ?Z6(Q,`${Q.scanner.shift()}${Q.scanner.shift()}`):_6(Q):Q.scanner.lookahead==="x"?Q.scanner.nextLookahead==="/"?Q.shiftedBy(2)&&Z6(Q,"x/"):_6(Q):_6(Q);var nX={">":!0,">=":!0},rX={"<":!0,"<=":!0};var t1={"<":">",">":"<","<=":">=",">=":"<=","==":"=="},tX=(Q,X)=>`Left bounds are only valid when paired with right bounds (try ...${X}${Q})`,J6=(Q)=>`Left-bounded expressions must specify their limits using < or <= (was ${Q})`,aX=(Q,X,Y,U)=>`An expression may have at most one left bound (parsed ${Q}${t1[X]}, ${Y}${t1[U]})`;var QY=(Q,X)=>{let Y=j8(Q,X);if(Q.root.hasKind("unit")){if(typeof Q.root.unit==="number"){Q.reduceLeftBound(Q.root.unit,Y),Q.unsetRoot();return}if(Q.root.unit instanceof Date){let U=`d'${Q.root.description??Q.root.unit.toISOString()}'`;Q.unsetRoot(),Q.reduceLeftBound(U,Y);return}}return y8(Q,Y)},XY={"<":1,">":1,"=":1},j8=(Q,X)=>Q.scanner.lookaheadIs("=")?`${X}${Q.scanner.shift()}`:X;var eX=(Q,X,Y,U)=>{if(Y.extends(F.intrinsic.number)){if(typeof X!=="number")return L(KQ(Q,X,U));return Q==="=="?["min","max"]:Q[0]===">"?["min"]:["max"]}if(Y.extends(F.intrinsic.lengthBoundable)){if(typeof X!=="number")return L(KQ(Q,X,U));return Q==="=="?["exactLength"]:Q[0]===">"?["minLength"]:["maxLength"]}if(Y.extends(F.intrinsic.Date))return Q==="=="?["after","before"]:Q[0]===">"?["after"]:["before"];return L(x4(Y.expression))},b8=(Q)=>({rule:hX(Q.limit)?pX(Q.limit):Q.limit,exclusive:Q.comparator.length===1}),y8=(Q,X)=>{let Y=Q.unsetRoot(),U=Q.scanner.location;Q.parseOperand();let Z=Q.unsetRoot(),W=Q.scanner.sliceChars(U,Q.scanner.location);if(Q.root=Y,!Z.hasKind("unit")||typeof Z.unit!=="number"&&!(Z.unit instanceof Date))return Q.error(KQ(X,W,"right"));let G=Z.unit,_=X.length===1,H=eX(X,typeof G==="number"?G:W,Y,"right");for(let $ of H)Q.constrainRoot($,X==="=="?{rule:G}:{rule:G,exclusive:_});if(!Q.branches.leftBound)return;if(!f(X,rX))return Q.error(J6(X));let J=eX(Q.branches.leftBound.comparator,Q.branches.leftBound.limit,Y,"left");Q.constrainRoot(J[0],b8(Q.branches.leftBound)),Q.branches.leftBound=null},KQ=(Q,X,Y)=>`Comparator ${Y==="left"?t1[Q]:Q} must be ${Y==="left"?"preceded":"followed"} by a corresponding literal (was ${X})`;var YY=(Q)=>{Q.scanner.shiftUntilNonWhitespace();let X=Q.scanner.shiftUntilLookahead(H1);Q.root=Q.root.brand(X)};var ZY=(Q)=>{Q.scanner.shiftUntilNonWhitespace();let X=Q.scanner.shiftUntilLookahead(H1),Y=z4(X,{errorOnFail:UY(X)});if(Y===0)Q.error(UY(0));Q.root=Q.root.constrain("divisor",Y)},UY=(Q)=>`% operator must be followed by a non-zero integer literal (was ${Q})`;var PQ=(Q)=>{let X=Q.scanner.shift();return X===""?Q.finalize(""):X==="["?Q.scanner.shift()==="]"?Q.setRoot(Q.root.array()):Q.error(f8):X==="|"?Q.scanner.lookahead===">"?Q.shiftedBy(1).pushRootToBranch("|>"):Q.pushRootToBranch(X):X==="&"?Q.pushRootToBranch(X):X===")"?Q.finalizeGroup():oX(X,Q.scanner.unscanned)?Q.finalize(X):f(X,XY)?QY(Q,X):X==="%"?ZY(Q):X==="#"?YY(Q):(X in T1)?PQ(Q):Q.error(L6(X))},L6=(Q,X="")=>`'${Q}' is not allowed here${X&&` (should be ${X})`}`,f8="Missing expected ']'";var WY=(Q)=>{let X=Q.unsetRoot();Q.parseOperand();let Y=Q.unsetRoot();if(!Y.hasKind("unit"))return Q.error(v8(Y.expression));let U=Y.unit instanceof Date?()=>new Date(Y.unit):Y.unit;return[X,"=",U]},v8=(Q)=>`Default value '${Q}' must be a literal value`;var NQ=(Q,X)=>{let Y=X.$.maybeResolveRoot(Q);if(Y)return Y;if(Q.endsWith("[]")){let W=X.$.maybeResolveRoot(Q.slice(0,-2));if(W)return W.array()}let U=new a1(new O2(Q),X),Z=k8(U);if(U.finalizer===">")L(L6(">"));return Z},k8=(Q)=>{Q.parseOperand();let X=b2(Q).root;if(!X)return C(`Root was unexpectedly unset after parsing string '${Q.scanner.scanned}'`);if(Q.finalizer==="=")X=WY(Q);else if(Q.finalizer==="?")X=[X,"?"];if(Q.scanner.shiftUntilNonWhitespace(),Q.scanner.lookahead)L(L6(Q.scanner.lookahead));return X},b2=(Q)=>{while(Q.finalizer===void 0)g8(Q);return Q},g8=(Q)=>Q.hasRoot()?Q.parseOperator():Q.parseOperand();class a1{root;branches={prefixes:[],leftBound:null,intersection:null,union:null,pipe:null};finalizer;groups=[];scanner;ctx;constructor(Q,X){this.scanner=Q,this.ctx=X}error(Q){return L(Q)}hasRoot(){return this.root!==void 0}setRoot(Q){this.root=Q}unsetRoot(){let Q=this.root;return this.root=void 0,Q}constrainRoot(...Q){this.root=this.root.constrain(Q[0],Q[1])}finalize(Q){if(this.groups.length)return this.error(u2(")"));this.finalizeBranches(),this.finalizer=Q}reduceLeftBound(Q,X){let Y=t1[X];if(!f(Y,nX))return this.error(J6(X));if(this.branches.leftBound)return this.error(aX(this.branches.leftBound.limit,this.branches.leftBound.comparator,Q,Y));this.branches.leftBound={comparator:Y,limit:Q}}finalizeBranches(){if(this.assertRangeUnset(),this.branches.pipe){this.pushRootToBranch("|>"),this.root=this.branches.pipe;return}if(this.branches.union){this.pushRootToBranch("|"),this.root=this.branches.union;return}if(this.branches.intersection){this.pushRootToBranch("&"),this.root=this.branches.intersection;return}this.applyPrefixes()}finalizeGroup(){this.finalizeBranches();let Q=this.groups.pop();if(!Q)return this.error(T4(")",this.scanner.unscanned));this.branches=Q}addPrefix(Q){this.branches.prefixes.push(Q)}applyPrefixes(){while(this.branches.prefixes.length){let Q=this.branches.prefixes.pop();this.root=Q==="keyof"?this.root.keyof():C(`Unexpected prefix '${Q}'`)}}pushRootToBranch(Q){this.assertRangeUnset(),this.applyPrefixes();let X=this.root;if(this.root=void 0,this.branches.intersection=this.branches.intersection?.rawAnd(X)??X,Q==="&")return;if(this.branches.union=this.branches.union?.rawOr(this.branches.intersection)??this.branches.intersection,this.branches.intersection=null,Q==="|")return;this.branches.pipe=this.branches.pipe?.rawPipeOnce(this.branches.union)??this.branches.union,this.branches.union=null}parseUntilFinalizer(){return b2(new a1(this.scanner,this.ctx))}parseOperator(){return PQ(this)}parseOperand(){return wQ(this)}assertRangeUnset(){if(this.branches.leftBound)return this.error(tX(this.branches.leftBound.limit,this.branches.leftBound.comparator))}reduceGroupOpen(){this.groups.push(this.branches),this.branches={prefixes:[],leftBound:null,union:null,intersection:null,pipe:null}}previousOperator(){return this.branches.leftBound?.comparator??this.branches.prefixes[this.branches.prefixes.length-1]??(this.branches.intersection?"&":this.branches.union?"|":this.branches.pipe?"|>":void 0)}shiftedBy(Q){return this.scanner.jumpForward(Q),this}}var x8="An empty string is not a valid generic parameter name",H6=(Q,X,Y)=>{Q.shiftUntilNonWhitespace();let U=Q.shiftUntilLookahead(H1);if(U===""){if(Q.lookahead===""&&X.length)return X;return L(x8)}return Q.shiftUntilNonWhitespace(),h8(Q,U,X,Y)},GY="extends ",h8=(Q,X,Y,U)=>{if(Q.shiftUntilNonWhitespace(),Q.unscanned.startsWith(GY))Q.jumpForward(GY.length);else{if(Q.lookahead===",")Q.shift();return Y.push(X),H6(Q,Y,U)}let Z=b2(new a1(Q,U));return Y.push([X,Z.root]),H6(Q,Y,U)};class EQ extends l{constructor(Q){let X={$:Q,raw:Q.fn};super((...Y)=>{let U=Y.indexOf(":"),Z=U===-1?Y.length-1:U-1,W=Y.slice(0,Z+1),G=Q.parse(W).assertHasKind("intersection"),_=Q.intrinsic.unknown;if(U!==-1){if(U!==Y.length-2)return L(p8);_=Q.parse(Y[U+1])}return(H)=>new _Y(H,G,_)},{attach:X})}}class _Y extends l{raw;params;returns;expression;constructor(Q,X,Y){let U=`typed ${Q.name}`,Z={[U]:(...G)=>{let _=X.assert(G),H=Q(..._);return Y.assert(H)}}[U];super(Z);this.raw=Q,this.params=X,this.returns=Y;let W=X.expression;if(W[0]==="["&&W[W.length-1]==="]")W=W.slice(1,-1);else if(W.endsWith("[]"))W=`...${W}`;this.expression=`(${W}) => ${Y?.expression??"unknown"}`}}var p8=`":" must be followed by exactly one return type e.g:
|
|
46
|
+
fn("string", ":", "number")(s => s.length)`;class IQ extends l{$;constructor(Q){super((...X)=>new y2(Q)(...X),{bind:Q});this.$=Q}in(Q){return new y2(this.$,Q===void 0?void 0:this.$.parse(Q))}at(Q,X){return new y2(this.$).at(Q,X)}case(Q,X){return new y2(this.$).case(Q,X)}}class y2 extends l{$;in;key;branches=[];constructor(Q,X){super((Y)=>this.caseEntries(Object.entries(Y).map(([U,Z])=>U==="default"?[U,Z]:[this.$.parse(U),Z])));this.$=Q,this.in=X}at(Q,X){if(this.key)L(m8);if(this.branches.length)L(u8);return this.key=Q,X?this.match(X):this}case(Q,X){return this.caseEntry(this.$.parse(Q),X)}caseEntry(Q,X){let U=(this.key?this.$.parse({[this.key]:Q}):Q).pipe(X);return this.branches.push(U),this}match(Q){return this(Q)}strings(Q){return this.caseEntries(Object.entries(Q).map(([X,Y])=>X==="default"?[X,Y]:[this.$.node("unit",{unit:X}),Y]))}caseEntries(Q){for(let X=0;X<Q.length;X++){let[Y,U]=Q[X];if(Y==="default"){if(X!==Q.length-1)L("default may only be specified as the last key of a switch definition");return this.default(U)}if(typeof U!=="function")return L(`Value for case "${Y}" must be a function (was ${y(U)})`);this.caseEntry(Y,U)}return this}default(Q){if(typeof Q==="function")this.case(z.unknown,Q);let X={branches:this.branches,ordered:!0};if(Q==="never"||Q==="assert")X.meta={onFail:JY};let Y=this.$.node("union",X);if(!this.in)return this.$.finalize(Y);let U=this.in.pipe(Y);if(Q==="never"||Q==="assert")U=U.configureReferences({onFail:JY},"self");return this.$.finalize(U)}}var JY=(Q)=>Q.throw(),u8="A key matcher must be specified before the first case i.e. match.at('foo') or match.in<object>().at('bar')",m8="At most one key matcher may be specified per expression";var F6=(Q,X)=>{if(K(Q)){if(Q[1]==="=")return[X.$.parseOwnDefinitionFormat(Q[0],X),"=",Q[2]];if(Q[1]==="?")return[X.$.parseOwnDefinitionFormat(Q[0],X),"?"]}return q6(Q,X)},LY="Only required keys may make their values optional, e.g. { [mySymbol]: ['number', '?'] }",HY="Only required keys may specify default values, e.g. { value: 'number = 0' }";var FY=(Q,X)=>{let Y,U={},Z=N1(Q);for(let[G,_]of Z){let H=c8(G);if(H.kind==="spread"){if(!J1(U))return L(d8);let b=X.$.parseOwnDefinitionFormat(_,X);if(b.equals(z.object))continue;if(!b.hasKind("intersection")||!b.basis?.equals(z.object))return L(o8(b.expression));Y=b.structure;continue}if(H.kind==="undeclared"){if(_!=="reject"&&_!=="delete"&&_!=="ignore")L(l8(_));U.undeclared=_;continue}let J=F6(_,X),$=H;if(H.kind==="required"){if(!K(J))SQ(U,"required",{key:H.normalized,value:J},X);else SQ(U,"optional",J[1]==="="?{key:H.normalized,value:J[0],default:J[2]}:{key:H.normalized,value:J[0]},X);continue}if(K(J)){if(J[1]==="?")L(LY);if(J[1]==="=")L(HY)}if(H.kind==="optional"){SQ(U,"optional",{key:H.normalized,value:J},X);continue}let O=X.$.parseOwnDefinitionFormat($.normalized,X),R=Q6(O,J,X.$);if(R.index)U.index=D(U.index,R.index);if(R.required)U.required=D(U.required,R.required)}let W=X.$.node("structure",U);return X.$.parseSchema({domain:"object",structure:Y?.merge(W)??W})},SQ=(Q,X,Y,U)=>{Q[X]=D(Q[X],U.$.node(X,Y))},l8=(Q)=>`Value of '+' key must be 'reject', 'delete', or 'ignore' (was ${B(Q)})`,d8="Spread operator may only be used as the first key in an object",c8=(Q)=>typeof Q==="symbol"?{kind:"required",normalized:Q}:Q[Q.length-1]==="?"?Q[Q.length-2]===I1?{kind:"required",normalized:`${Q.slice(0,-2)}?`}:{kind:"optional",normalized:Q.slice(0,-1)}:Q[0]==="["&&Q[Q.length-1]==="]"?{kind:"index",normalized:Q.slice(1,-1)}:Q[0]===I1&&Q[1]==="["&&Q[Q.length-1]==="]"?{kind:"required",normalized:Q.slice(1)}:Q==="..."?{kind:"spread"}:Q==="+"?{kind:"undeclared"}:{kind:"required",normalized:Q==="\\..."?"...":Q==="\\+"?"+":Q},o8=(Q)=>`Spread operand must resolve to an object literal type (was ${Q})`;var $Y=(Q,X)=>Y3(Q)?VY[Q[0]](Q,X):Q3(Q)?OY[Q[1]](Q,X):null,i8=(Q,X)=>X.$.parseOwnDefinitionFormat(Q[1],X).keyof(),jQ=(Q,X)=>{if(Q[2]===void 0)return L(CQ(Q[1],""));let Y=X.$.parseOwnDefinitionFormat(Q[0],X),U=X.$.parseOwnDefinitionFormat(Q[2],X);if(Q[1]==="|")return X.$.node("union",{branches:[Y,U]});let Z=Q[1]==="&"?o(Y,U,X.$):D2(Y,U,X.$);if(Z instanceof q)return Z.throw();return Z},s8=(Q,X)=>X.$.parseOwnDefinitionFormat(Q[0],X).array(),n8=(Q,X)=>{if(typeof Q[2]!=="function")return L(AY("=>",Q[2]));return X.$.parseOwnDefinitionFormat(Q[0],X).pipe(Q[2])},AY=(Q,X)=>`${Q===":"?"Narrow":"Morph"} expression requires a function following '${Q}' (was ${typeof X})`,r8=(Q,X)=>{if(typeof Q[2]!=="function")return L(AY(":",Q[2]));return X.$.parseOwnDefinitionFormat(Q[0],X).constrain("predicate",Q[2])},t8=(Q,X)=>X.$.parseOwnDefinitionFormat(Q[0],X).configure(Q[2],Q[3]),zY=(Q)=>Q,a8=zY({"[]":s8,"?":()=>L(W6)}),e8=zY({"|":jQ,"&":jQ,":":r8,"=>":n8,"|>":jQ,"@":t8,"=":()=>L(G6)}),OY={...a8,...e8},Q3=(Q)=>OY[Q[1]]!==void 0,X3=(Q)=>Q,VY=X3({keyof:i8,instanceof:(Q,X)=>{if(typeof Q[1]!=="function")return L(qY(L2(Q[1])));let Y=Q.slice(1).map((U)=>typeof U==="function"?X.$.node("proto",{proto:U}):L(qY(L2(U))));return Y.length===1?Y[0]:X.$.node("union",{branches:Y})},"===":(Q,X)=>X.$.units(Q.slice(1))}),Y3=(Q)=>VY[Q[0]]!==void 0,qY=(Q)=>`Expected a constructor following 'instanceof' operator (was ${Q})`;var TY=(Q,X)=>{let Y=[{}],U=0;while(U<Q.length){let Z=!1;if(Q[U]==="..."&&U<Q.length-1)Z=!0,U++;let W=F6(Q[U],X),[G,_,H]=!K(W)?[W]:W;if(U++,Z){if(!G.extends(F.intrinsic.Array))return L(W3(G.expression));Y=Y.flatMap((J)=>G.distribute(($)=>Z3(l2(J),$)))}else Y=Y.map((J)=>{if(_==="?")return DY(J,G);if(_==="=")return U3(J,G,H);return bQ(J,G)})}return X.$.parseSchema(Y.map((Z)=>J1(Z)?{proto:Array,exactLength:0}:{proto:Array,sequence:Z}))},bQ=(Q,X)=>{if(Q.defaultables||Q.optionals)return L(Q.variadic?HQ:G3);if(Q.variadic)Q.postfix=D(Q.postfix,X);else Q.prefix=D(Q.prefix,X);return Q},DY=(Q,X)=>{if(Q.variadic)return L(RY);return Q.optionals=D(Q.optionals,X),Q},U3=(Q,X,Y)=>{if(Q.variadic)return L(RY);if(Q.optionals)return L(_3);return Q.defaultables=D(Q.defaultables,[[X,Y]]),Q},BY=(Q,X)=>{if(Q.postfix)L(MY);if(Q.variadic){if(!Q.variadic.equals(X))L(MY)}else Q.variadic=X.internal;return Q},Z3=(Q,X)=>{let Y=X.select({method:"find",kind:"sequence"});if(!Y)return BY(Q,F.intrinsic.unknown);if(Y.prefix)for(let U of Y.prefix)bQ(Q,U);if(Y.optionals)for(let U of Y.optionals)DY(Q,U);if(Y.variadic)BY(Q,Y.variadic);if(Y.postfix)for(let U of Y.postfix)bQ(Q,U);return Q},W3=(Q)=>`Spread element must be an array (was ${Q})`,MY="A tuple may have at most one variadic element",G3="A required element may not follow an optional element",RY="An optional element may not follow a variadic element";var _3="A defaultable element may not follow an optional element without a default";var J3={},q6=(Q,X)=>{if(typeof Q==="string"){if(X.args&&Object.keys(X.args).some((U)=>Q.includes(U)))return NQ(Q,X);let Y=J3[X.$.name]??={};return Y[Q]??=NQ(Q,X)}return p(Q,"object")?L3(Q,X):L(yQ(y(Q)))},L3=(Q,X)=>{let Y=J2(Q);switch(Y){case void 0:if(A(Q,"root"))return Q;if("~standard"in Q)return H3(Q,X);return FY(Q,X);case"Array":return F3(Q,X);case"RegExp":return X.$.node("intersection",{domain:"string",pattern:Q},{prereduced:!0});case"Function":{let U=M1(Q)?Q():Q;if(A(U,"root"))return U;return L(yQ("Function"))}default:return L(yQ(Y??B(Q)))}},H3=(Q,X)=>X.$.intrinsic.unknown.pipe((Y,U)=>{let Z=Q["~standard"].validate(Y);if(!Z.issues)return Z.value;for(let{message:W,path:G}of Z.issues)if(G)if(G.length)U.error({problem:_4(W),relativePath:G.map((_)=>typeof _==="object"?_.key:_)});else U.error({message:W});else U.error({message:W})}),F3=(Q,X)=>$Y(Q,X)??TY(Q,X),yQ=(Q)=>`Type definitions must be strings or objects (was ${Q})`;class fQ extends l{constructor(Q){let X=Object.assign({errors:d,hkt:k,$:Q,raw:Q.parse,module:Q.constructor.module,scope:Q.constructor.scope,declare:Q.declare,define:Q.define,match:Q.match,generic:Q.generic,schema:Q.schema,keywords:Q.ambient,unit:Q.unit,enumerated:Q.enumerated,instanceOf:Q.instanceOf,valueOf:Q.valueOf,or:Q.or,and:Q.and,merge:Q.merge,pipe:Q.pipe,fn:Q.fn},Q.ambientAttachments);super((...Y)=>{if(Y.length===1)return Q.parse(Y[0]);if(Y.length===2&&typeof Y[0]==="string"&&Y[0][0]==="<"&&Y[0][Y[0].length-1]===">"){let U=Y[0].slice(1,-1),Z=Q.parseGenericParams(U,{});return new w1(Z,Y[1],Q,Q,null)}return Q.parse(Y)},{attach:X})}}var e1=F;class $6 extends X6{get ambientAttachments(){if(!e1.typeAttachments)return;return this.cacheGetter("ambientAttachments",V(e1.typeAttachments,(Q,X)=>[Q,this.bindReference(X)]))}preparseOwnAliasEntry(Q,X){let Y=Q.indexOf("<");if(Y===-1){if(A(X,"module")||A(X,"generic"))return[Q,X];let W=this.name==="ark"?Q:Q==="root"?this.name:`${this.name}.${Q}`,G=this.resolvedConfig.keywords?.[W];if(G)X=[X,"@",G];return[Q,X]}if(Q[Q.length-1]!==">")L("'>' must be the last character of a generic declaration in a scope");let U=Q.slice(0,Y),Z=Q.slice(Y+1,-1);return[U,()=>{let W=this.parseGenericParams(Z,{alias:U});return v4(W,X,this)}]}parseGenericParams(Q,X){return H6(new O2(Q),[],this.createParseContext({...X,def:Q,prefix:"generic"}))}normalizeRootScopeValue(Q){if(M1(Q)&&!A(Q,"generic"))return Q();return Q}preparseOwnDefinitionFormat(Q,X){return{...X,def:Q,prefix:X.alias??"type"}}parseOwnDefinitionFormat(Q,X){if(!(X.alias&&(X.alias in this.aliases))&&!X.args)X.args={this:X.id};let U=q6(Q,X);if(K(U)){if(U[1]==="=")return L(G6);if(U[1]==="?")return L(W6)}return U}unit=(Q)=>this.units([Q]);valueOf=(Q)=>this.units(aQ(Q));enumerated=(...Q)=>this.units(Q);instanceOf=(Q)=>this.node("proto",{proto:Q},{prereduced:!0});or=(...Q)=>this.schema(Q.map((X)=>this.parse(X)));and=(...Q)=>Q.reduce((X,Y)=>X.and(this.parse(Y)),this.intrinsic.unknown);merge=(...Q)=>Q.reduce((X,Y)=>X.merge(this.parse(Y)),this.intrinsic.object);pipe=(...Q)=>this.intrinsic.unknown.pipe(...Q);fn=new EQ(this);match=new IQ(this);declare=()=>({type:this.type});define(Q){return Q}type=new fQ(this);static scope=(Q,X={})=>new $6(Q,X);static module=(Q,X={})=>this.scope(Q,X).export()}var f2=Object.assign($6.scope,{define:(Q)=>Q}),T=$6;class CY extends k{description='merge an object\'s properties onto another like `Merge(User, { isAdmin: "true" })`'}var q3=e(["base",z.object],["props",z.object])((Q)=>Q.base.merge(Q.props),CY),wY=T.module({Key:z.key,Merge:q3});class KY extends k{}var $3=e("element")((Q)=>{let X=Q.element.exclude(z.Array),Y=X.array();return X.rawOr(Y).pipe(B1).distribute((U)=>U.assertHasKind("morph").declareOut(Y),w)},KY),PY=T.module({root:z.Array,readonly:"root",index:z.nonNegativeIntegerString,liftFrom:$3},{name:"Array"});var vQ=w(["string",S1.FileConstructor]),A3=vQ.rawOr(vQ.array()),NY=w({meta:"an object representing parsed form data",domain:"object",index:{signature:"string",value:A3}}),EY=T.module({root:["instanceof",FormData],value:vQ,parsed:NY,parse:w({in:FormData,morphs:(Q)=>{let X={};for(let[Y,U]of Q)if(Y in X){let Z=X[Y];if(typeof Z==="string"||Z instanceof S1.FileConstructor)X[Y]=[Z,U];else Z.push(U)}else X[Y]=U;return X},declaredOut:NY})},{name:"FormData"});var IY=T.module({Int8:["instanceof",Int8Array],Uint8:["instanceof",Uint8Array],Uint8Clamped:["instanceof",Uint8ClampedArray],Int16:["instanceof",Int16Array],Uint16:["instanceof",Uint16Array],Int32:["instanceof",Int32Array],Uint32:["instanceof",Uint32Array],Float32:["instanceof",Float32Array],Float64:["instanceof",Float64Array],BigInt64:["instanceof",BigInt64Array],BigUint64:["instanceof",BigUint64Array]},{name:"TypedArray"});var z3={Boolean:1,Number:1,String:1},SY=T.module({...V({...C6,...K6},(Q,X)=>(Q in z3)?[]:[Q,["instanceof",X]]),Array:PY,TypedArray:IY,FormData:EY});var O3=w({domain:{domain:"number",meta:"a number representing a Unix timestamp"},divisor:{rule:1,meta:"an integer representing a Unix timestamp"},min:{rule:-8640000000000000,meta:"a Unix timestamp after -8640000000000000"},max:{rule:8640000000000000,meta:"a Unix timestamp before 8640000000000000"},meta:"an integer representing a safe Unix timestamp"}),V3=w({domain:"number",divisor:1}),A6=T.module({root:z.number,integer:V3,epoch:O3,safe:w({domain:{domain:"number",numberAllowsNaN:!1},min:Number.MIN_SAFE_INTEGER,max:Number.MAX_SAFE_INTEGER}),NaN:["===",Number.NaN],Infinity:["===",Number.POSITIVE_INFINITY],NegativeInfinity:["===",Number.NEGATIVE_INFINITY]},{name:"number"});var I=(Q,X,Y)=>{let U={domain:"string",pattern:{rule:Q.source,flags:Q.flags,meta:X}};if(Y)U.meta={format:Y};return r1("intersection",U)},jY=I(F2,"a well-formed integer string"),lY=T.module({root:jY,parse:w({in:jY,morphs:(Q,X)=>{let Y=Number.parseInt(Q);return Number.isSafeInteger(Y)?Y:X.error("an integer in the range Number.MIN_SAFE_INTEGER to Number.MAX_SAFE_INTEGER")},declaredOut:z.integer})},{name:"string.integer"}),B3=I(/^[\dA-Fa-f]+$/,"hex characters only"),M3=T.module({root:I(/^(?:[\d+/A-Za-z]{4})*(?:[\d+/A-Za-z]{2}==|[\d+/A-Za-z]{3}=)?$/,"base64-encoded"),url:I(/^(?:[\w-]{4})*(?:[\w-]{2}(?:==|%3D%3D)?|[\w-]{3}(?:=|%3D)?)?$/,"base64url-encoded")},{name:"string.base64"}),bY=I(/^[A-Z].*$/,"capitalized"),T3=T.module({root:w({in:"string",morphs:(Q)=>Q.charAt(0).toUpperCase()+Q.slice(1),declaredOut:bY}),preformatted:bY},{name:"string.capitalize"}),D3=(Q)=>{let X=Q.replace(/[ -]+/g,""),Y=0,U,Z,W=!1;for(let G=X.length-1;G>=0;G--){if(U=X.substring(G,G+1),Z=Number.parseInt(U,10),W)Z*=2,Y+=Z>=10?Z%10+1:Z;else Y+=Z;W=!W}return!!(Y%10===0?X:!1)},R3=/^(?:4\d{12}(?:\d{3,6})?|5[1-5]\d{14}|(222[1-9]|22[3-9]\d|2[3-6]\d{2}|27[01]\d|2720)\d{12}|6(?:011|5\d\d)\d{12,15}|3[47]\d{13}|3(?:0[0-5]|[68]\d)\d{11}|(?:2131|1800|35\d{3})\d{11}|6[27]\d{14}|^(81\d{14,17}))$/,C3=w({domain:"string",pattern:{meta:"a credit card number",rule:R3.source},predicate:{meta:"a credit card number",predicate:D3}});var w3=/^([+-]?\d{4}(?!\d{2}\b))((-?)((0[1-9]|1[0-2])(\3([12]\d|0[1-9]|3[01]))?|W([0-4]\d|5[0-3])(-?[1-7])?|(00[1-9]|0[1-9]\d|[12]\d{2}|3([0-5]\d|6[1-6])))(T((([01]\d|2[0-3])((:?)[0-5]\d)?|24:?00)([,.]\d+(?!:))?)?(\17[0-5]\d([,.]\d+)?)?([Zz]|([+-])([01]\d|2[0-3]):?([0-5]\d)?)?)?)?$/;var K3=(Q)=>!Number.isNaN(new Date(Q).valueOf()),yY=w({domain:"string",predicate:{meta:"a parsable date",predicate:K3}}).assertHasKind("intersection"),fY=lY.root.internal.narrow((Q,X)=>{let Y=Number.parseInt(Q),U=A6.epoch(Y);if(U instanceof d)return X.errors.merge(U),!1;return!0}).configure({description:"an integer string representing a safe Unix timestamp"},"self").assertHasKind("intersection"),P3=T.module({root:fY,parse:w({in:fY,morphs:(Q)=>new Date(Q),declaredOut:z.Date})},{name:"string.date.epoch"}),vY=I(w3,"an ISO 8601 (YYYY-MM-DDTHH:mm:ss.sssZ) date").internal.assertHasKind("intersection"),N3=T.module({root:vY,parse:w({in:vY,morphs:(Q)=>new Date(Q),declaredOut:z.Date})},{name:"string.date.iso"}),E3=T.module({root:yY,parse:w({declaredIn:yY,in:"string",morphs:(Q,X)=>{let Y=new Date(Q);if(Number.isNaN(Y.valueOf()))return X.error("a parsable date");return Y},declaredOut:z.Date}),iso:N3,epoch:P3},{name:"string.date"}),I3=I(/^[\w%+.-]+@[\d.A-Za-z-]+\.[A-Za-z]{2,}$/,"an email address","email"),kY="(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])",K1=`(${kY}[.]){3}${kY}`,S3=new RegExp(`^${K1}$`),j="(?:[0-9a-fA-F]{1,4})",j3=new RegExp(`^((?:${j}:){7}(?:${j}|:)|(?:${j}:){6}(?:${K1}|:${j}|:)|(?:${j}:){5}(?::${K1}|(:${j}){1,2}|:)|(?:${j}:){4}(?:(:${j}){0,1}:${K1}|(:${j}){1,3}|:)|(?:${j}:){3}(?:(:${j}){0,2}:${K1}|(:${j}){1,4}|:)|(?:${j}:){2}(?:(:${j}){0,3}:${K1}|(:${j}){1,5}|:)|(?:${j}:){1}(?:(:${j}){0,4}:${K1}|(:${j}){1,6}|:)|(?::((?::${j}){0,5}:${K1}|(?::${j}){1,7}|:)))(%[0-9a-zA-Z.]{1,})?$`),b3=T.module({root:["v4 | v6","@","an IP address"],v4:I(S3,"an IPv4 address","ipv4"),v6:I(j3,"an IPv6 address","ipv6")},{name:"string.ip"}),Q2="a JSON string",dY=(Q)=>{if(!(Q instanceof SyntaxError))throw Q;return`must be ${Q2} (${Q})`},y3=w({meta:Q2,domain:"string",predicate:{meta:Q2,predicate:(Q,X)=>{try{return JSON.parse(Q),!0}catch(Y){return X.reject({code:"predicate",expected:Q2,problem:dY(Y)})}}}}),f3=(Q,X)=>{if(Q.length===0)return X.error({code:"predicate",expected:Q2,actual:"empty"});try{return JSON.parse(Q)}catch(Y){return X.error({code:"predicate",expected:Q2,problem:dY(Y)})}},v3=T.module({root:y3,parse:w({meta:"safe JSON string parser",in:"string",morphs:f3,declaredOut:z.jsonObject})},{name:"string.json"}),gY=I(/^[a-z]*$/,"only lowercase letters"),k3=T.module({root:w({in:"string",morphs:(Q)=>Q.toLowerCase(),declaredOut:gY}),preformatted:gY},{name:"string.lower"}),cY=["NFC","NFD","NFKC","NFKD"],v2=V(cY,(Q,X)=>[X,w({domain:"string",predicate:(Y)=>Y.normalize(X)===Y,meta:`${X}-normalized unicode`})]),z6=V(cY,(Q,X)=>[X,w({in:"string",morphs:(Y)=>Y.normalize(X),declaredOut:v2[X]})]),g3=T.module({root:z6.NFC,preformatted:v2.NFC},{name:"string.normalize.NFC"}),x3=T.module({root:z6.NFD,preformatted:v2.NFD},{name:"string.normalize.NFD"}),h3=T.module({root:z6.NFKC,preformatted:v2.NFKC},{name:"string.normalize.NFKC"}),p3=T.module({root:z6.NFKD,preformatted:v2.NFKD},{name:"string.normalize.NFKD"}),u3=T.module({root:"NFC",NFC:g3,NFD:x3,NFKC:h3,NFKD:p3},{name:"string.normalize"}),xY=I(h2,"a well-formed numeric string"),m3=T.module({root:xY,parse:w({in:xY,morphs:(Q)=>Number.parseFloat(Q),declaredOut:z.number})},{name:"string.numeric"}),hY="a regex pattern",l3=w({domain:"string",predicate:{meta:hY,predicate:(Q,X)=>{try{return new RegExp(Q),!0}catch(Y){return X.reject({code:"predicate",expected:hY,problem:String(Y)})}}},meta:{format:"regex"}}),d3=/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[A-Za-z-][\dA-Za-z-]*)(?:\.(?:0|[1-9]\d*|\d*[A-Za-z-][\dA-Za-z-]*))*))?(?:\+([\dA-Za-z-]+(?:\.[\dA-Za-z-]+)*))?$/,c3=I(d3,"a semantic version (see https://semver.org/)"),pY=I(/^\S.*\S$|^\S?$/,"trimmed"),o3=T.module({root:w({in:"string",morphs:(Q)=>Q.trim(),declaredOut:pY}),preformatted:pY},{name:"string.trim"}),uY=I(/^[A-Z]*$/,"only uppercase letters"),i3=T.module({root:w({in:"string",morphs:(Q)=>Q.toUpperCase(),declaredOut:uY}),preformatted:uY},{name:"string.upper"}),s3=(Q)=>URL.canParse(Q),mY=w({domain:"string",predicate:{meta:"a URL string",predicate:s3},meta:{format:"uri"}}),n3=T.module({root:mY,parse:w({declaredIn:mY,in:"string",morphs:(Q,X)=>{try{return new URL(Q)}catch{return X.error("a URL string")}},declaredOut:w(URL)})},{name:"string.url"}),r3=T.module({root:["versioned | nil | max","@",{description:"a UUID",format:"uuid"}],"#nil":"'00000000-0000-0000-0000-000000000000'","#max":"'ffffffff-ffff-ffff-ffff-ffffffffffff'","#versioned":/[\da-f]{8}-[\da-f]{4}-[1-8][\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}/i,v1:I(/^[\da-f]{8}-[\da-f]{4}-1[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv1"),v2:I(/^[\da-f]{8}-[\da-f]{4}-2[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv2"),v3:I(/^[\da-f]{8}-[\da-f]{4}-3[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv3"),v4:I(/^[\da-f]{8}-[\da-f]{4}-4[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv4"),v5:I(/^[\da-f]{8}-[\da-f]{4}-5[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv5"),v6:I(/^[\da-f]{8}-[\da-f]{4}-6[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv6"),v7:I(/^[\da-f]{8}-[\da-f]{4}-7[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv7"),v8:I(/^[\da-f]{8}-[\da-f]{4}-8[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv8")},{name:"string.uuid"}),oY=T.module({root:z.string,alpha:I(/^[A-Za-z]*$/,"only letters"),alphanumeric:I(/^[\dA-Za-z]*$/,"only letters and digits 0-9"),hex:B3,base64:M3,capitalize:T3,creditCard:C3,date:E3,digits:I(/^\d*$/,"only digits 0-9"),email:I3,integer:lY,ip:b3,json:v3,lower:k3,normalize:u3,numeric:m3,regex:l3,semver:c3,trim:o3,upper:i3,url:n3,uuid:r3},{name:"string"});var iY=T.module({bigint:z.bigint,boolean:z.boolean,false:z.false,never:z.never,null:z.null,number:z.number,object:z.object,string:z.string,symbol:z.symbol,true:z.true,unknown:z.unknown,undefined:z.undefined}),sY=T.module({root:z.unknown,any:z.unknown},{name:"unknown"}),t3=T.module({root:z.jsonObject,stringify:r1("morph",{in:z.jsonObject,morphs:(Q)=>JSON.stringify(Q),declaredOut:z.string})},{name:"object.json"}),nY=T.module({root:z.object,json:t3},{name:"object"});class rY extends k{description='instantiate an object from an index signature and corresponding value type like `Record("string", "number")`'}var a3=e(["K",z.key],"V")((Q)=>({domain:"object",index:{signature:Q.K,value:Q.V}}),rY);class tY extends k{description='pick a set of properties from an object like `Pick(User, "name | age")`'}var e3=e(["T",z.object],["K",z.key])((Q)=>Q.T.pick(Q.K),tY);class aY extends k{description='omit a set of properties from an object like `Omit(User, "age")`'}var Q9=e(["T",z.object],["K",z.key])((Q)=>Q.T.omit(Q.K),aY);class eY extends k{description="make all named properties of an object optional like `Partial(User)`"}var X9=e(["T",z.object])((Q)=>Q.T.partial(),eY);class QU extends k{description="make all named properties of an object required like `Required(User)`"}var Y9=e(["T",z.object])((Q)=>Q.T.required(),QU);class XU extends k{description='exclude branches of a union like `Exclude("boolean", "true")`'}var U9=e("T","U")((Q)=>Q.T.exclude(Q.U),XU);class YU extends k{description='extract branches of a union like `Extract("0 | false | 1", "number")`'}var Z9=e("T","U")((Q)=>Q.T.extract(Q.U),YU),UU=T.module({Exclude:U9,Extract:Z9,Omit:Q9,Partial:X9,Pick:e3,Record:a3,Required:Y9});var V1=f2({...iY,...UU,...SY,...wY,string:oY,number:A6,object:nY,unknown:sY},{prereducedAliases:!0,name:"ark"}),v=V1.export();Object.assign(e1.ambient,v);e1.typeAttachments={string:v.string.root,number:v.number.root,bigint:v.bigint,boolean:v.boolean,symbol:v.symbol,undefined:v.undefined,null:v.null,object:v.object.root,unknown:v.unknown.root,false:v.false,true:v.true,never:v.never,arrayIndex:v.Array.index,Key:v.Key,Record:v.Record,Array:v.Array.root,Date:v.Date};var kQ=Object.assign(V1.type,e1.typeAttachments),W9=V1.match,G9=V1.fn,_9=V1.generic,Nq=V1.schema,J9=V1.define,L9=V1.declare;var y1=f2({Operator:"'EQ' | '==' | 'NEQ' | '!=' | 'GT' | '>' | 'GTE' | '>=' | 'LT' | '<' | 'LTE' | '<=' | 'IN' | 'NOT_IN' | 'CONTAINS' | 'MATCHES' | 'RANGE' | 'SINCE' | 'AFTER' | 'BEFORE' | 'UNTIL'",Condition:"RangeCondition | ListCondition | ContainsCondition | NumericCondition | RegexCondition | BasicCondition",RangeCondition:{field:"string > 0",operator:"'RANGE'",value:"unknown[] == 2"},ListCondition:{field:"string > 0",operator:"'IN' | 'NOT_IN'",value:"unknown[]"},ContainsCondition:{field:"string > 0",operator:"'CONTAINS'",value:"string | unknown[]"},NumericCondition:{field:"string > 0",operator:"'>' | '>=' | '<' | '<=' | 'GT' | 'GTE' | 'LT' | 'LTE'",value:"number | string"},RegexCondition:{field:"string > 0",operator:"'MATCHES'",value:"string"},BasicCondition:{field:"string > 0",operator:"Operator",value:"unknown"},ConditionGroup:{operator:"'AND' | 'OR'",conditions:"(Condition | ConditionGroup)[] >= 1"},RuleCondition:"Condition | ConditionGroup",Action:{type:"string > 0","params?":"object","delay?":"number.integer >= 0","probability?":"0 <= number <= 1"},ActionGroup:{"mode?":"'ALL' | 'EITHER' | 'SEQUENCE'",actions:"(Action | ActionGroup)[] >= 1"},RuleAction:"Action | ActionGroup",TriggerRule:{id:"string > 0","name?":"string","description?":"string","priority?":"number.integer","enabled?":"boolean","cooldown?":"number.integer >= 0","tags?":"string[]",on:"string > 0","if?":"RuleCondition | RuleCondition[]",do:"RuleAction | RuleAction[]","comment?":"string"}}).export(),cq=y1.Operator,oq=y1.Condition,iq=y1.ConditionGroup,sq=y1.RuleCondition,nq=y1.Action,rq=y1.ActionGroup,H9=y1.TriggerRule;class F9{static validate(Q){let X=H9(Q);if(X instanceof kQ.errors){let Z=[];for(let W of X){let G=W.path.join("."),_=W.message,H=void 0;if(G.endsWith("on")&&(_.includes("string")||_.includes("must be")))if(typeof Q==="object"&&Q!==null&&"on"in Q&&Q.on===!0)_="The 'on' field is incorrect (boolean true found).",H=`In YAML, 'on' is a boolean keyword (true). Quote it: "on": "EventName"`;else H="Ensure 'on' is a string event name.";Z.push({path:G,message:_,suggestion:H,severity:"error"})}return{valid:!1,issues:Z}}let Y=X,U=[];if(this.validateConditionsRecursive(Y.if,U,"if"),U.length>0)return{valid:!1,issues:U};return{valid:!0,rule:Y}}static validateConditionsRecursive(Q,X,Y){if(!Q)return;if(Array.isArray(Q)){Q.forEach((U,Z)=>{this.validateConditionsRecursive(U,X,`${Y}.${Z}`)});return}if(typeof Q==="object"&&Q!==null&&"conditions"in Q&&Array.isArray(Q.conditions)){Q.conditions.forEach((U,Z)=>{this.validateConditionsRecursive(U,X,`${Y}.conditions.${Z}`)});return}if(typeof Q==="object"&&Q!==null&&"operator"in Q&&"value"in Q)this.validateConditionValue(Q,X,Y)}static validateConditionValue(Q,X,Y){let{operator:U,value:Z}=Q;if(typeof U==="string"&&["IN","NOT_IN","RANGE","CONTAINS"].includes(U)){if(U==="CONTAINS"){if(typeof Z!=="string"&&!Array.isArray(Z))X.push({path:`${Y}.value`,message:`Incorrect value type: Operator 'CONTAINS' expects a String or List (Array), but received ${typeof Z}.`,suggestion:"Use a substring or a list of items.",severity:"error"});return}if(!Array.isArray(Z)){X.push({path:`${Y}.value`,message:`Incorrect value type: Operator '${U}' expects a List (Array), but received ${typeof Z}.`,suggestion:U==="RANGE"?"Use format [min, max]":"Use format [item1, item2]",severity:"error"});return}if(U==="RANGE"){if(Z.length!==2)X.push({path:`${Y}.value`,message:"Invalid Range: Operator 'RANGE' requires exactly 2 values (min and max).",suggestion:"Use format [min, max], e.g. [1, 10]",severity:"error"});else if(typeof Z[0]!=="number"&&typeof Z[0]!=="string")X.push({path:`${Y}.value`,message:"Incorrect range type: Range values must be numbers or expression strings.",severity:"error"})}}else if(U==="MATCHES")if(typeof Z!=="string")X.push({path:`${Y}.value`,message:`Incorrect value type: Operator 'MATCHES' expects a string (regex pattern), but received ${typeof Z}.`,severity:"error"});else try{new RegExp(Z)}catch(W){X.push({path:`${Y}.value`,message:`Invalid Regex pattern: ${W.message}`,severity:"error"})}else if(typeof U==="string"&&["GT","GTE","LT","LTE",">",">=","<","<="].includes(U)){if(typeof Z!=="number"&&typeof Z!=="string")X.push({path:`${Y}.value`,message:`Incorrect value type: Operator '${U}' expects a number or expression string, but received ${typeof Z}.`,severity:"error"})}}}export{F9 as TriggerValidator,Y2 as TriggerUtils,H9 as TriggerRuleSchema,W2 as TriggerEngine,Q1 as StateManager,T6 as RuleEngine,sq as RuleConditionSchema,B6 as InMemoryPersistence,i as ExpressionEngine,JU as EventQueue,W2 as Engine,HU as ContextAdapter,oq as ConditionSchema,iq as ConditionGroupSchema,cq as ComparisonOperatorSchema,hQ as BrowserPersistence,T6 as AdvancedRuleEngine,nq as ActionSchema,v1 as ActionRegistry,rq as ActionGroupSchema};
|
|
47
47
|
|
|
48
|
-
//# debugId=
|
|
48
|
+
//# debugId=B879CD189408322364756E2164756E21
|